# --- Engrams Memory Strategy for Cursor ---
# Install: Place this content in your Cursor settings under Rules for AI,
# or save as .cursorrules in your project root.
# Cursor supports MCP servers — configure Engrams MCP in Cursor Settings → MCP Servers.
engrams_memory_strategy:
  # CRITICAL: At the beginning of every session, the agent MUST execute the 'initialization' sequence
  # to determine the Engrams status and load relevant context.
  # CRITICAL: NO task that mutates the workspace (file creation, modification, deletion, code generation,
  # or architectural decisions) may begin until [ENGRAMS_ACTIVE] is confirmed AND the
  # 'pre_task_governance_check' sequence has been completed without finding a blocking conflict.
  workspace_id_source: "The agent must obtain the absolute path to the current workspace to use as `workspace_id` for all Engrams tool calls. This might be available as `${workspaceFolder}` or require asking the user."

  initialization:
    thinking_preamble: |

    agent_action_plan:
      - step: 1
        action: "Determine `ACTUAL_WORKSPACE_ID`."
      - step: 2
        action: "Invoke a \"list files\" tool for `ACTUAL_WORKSPACE_ID + \"/engrams/\"`."
        parameters: 'path: ACTUAL_WORKSPACE_ID + "/engrams/"'
      - step: 3
        action: "Analyze result and branch based on 'context.db' existence."
        conditions:
          - if: "'context.db' is found"
            then_sequence: "load_existing_engrams_context"
          - else: "'context.db' NOT found"
            then_sequence: "handle_new_engrams_setup"

  load_existing_engrams_context:
    thinking_preamble: |

    agent_action_plan:
      - step: 1
        description: "Attempt to load initial contexts from Engrams."
        actions:
          - "Invoke `get_product_context`... Store result."
          - "Invoke `get_active_context`... Store result."
          - "Invoke `get_decisions` (limit 5 for a better overview)... Store result."
          - "Invoke `get_progress` (limit 5)... Store result."
          - "Invoke `get_system_patterns` (limit 5)... Store result."
          - "Invoke `get_custom_data` (category: \"critical_settings\")... Store result."
          - "Invoke `get_custom_data` (category: \"ProjectGlossary\")... Store result."
          - "Invoke `get_recent_activity_summary` (default params, e.g., last 24h, limit 3 per type) for a quick catch-up. Store result."
      - step: 2
        description: "Analyze loaded context."
        conditions:
          - if: "results from step 1 are NOT empty/minimal"
            actions:
              - "Set internal status to [ENGRAMS_ACTIVE]."
              - "Inform user: \"Engrams memory initialized. Existing contexts and recent activity loaded.\""
              - "Ask follow up questions with suggestions like \"Review recent activity?\", \"Continue previous task?\", \"What would you like to work on?\"."
          - else: "loaded context is empty/minimal despite DB file existing"
            actions:
              - "Set internal status to [ENGRAMS_ACTIVE]."
              - "Inform user: \"Engrams database file found, but it appears to be empty or minimally initialized. You can start by defining Product/Active Context or logging project information.\""
              - "Ask follow up questions with suggestions like \"Define Product Context?\", \"Log a new decision?\"."
      - step: 3
        description: "Handle Load Failure (if step 1's `get_*` calls failed)."
        condition: "If any `get_*` calls in step 1 failed unexpectedly"
        action: "Fall back to `if_engrams_unavailable_or_init_failed`."

  handle_new_engrams_setup:
    thinking_preamble: |

    agent_action_plan:
      - step: 1
        action: "Inform user: \"No existing Engrams database found at `ACTUAL_WORKSPACE_ID + \"/engrams/context.db\"`.\""
      - step: 2
        action: "Ask follow up questions"
        parameters:
          question: "Would you like to initialize a new Engrams database for this workspace? The database will be created automatically when Engrams tools are first used."
          suggestions:
            - "Yes, initialize a new Engrams database."
            - "No, do not use Engrams for this session."
      - step: 3
        description: "Process user response."
        conditions:
          - if_user_response_is: "Yes, initialize a new Engrams database."
            actions:
              - "Inform user: \"Okay, a new Engrams database will be created.\""
              - description: "Attempt to bootstrap Product Context from projectBrief.md (this happens only on new setup)."
                thinking_preamble: |

                sub_steps:
                  - "Invoke `list_files` with `path: ACTUAL_WORKSPACE_ID` (non-recursive, just to check root)."
                  - description: "Analyze `list_files` result for 'projectBrief.md'."
                    conditions:
                      - if: "'projectBrief.md' is found in the listing"
                        actions:
                          - "Invoke `read_file` for `ACTUAL_WORKSPACE_ID + \"/projectBrief.md\"`."
                          - action: "Ask follow up questions"
                            parameters:
                              question: "Found projectBrief.md in your workspace. As we're setting up Engrams for the first time, would you like to import its content into the Product Context?"
                              suggestions:
                                - "Yes, import its content now."
                                - "No, skip importing it for now."
                          - description: "Process user response to import projectBrief.md."
                            conditions:
                              - if_user_response_is: "Yes, import its content now."
                                actions:
                                  - "(No need to `get_product_context` as DB is new and empty)"
                                  - "Prepare `content` for `update_product_context`. For example: `{\"initial_product_brief\": \"[content from projectBrief.md]\"}`."
                                  - "Invoke `update_product_context` with the prepared content."
                                  - "Inform user of the import result (success or failure)."
                      - else: "'projectBrief.md' NOT found"
                        actions:
                          - action: "Ask follow up questions."
                            parameters:
                              question: "`projectBrief.md` was not found in the workspace root. Would you like to define the initial Product Context manually now?"
                              suggestions:
                                - "Define Product Context manually."
                                - "Skip for now."
                          - "(If \"Define manually\", guide user through `update_product_context`)."
              - "Proceed to 'post_task_setup_questionnaire' sequence to configure project-specific verification checks."
          - if_user_response_is: "No, do not use Engrams for this session."
            action: "Proceed to `if_engrams_unavailable_or_init_failed` (with a message indicating user chose not to initialize)."

  post_task_setup_questionnaire:
    description: |
      Runs during first-time Engrams setup to configure project-specific verification checks
      that will be automatically executed as part of the post_task_completion gate.
      The agent auto-detects the project type and suggests relevant checks.
    trigger: "During handle_new_engrams_setup, after projectBrief import and DB initialization."
    steps:
      - step: 1
        action: "Auto-detect project type by scanning workspace root for manifest files."
        detection_rules:
          - indicator: "package.json"
            suggests: ["npm test", "npm run lint", "npm run build", "npx tsc --noEmit"]
            project_type: "Node.js/TypeScript"
          - indicator: "pyproject.toml OR requirements.txt OR setup.py"
            suggests: ["pytest", "flake8 .", "mypy .", "python -m py_compile"]
            project_type: "Python"
          - indicator: "Cargo.toml"
            suggests: ["cargo check", "cargo test", "cargo clippy"]
            project_type: "Rust"
          - indicator: "go.mod"
            suggests: ["go test ./...", "go vet ./...", "golangci-lint run"]
            project_type: "Go"
          - indicator: "pom.xml OR build.gradle"
            suggests: ["mvn test", "mvn compile", "gradle test", "gradle build"]
            project_type: "Java/JVM"
          - indicator: "Gemfile"
            suggests: ["bundle exec rspec", "bundle exec rubocop"]
            project_type: "Ruby"
          - indicator: "composer.json"
            suggests: ["composer test", "php -l", "phpstan analyse"]
            project_type: "PHP"
      - step: 2
        action: "Present detected project type and suggested checks to the user."
      - step: 3
        action: "If user wants to customize, present each check individually."
      - step: 4
        action: "Store the configured checks in Engrams as custom_data."
        tool_to_use: "log_custom_data"
        parameters: { category: "post_task_checks", key: "verification_commands" }
      - step: 5
        action: "Log a decision recording the post-task check configuration."
        tool_to_use: "log_decision"
        parameters: { summary: "Configured post-task verification checks", tags: ["post-task-checks", "project-setup", "dx"] }
      - step: 6
        action: "Proceed to 'load_existing_engrams_context' sequence."

  if_engrams_unavailable_or_init_failed:
    thinking_preamble: |

    agent_action: "Inform user: \"Engrams memory will not be used for this session. Status: [ENGRAMS_INACTIVE].\""

  general:
    status_prefix: "Begin EVERY response with either '[ENGRAMS_ACTIVE]' or '[ENGRAMS_INACTIVE]'."
    proactive_logging_cue: "Proactively log decisions, progress, and context changes to Engrams throughout the conversation. Do NOT wait for the user to ask — if a decision was made, a task completed, or context changed, log it automatically as part of the workflow."
    proactive_error_handling: "When encountering errors (e.g., tool failures, unexpected output), proactively log the error details using `log_custom_data` (category: 'ErrorLogs', key: 'timestamp_error_summary') and consider updating active context with open issues if it's a persistent problem. Prioritize using Engrams's item history or recent activity summary to diagnose issues if they relate to past context changes."
    semantic_search_emphasis: "For complex or nuanced queries, especially when direct keyword search might be insufficient, prioritize using semantic search to leverage conceptual understanding and retrieve more relevant context. Explain to the user why semantic search is being used."
    merged_tools_note: |
      The following tools have been merged into unified interfaces:
      - To delete any item: use `delete_item` with item_type + item_id (or category+key for custom_data)
      - To check binding staleness: use `verify_bindings` with `mode='staleness'`
      - To preview context size without retrieving: use `get_relevant_context` with `dry_run=True`
      - To check briefing freshness without generating: use `get_project_briefing` with `staleness_only=True`
      - To manage budget weights: use `manage_budget_config`
      - To search glossary: use `search_custom_data_value_fts` with `category_filter='ProjectGlossary'`

  pre_task_governance_check:
    description: |
      MANDATORY gate that MUST run before executing any task that creates, modifies, or deletes files,
      generates code, or makes architectural decisions. Engrams MUST be [ENGRAMS_ACTIVE] before this
      check can proceed. If status is [ENGRAMS_INACTIVE], run the initialization sequence first.
    trigger: "Before ANY workspace-mutating action: file creation, modification, deletion, code generation, or architectural decisions."
    mandatory: true
    steps:
      - step: 1
        action: "Verify Engrams is [ENGRAMS_ACTIVE]. If not, complete the initialization sequence before proceeding."
      - step: 2
        action: "Invoke `get_decisions` (limit 20) to retrieve all team decisions. Scan results for any decision that constrains the planned task (e.g., file naming rules, prohibited patterns, required workflows)."
      - step: 3
        action: "Invoke `get_scopes` to check whether governance scopes are configured in this workspace."
      - step: 4
        action: "If scopes exist, invoke `get_governance_rules` for each relevant scope to retrieve `hard_block` and `soft_warn` rules applicable to the task type."
      - step: 5
        action: "Evaluate whether the planned task violates any loaded decision or governance rule."
        conditions:
          - if: "A conflict is found (a decision prohibits the action, OR a hard_block governance rule applies)"
            then: "STOP. Do NOT proceed. Inform the user of the conflict, citing the specific item by ID and summary. Require explicit override confirmation before taking any action."
          - elif: "A soft_warn rule applies"
            then: "Inform the user of the concern and the matched rule. Proceed only after the user explicitly acknowledges."
          - else: "No conflict found"
            then: "Proceed with the task as planned."
    efficiency_note: "As an alternative to steps 2-4, invoke `get_relevant_context` with a `task_description` describing the planned action and a modest `token_budget` (e.g., 2000 tokens). This surfaces relevant decisions and governance items in a single call."

  post_task_completion:
    description: |
      MANDATORY gate that MUST run BEFORE presenting final results. When Engrams is [ENGRAMS_ACTIVE],
      the agent must: (1) run any configured project verification checks, (2) log all significant
      outcomes to Engrams, then (3) present results to the user.
    trigger: "Before presenting final task results when Engrams is [ENGRAMS_ACTIVE]."
    mandatory: true
    steps:
      - step: 1
        action: "Load project verification checks from Engrams."
        tool_to_use: "get_custom_data"
        parameters: { category: "post_task_checks", key: "verification_commands" }
        on_missing: "Skip to step 4 (no checks configured)."
      - step: 2
        action: "Execute each enabled check command via terminal."
        sub_steps:
          - "If severity is 'blocking' and check fails: STOP. Inform user. Do NOT present as complete."
          - "If severity is 'warning' and check fails: Note warning, continue."
      - step: 3
        action: "Summarize check results. If all passed, proceed. If any blocking check failed, halt and report."
      - step: 4
        action: "Review the work just completed. Identify decisions, task status changes, patterns, context changes."
      - step: 5
        action: "Log each decision using `log_decision` with summary, rationale, and implementation_details."
      - step: 6
        action: "Log or update progress using `log_progress` or `update_progress` to reflect task completion."
      - step: 7
        action: "If the current work focus or active context changed, update it via `update_active_context` with `patch_content`."
      - step: 8
        action: "Identify and log any new relationships between items using `link_engrams_items`."
      - step: 9
        action: "Only after all checks pass and all Engrams updates are complete, present the final result."

  engrams_sync_routine:
    trigger: "^(Sync Engrams|Engrams Sync)$"
    user_acknowledgement_text: "[ENGRAMS_SYNCING]"
    instructions:
      - "Halt Current Task: Stop current activity."
      - "Acknowledge Command: Send `[ENGRAMS_SYNCING]` to the user."
      - "Review Chat History: Analyze the complete current chat session for new information, decisions, progress, context changes, clarifications, and potential new relationships between items."
    core_update_process:
      thinking_preamble: |
        - Synchronize Engrams with information from the current chat session.
        - Use appropriate Engrams tools based on identified changes.
        - For `update_product_context` and `update_active_context`, first fetch current content, then merge/update (potentially using `patch_content`), then call the update tool with the *complete new content object* or the patch.
        - All tool calls require the `workspace_id`.
      agent_action_plan_illustrative:
        - "Log new decisions (use `log_decision`)."
        - "Log task progress/status changes (use `log_progress`)."
        - "Update existing progress entries (use `update_progress`)."
        - "Log new system patterns (use `log_system_pattern`)."
        - "Update Active Context (use `get_active_context` then `update_active_context` with full or patch)."
        - "Update Product Context if significant changes (use `get_product_context` then `update_product_context` with full or patch)."
        - "Log new custom context, including ProjectGlossary terms (use `log_custom_data`)."
        - "Identify and log new relationships between items (use `link_engrams_items`)."
        - "If many items of the same type were discussed, consider `batch_log_items`."
        - "After updates, consider a brief `get_recent_activity_summary` to confirm and refresh understanding."
    post_sync_actions:
      - "Inform user: Engrams synchronized with session info."
      - "Resume previous task or await new instructions."

  proactive_knowledge_graph_linking:
    description: |
      Guidance for the AI to proactively identify and suggest the creation of links between Engrams items,
      enriching the project's knowledge graph based on conversational context.
    trigger: "During ongoing conversation, when the AI observes potential relationships (e.g., causal, implementational, clarifying) between two or more discussed Engrams items or concepts that are likely represented as Engrams items."
    goal: "To actively build and maintain a rich, interconnected knowledge graph within Engrams by capturing relationships that might otherwise be missed."
    steps:
      - step: 1
        action: "Monitor Conversational Context"
        details: "Continuously analyze the user's statements and the flow of discussion for mentions of Engrams items (explicitly by ID, or implicitly by well-known names/summaries) and the relationships being described or implied between them."
      - step: 2
        action: "Identify Potential Links"
        details: |
          Look for patterns such as:
          - User states "Decision X led to us doing Y (which is Progress item P-3)."
          - User discusses how System Pattern SP-2 helps address a concern noted in Decision D-5.
          - User outlines a task (Progress P-10) that implements a specific feature detailed in a `custom_data` spec (CD-Spec-FeatureX).
      - step: 3
        action: "Formulate and Propose Link Suggestion"
        details: |
          If a potential link is identified:
          - Clearly state the items involved (e.g., "Decision D-5", "System Pattern SP-2").
          - Describe the perceived relationship (e.g., "It seems SP-2 addresses a concern in D-5.").
          - Propose creating a link.
          - Offer common relationship types as examples: 'implements', 'clarifies', 'related_to', 'depends_on', 'blocks', 'resolves', 'derived_from'.
      - step: 4
        action: "Gather Details and Execute Linking"
        details: |
          If the user confirms:
          - Ensure you have the correct source item type, source item ID, target item type, target item ID, and the agreed-upon relationship type.
          - Ask for an optional brief description for the link if the relationship isn't obvious.
          - Invoke the `link_engrams_items` tool.
      - step: 5
        action: "Confirm Outcome"
        details: "Inform the user of the success or failure of the `link_engrams_items` tool call."
    general_principles:
      - "Be helpful, not intrusive. If the user declines a suggestion, accept and move on."
      - "Prioritize clear, strong relationships over tenuous ones."
      - "This strategy complements the general `proactive_logging_cue` by providing specific guidance for link creation."
