### Manual Project Installation Source: https://github.com/ctxr-dev/memory/blob/main/README.md Installs the memory project from source and starts the associated services. The first run is slow due to cloning the upstream Dify repository and pulling Docker images. ```bash # from inside the project root git clone https://github.com/ctxr-dev/memory ./.memory/src ./.memory/src/bootstrap.sh --slug ./.memory/src/scripts/up.sh # FIRST RUN IS SLOW: clones the upstream Dify repo # into .memory/src/vendor/dify, pulls Dify images, and # builds the bridge. First-run cold pull is 2-5 min # multi-GB; warm cache is ~30-60s. up.sh prints # the Dify UI URL # at the end. ``` -------------------------------- ### Automated Dify Setup Script Source: https://github.com/ctxr-dev/memory/blob/main/README.md The `dify-setup.sh` script guides through Dify setup, including API key configuration, dataset slot creation, metadata schema installation, and bridge restarts. It can be re-run to manage new slots or overwrite existing documents. ```bash dify-setup.sh ``` -------------------------------- ### Manual Dify Onboarding Flow Source: https://github.com/ctxr-dev/memory/blob/main/README.md This sequence of commands outlines the manual steps for starting Dify and its bridge, opening the UI, configuring the embedding model, running the setup script, and performing a smoke test. ```bash ./.memory/src/scripts/up.sh ``` ```bash ./.memory/src/scripts/ui-url.sh ``` ```bash ./.memory/src/scripts/dify-setup.sh ``` ```bash ./.memory/src/scripts/mcp-smoke.sh ``` -------------------------------- ### Start Memory Stack Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md Execute this script to initialize and start the Dify and MCP memory stack. It handles Dify version resolution, cloning, environment setup, and launching services. ```bash ./.memory/src/scripts/up.sh ``` -------------------------------- ### AI Prompt for Host-Side Install Source: https://github.com/ctxr-dev/memory/blob/main/README.md Paste this prompt into your AI agent (Claude Code, Cursor, Codex) to initiate the host-side installation of the Dify MCP memory boilerplate. It guides the agent through cloning, bootstrapping, and Docker stack setup. ```text Install the local Dify MCP memory boilerplate into this project. Target the current working directory unless I explicitly give you another path. Steps: 1. Confirm the boilerplate Git URL with me first if you cannot infer it. Default: https://github.com/ctxr-dev/memory 2. Ask me for the project slug. Lowercase ASCII a-z, 0-9, hyphen (e.g. billing-api, docs-site). If I give you a name, propose a sanitised slug derived from the project folder name and confirm. The slug becomes the per-project Docker container, image, and Compose project name, so multiple projects can run their own memory stacks without collisions. 3. Ask me which LLM provider to use for the flush + compile pipeline: - claude (recommended; spawns `claude -p`, no API key needed) - codex (spawns `codex exec --json`, no API key needed) - anthropic (REST with ANTHROPIC_API_KEY in ./.memory/settings/.env) - openai (REST with OPENAI_API_KEY in ./.memory/settings/.env) Detect which CLIs are on PATH before asking. If only one is available, default to it and ask me to confirm. 4. Ask whether to install Claude Code hooks (default: yes). Hooks live in .claude/settings.json and wire SessionStart, PreCompact, PostCompact, SessionEnd, and PostToolUse (matcher ExitPlanMode, for auto-capturing approved plans into the `plans` slot) to ./.memory/src/scripts/hooks/. Other clients can adapt .agents/hooks.json manually. 5. Ask which MCP clients I want registered: Claude Desktop, Cursor, Codex/OpenAI, generic. Note the choices for step 8; the actual snippets only exist after bootstrap.sh runs. 6. Verify host prerequisites or tell me exactly what is missing: - docker (Docker Desktop or engine) with `docker compose` 2.24.4+ - node 20+ - git, curl, bash 3.2+ bootstrap.sh itself only enforces docker + node + docker-compose-version; git and curl are needed by `git clone` and the Dify-version probe. No `jq`, `realpath`, or other extras are required (the install path is intentionally portable to Git Bash on Windows). 7. Run the install. If I chose Codex/OpenAI as a client in step 5 AND the `codex` CLI is on PATH, append `--register-codex` so bootstrap auto-runs `codex mcp add` for me; otherwise tell me to run that command manually after step 8: git clone ./.memory/src ./.memory/src/bootstrap.sh --slug --llm-provider [--no-hooks if I declined] [--register-codex if Codex picked] 8. Static verification only (Docker not yet required; the stack is not up yet): bash -n ./.memory/src/bootstrap.sh ./.memory/src/scripts/*.sh ./.memory/src/scripts/hooks/*.sh node --check ./.memory/src/scripts/compile.mjs ./.memory/src/scripts/hooks/flush.mjs ./.memory/src/scripts/hooks/session-start.mjs node --check ./.memory/src/scripts/lib/*.mjs ./.memory/src/mcp-server/src/*.js ( cd ./.memory/src && npm test ) Then print the requested client snippets from `./.memory/src/.agents/clients/` (now that bootstrap has rendered them): ./.memory/src/scripts/mcp-config.sh all For Codex (if not auto-registered in step 7): codex mcp add -memory -- docker exec -i -memory node src/index.js 9. Start the stack. WARN ME this is slow on first run: dify-bootstrap clones the upstream Dify repo (~hundreds of MB) and `up.sh` then pulls and builds Dify + the bridge image (2-5 minutes on a cold pull, multi-GB; ~30-60s once the Docker image cache is warm): ./.memory/src/scripts/up.sh (`up.sh` invokes `ui-url.sh` itself, so the Dify UI URL is printed when it finishes.) 10. Tell me the exact next steps after the stack is up: a) Open the printed Dify UI URL. b) Create the admin account, configure an embedding model under Settings -> Model Provider (REQUIRED before any high_quality dataset can be created). c) Open Knowledge -> Service API, create a Knowledge API key. d) Restart your MCP client (Claude Desktop / Cursor / Codex / your terminal-spawned agent) so it picks up the new memory MCP server. The server only becomes callable after this restart. e) Run `./.memory/src/scripts/dify-setup.sh` to wire datasets, install the per-document metadata schema, and (optionally) absorb my existing docs. ALTERNATIVELY paste the second AI prompt from the README (under "Onboarding -> AI-driven flow") to a fresh agent session for an MCP-driven walkthrough that uses list_datasets / create_dataset / scan_documents / absorb_files instead of the wizard. f) Final end-to-end smoke (only valid after step e): `./.memory/src/scripts/mcp-smoke.sh` — read-only round-trip across get_memory_config, search_memory (plain + filtered), and recall_lessons. ``` -------------------------------- ### Example Dify UI URL Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md An example of the Dify UI URL format. The specific port will vary. ```text http://127.0.0.1:32774 ``` -------------------------------- ### AI-driven flow prompt for Dify memory setup Source: https://github.com/ctxr-dev/memory/blob/main/README.md This prompt guides an agent through setting up the Dify memory boilerplate. It requires Phase 1 to be completed first and the MCP client to be restarted. The prompt uses various MCP tools to configure Dify, manage datasets, absorb files, and perform sanity checks. ```text Set up the Dify memory boilerplate for this project. The MCP server is "-memory". Do this: 1. Call `get_memory_config` to confirm DIFY_KNOWLEDGE_API_KEY is set (the bridge surfaces `apiKeyConfigured: true|false` without leaking the key). If false, STOP and tell me to: (a) Open the Dify UI URL printed by ./.memory/src/scripts/ui-url.sh (b) Sign in, configure an embedding model under Settings → Model Provider (REQUIRED before any high_quality dataset can be created) (c) Knowledge → Service API → create a Knowledge API key (d) Paste the key into ./.memory/settings/.env as DIFY_KNOWLEDGE_API_KEY= (e) Recreate the bridge so the new env is picked up: ./.memory/src/scripts/up.sh memory_mcp THEN re-run me. Do not attempt to proceed without the key — `dify-setup.sh --non-interactive` will exit FATAL. 2. Call `list_datasets` to see what already exists in Dify. 3. For each of these slots (daily, knowledge, plans, investigations, self_improvement), check whether a dataset with that name already exists. - If it exists, tell me the id and ask whether to bind it. - If it does not, ask whether to call `create_dataset` to create it (high_quality + hybrid_search; requires the embedding model from step 1). 4. Tell me which DIFY_DATASET__ID values to put in ./.memory/settings/.env, then I will run `./.memory/src/scripts/dify-setup.sh --non-interactive --auto-create` to commit them, OR you tell me the exact lines to paste. The wizard also installs the per-document metadata schema (atom_type, tags, project_module, language, task_type, error_pattern) on every bound slot. 5. Then call `scan_documents` (default globs cover .md/.mdx/.markdown/.txt/.rst/.adoc) and show me the file list with proposed doc names. 6. Ask which subset I want absorbed and into which slot (default: knowledge). Use `absorb_files` with `dryRun=true` first, show me the result, and only do the real call after I confirm. 7. Sanity round-trip (proves the metadata schema you installed in step 4 actually works): call `save_lesson` with a deliberately-tagged smoke lesson (title "Onboarding smoke", error_pattern "smoke-test", project_module "smoke", task_type "unknown"), then immediately call `recall_lessons(query="smoke", project_module="smoke")`. The lesson must round-trip. If it does NOT, the metadata schema install probably failed; tell me to re-run `./.memory/src/scripts/dify-setup.sh`. 8. Tell me about the cleanup tools available. Three MCP tools handle retracting auto-captured / absorbed docs: `delete_document` (permanent, accepts any slot — use sparingly on lessons / compile-managed slots), `disable_document` (soft, hides from search but keeps audit trail), `enable_document` (reverses a disable). Mention these so I know how to clean up if a plan title changes (the auto-capture writes a doc under the new slug; the old slug stays unless I explicitly remove it). Stop and ask me whenever you would otherwise guess. This is configuration, not refactoring. ``` -------------------------------- ### Run Dify Setup Script Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md Execute the setup script to automatically configure Dify dataset IDs in the .env file. This script helps bind named slots to your Dify dataset IDs and can optionally absorb existing project documentation. ```bash ./.memory/src/scripts/dify-setup.sh ``` -------------------------------- ### Bootstrap Memory Installation Source: https://github.com/ctxr-dev/memory/blob/main/README.md Executes the bootstrap script to install the memory boilerplate. Requires project slug and LLM provider. Optionally registers Codex and skips hooks. ```bash ./.memory/src/bootstrap.sh --slug --llm-provider [--no-hooks if I declined] [--register-codex if Codex picked] ``` -------------------------------- ### Clone and Install Dependencies for Boilerplate Development Source: https://github.com/ctxr-dev/memory/blob/main/CONTRIBUTING.md Clone the repository and install dependencies for the bridge server when working on the boilerplate itself. The root of the project has no dependencies. ```bash git clone https://github.com/ctxr-dev/memory cd memory # Root has zero dependencies. The bridge has its own: ( cd mcp-server && npm install ) ``` -------------------------------- ### Upgrade to Plan-Capture Release Source: https://github.com/ctxr-dev/memory/blob/main/README.md Specific steps for upgrading to a plan-capture release, including re-running setup scripts, recreating the bridge container, and restarting clients. This ensures metadata schema is installed and environment changes are picked up. ```bash ./.memory/src/scripts/dify-setup.sh ``` ```bash ./.memory/src/scripts/up.sh memory_mcp ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/ctxr-dev/memory/blob/main/CONTRIBUTING.md Examples of commit messages following the Conventional Commits specification with a scope. This format helps in generating changelogs and understanding commit history. ```text feat(plan-capture): auto-capture approved plans to RAG via PostToolUse/ExitPlanMode fix(hooks): TTY guard so manual debug runs don't hang on stdin docs(readme): split atom-types table to avoid contradiction with prompts/flush.md ``` -------------------------------- ### Session Start Hook Script Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md Shell script for handling the session start lifecycle event. It expects optional session ID, current working directory, and hook event name. ```bash ./.memory/src/scripts/hooks/session-start.sh ``` -------------------------------- ### Clone Boilerplate Source: https://github.com/ctxr-dev/memory/blob/main/README.md Clones the memory boilerplate repository into the ./.memory/src directory. This is the initial step in the installation process. ```bash git clone ./.memory/src ``` -------------------------------- ### Recall Self-Improvement Lessons Source: https://github.com/ctxr-dev/memory/blob/main/templates/skills/self-improvement.md Call `recall_lessons` before starting a non-trivial task to search for relevant self-improvement lessons. Apply any returned lesson silently. If a lesson is applied, add a short line to your reply indicating this. ```typescript recall_lessons({ query: "", project_module: "", language: "", task_type: "", error_pattern: "" }) ``` -------------------------------- ### Cloning a Specific Tagged Release Source: https://github.com/ctxr-dev/memory/blob/main/RELEASING.md How downstream users can pin their installation to a specific tagged release for stability. This clones the repository at the specified tag. ```bash git clone --branch v0.1.0 https://github.com/ctxr-dev/memory ./.memory/src ``` -------------------------------- ### Live Bridge Verification Commands Source: https://github.com/ctxr-dev/memory/blob/main/RELEASING.md Optional but recommended steps to verify the release against a live bridge. These commands test read and write paths. ```bash ./scripts/up.sh memory_mcp ./scripts/mcp-smoke.sh ./scripts/plan-capture-smoke.sh ``` -------------------------------- ### Pre-tag Verification Commands Source: https://github.com/ctxr-dev/memory/blob/main/RELEASING.md Run these commands to verify the project's state before tagging a release. Ensure all tests pass and scripts are syntactically correct. ```bash cd /path/to/memory npm test bash -n bootstrap.sh scripts/*.sh scripts/hooks/*.sh node --check scripts/compile.mjs scripts/hooks/*.mjs scripts/lib/*.mjs mcp-server/src/*.js test/*.test.mjs test/lib/*.mjs ``` -------------------------------- ### Generate MCP Client Configs Source: https://github.com/ctxr-dev/memory/blob/main/README.md Generates client configuration snippets for MCP clients. Use 'all' to print every snippet or specify a client name like 'codex'. ```bash ./.memory/src/scripts/mcp-config.sh all ./.memory/src/scripts/mcp-config.sh codex ``` -------------------------------- ### Entry-Point Smoke Test for Hooks Source: https://github.com/ctxr-dev/memory/blob/main/README.md Verifies that hooks gracefully skip when prerequisites like bridge, slots, or LLM provider are missing. Requires bootstrap only. ```bash echo '{"session_id":"smoke","hook_event_name":"PostCompact","compact_summary":"Decision: Dify is the canonical store for project memory."}' \ | ./.memory/src/scripts/hooks/post-compact.sh node ./.memory/src/scripts/compile.mjs --dry-run ``` -------------------------------- ### Generate MCP Configuration Scripts Source: https://github.com/ctxr-dev/memory/blob/main/templates/agents/clients/README.md Use these shell scripts to generate MCP configuration files for different clients. Run 'all' to generate all available configurations. ```bash ./.memory/src/scripts/mcp-config.sh all ./.memory/src/scripts/mcp-config.sh codex ./.memory/src/scripts/mcp-config.sh codex-toml ./.memory/src/scripts/mcp-config.sh claude-desktop ./.memory/src/scripts/mcp-config.sh cursor ``` -------------------------------- ### End-to-End Smoke Test Source: https://github.com/ctxr-dev/memory/blob/main/README.md Performs a read-only round-trip test of memory configuration and search functionalities. This test is valid only after the Dify setup is complete. ```bash ./.memory/src/scripts/mcp-smoke.sh ``` -------------------------------- ### Run All Tests Source: https://github.com/ctxr-dev/memory/blob/main/CONTRIBUTING.md Execute the entire test suite using npm test. This command runs the same tests as the CI pipeline. ```bash npm test ``` -------------------------------- ### Direct CLI Metadata Schema Check Source: https://github.com/ctxr-dev/memory/blob/main/README.md Checks if the metadata schema is installed on the self_improvement slot using the CLI. Requires the bridge container to be running. ```bash docker exec -i "$(grep '^MCP_CONTAINER_NAME=' ./.memory/settings/.env | cut -d= -f2 | tr -d '\r')" \ node src/memory-cli.js list-metadata-fields --datasetId self_improvement ``` -------------------------------- ### Example Squash-Merge Commit Title Source: https://github.com/ctxr-dev/memory/blob/main/RELEASING.md Suggested format for the squash-commit title when merging a feature PR. This helps in summarizing the changes included in the release. ```git commit feat: typed memory pipeline + plan-capture + audit tools (#2) ``` -------------------------------- ### Repository Structure Overview Source: https://github.com/ctxr-dev/memory/blob/main/README.md The project is organized under a single .memory/ directory. This directory contains the cloned boilerplate source code and persistent data. ```text .memory/ # single gitignored folder (one .gitignore entry: /.memory) ├── src/ # the cloned boilerplate (THIS repo); rm -rf + re-clone safe │ ├── bootstrap.sh # render project-root files; idempotent │ ├── compose.mcp.yaml # Docker Compose override for the MCP bridge │ ├── .env.example # template for ../settings/.env │ ├── scripts/ │ │ ├── up.sh, down.sh, ps.sh # stack lifecycle │ │ ├── ui-url.sh # discover the host UI port │ │ ├── dify-bootstrap.sh # resolve + pin Dify version, clone vendor │ │ ├── dify-setup.sh # interactive dataset binding + metadata │ │ │ # schema installer + absorb wizard │ │ ├── mcp-config.sh # print client snippets │ │ ├── mcp-smoke.sh # JSON-RPC smoke against the bridge │ │ ├── compile.mjs # daily -> knowledge / self_improvement │ │ │ # promotion (per-atom-type routing, │ │ │ # metadata-filtered dedup-merge) │ │ ├── merge-config.mjs # CLI used by bootstrap.sh to structurally │ │ │ # merge our hooks/MCP entries into the │ │ │ # user's existing config without losing │ │ │ # user content │ │ ├── lib/{env,llm,dify-write,redact,slug,datasets,lock,merge-config}.mjs │ │ └── hooks/ │ │ ├── session-start.{sh,mjs} # lazy compile trigger + reminder │ │ ├── pre-compact.sh # -> flush.mjs pre-compact │ │ ├── post-compact.sh # -> flush.mjs post-compact │ │ ├── session-end.sh # -> flush.mjs session-end │ │ └── flush.mjs # shared extractor (incl. self- │ │ # improvement-lesson type + metadata) │ ├── prompts/{flush,compile}.md # LLM extraction + dedup-merge prompts │ ├── mcp-server/src/{index,dify,memory-cli,glob,slug}.js │ ├── templates/ │ │ ├── agents/ # rendered to /.agents/ │ │ ├── claude/settings.json # rendered to /.claude/ │ │ ├── skills/self-improvement.md # rendered to .claude/skills/ AND .agents/rules/ │ │ ├── skills/plan-capture.md # rendered to .claude/skills/ AND .agents/rules/ │ │ ├── skills/investigation-capture.md # rendered to .claude/skills/ AND .agents/rules/ │ │ └── gitignore.append # appended to /.gitignore │ └── vendor/dify/ # upstream Dify source, cloned at first dify-bootstrap ├── dify/ # Dify persistent data (db, object storage, weaviate, redis) └── settings/ # canonical .env (API key + dataset bindings) + .dify-version # Memory is stored entirely in Dify, organised by named slot, named: # daily-.md (one per UTC day, sessions accumulate, daily slot) # knowledge--.md (one per deduped fact, knowledge slot) # lesson--.md (one per deduped lesson, self_improvement slot) ``` -------------------------------- ### Restarting the Memory Bridge Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md Restart the memory bridge service after making environment variable changes. Use the correct service name for your Docker Compose setup. ```bash ./.memory/src/scripts/up.sh memory_mcp ``` -------------------------------- ### Register Codex/OpenAI Client Source: https://github.com/ctxr-dev/memory/blob/main/templates/agents/clients/README.md Register the Codex/OpenAI client with the memory server using this command. Ensure the memory server name is correctly specified. ```bash codex mcp add __MEMORY_SERVER_NAME__ -- docker exec -i __MEMORY_SERVER_NAME__ node src/index.js ``` -------------------------------- ### Generate MCP Configuration Snippets Source: https://github.com/ctxr-dev/memory/blob/main/templates/agents/README.md Use this helper script to generate MCP configuration snippets for clients that do not automatically read the main `.agents/mcp.json` file. ```bash ./.memory/src/scripts/mcp-config.sh all ``` -------------------------------- ### Useful Memory Stack Commands Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md A collection of utility scripts for managing the memory stack. Use these to check status, retrieve UI URLs, stop services, and migrate data. ```bash ./.memory/src/scripts/ui-url.sh ``` ```bash ./.memory/src/scripts/ps.sh ``` ```bash ./.memory/src/scripts/down.sh ``` ```bash ./.memory/src/scripts/migrate-persistent-data.sh ``` -------------------------------- ### Upgrade Memory Project Recipe Source: https://github.com/ctxr-dev/memory/blob/main/README.md Follow these steps to upgrade the memory project, including pulling the latest code, re-running bootstrap scripts, and recreating the bridge container. Ensure your project slug is replaced with the actual slug. ```bash cd .memory/src && git pull && cd .. && ./.memory/src/bootstrap.sh --slug ./.memory/src/scripts/up.sh memory_mcp # recreate the bridge so it picks up env changes ``` -------------------------------- ### Configure Dify Environment Variables Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md Manually configure the Dify Knowledge API key and dataset IDs in the .env file. Each line after DIFY_KNOWLEDGE_API_KEY declares a slot, with the slot name derived from the environment variable name. ```bash DIFY_KNOWLEDGE_API_KEY=... # Each line declares one slot. The slot NAME is the env-var name # lowercased between DIFY_DATASET_ and _ID. Empty value = declared but ``` -------------------------------- ### Print Specific MCP Client Configuration Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md This bash script prints the configuration for a specific MCP client, such as 'codex', 'claude-desktop', or 'cursor'. Use this to check individual client settings. ```bash ./.memory/src/scripts/mcp-config.sh codex ``` ```bash ./.memory/src/scripts/mcp-config.sh claude-desktop ``` ```bash ./.memory/src/scripts/mcp-config.sh cursor ``` -------------------------------- ### Run Write-Path Integration Smoke Test Source: https://github.com/ctxr-dev/memory/blob/main/CONTRIBUTING.md Execute the write-path integration smoke test, which writes, verifies, and deletes a synthetic document. Use the --keep flag to retain the document for inspection. ```bash ./scripts/plan-capture-smoke.sh ``` ```bash ./scripts/plan-capture-smoke.sh --keep ``` ```bash ./scripts/plan-capture-smoke.sh --help ``` -------------------------------- ### Pipeline Routing Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md Configure pipeline routing for datasets using DIFY_FLUSH_DATASET, DIFY_COMPILE_DATASET, and DIFY_ABSORB_DEFAULT_DATASET. ```bash DIFY_FLUSH_DATASET=daily DIFY_COMPILE_DATASET=knowledge DIFY_ABSORB_DEFAULT_DATASET=knowledge ``` -------------------------------- ### Static Verification of Scripts Source: https://github.com/ctxr-dev/memory/blob/main/README.md Performs static analysis on shell and Node.js scripts to ensure syntax correctness before running the Docker stack. Includes testing the npm package. ```bash bash -n ./.memory/src/bootstrap.sh ./.memory/src/scripts/*.sh ./.memory/src/scripts/hooks/*.sh ``` ```bash node --check ./.memory/src/scripts/compile.mjs ./.memory/src/scripts/hooks/flush.mjs ./.memory/src/scripts/hooks/session-start.mjs ``` ```bash node --check ./.memory/src/scripts/lib/*.mjs ./.memory/src/mcp-server/src/*.js ``` ```bash ( cd ./.memory/src && npm test ) ``` -------------------------------- ### Static Analysis and Compilation Checks Source: https://github.com/ctxr-dev/memory/blob/main/README.md Performs static analysis on shell scripts and checks Node.js script compilation. Requires only bootstrap.sh. ```bash bash -n ./.memory/src/bootstrap.sh ./.memory/src/scripts/*.sh ./.memory/src/scripts/hooks/*.sh node --check ./.memory/src/scripts/compile.mjs ./.memory/src/scripts/hooks/flush.mjs ./.memory/src/scripts/hooks/session-start.mjs node --check ./.memory/src/scripts/lib/*.mjs ./.memory/src/mcp-server/src/*.js ``` -------------------------------- ### Retrieve Plans by Query and Metadata Filter Source: https://github.com/ctxr-dev/memory/blob/main/templates/skills/plan-capture.md Use this function to retrieve plans based on a query and specific metadata filters. The `datasets` parameter should include 'plans', and `filters` can specify `atom_type` and `project_module` for precise scoping. ```javascript search_memory({ query: "some query", datasets: ["plans"], filters: { atom_type: "plan" }, scoreThreshold: 0.55 }) ``` ```javascript search_memory({ query: "some query", datasets: ["plans"], filters: { atom_type: "plan", project_module: "auth" }, scoreThreshold: 0.55 }) ``` -------------------------------- ### Search for a Plan by Title Source: https://github.com/ctxr-dev/memory/blob/main/templates/skills/plan-capture.md Programmatically verify plan capture by searching the 'plans' dataset for a specific plan title. Asserts at least one hit. ```javascript search_memory({ query: "", datasets: ["plans"], filters: { atom_type: "plan" } }) ``` -------------------------------- ### Hook-Created Memory Document Options Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md Configure indexing, document form, language, and processing rules for hook-created memory documents. These settings control how Dify processes captured conversations. ```bash DIFY_SESSION_INDEXING_TECHNIQUE=high_quality DIFY_SESSION_DOC_FORM=text_model DIFY_SESSION_DOC_LANGUAGE=English DIFY_SESSION_PROCESS_RULE_PRESET=conversation MEMORY_HOOK_MAX_TURNS=30 MEMORY_HOOK_MAX_CHARS=80000 MEMORY_HOOK_SESSION_END_MIN_TURNS=1 MEMORY_HOOK_PRECOMPACT_MIN_TURNS=5 ``` -------------------------------- ### Run Plan-Capture Write Path Smoke Test Source: https://github.com/ctxr-dev/memory/blob/main/README.md Execute the smoke test script to verify the ExitPlanMode auto-capture write path. Use the --keep flag to retain the generated smoke document for inspection. ```bash ./.memory/src/scripts/plan-capture-smoke.sh ``` ```bash ./.memory/src/scripts/plan-capture-smoke.sh --keep ``` -------------------------------- ### Hermetic Unit Tests Source: https://github.com/ctxr-dev/memory/blob/main/README.md Runs hermetic unit tests for the project. Requires Node.js 20+. ```bash ( cd ./.memory/src && npm test ) ``` -------------------------------- ### Post-Compact Hook Script Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md Shell script for the post-compaction lifecycle event. It prefers the compact summary, with optional session ID, CWD, and reason. ```bash ./.memory/src/scripts/hooks/post-compact.sh ``` -------------------------------- ### Dataset Bindings Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md Define dataset IDs by adding DIFY_DATASET__ID lines. An empty value means the dataset is declared but unbound. The dify-setup.sh script manages these bindings. ```bash DIFY_DATASET_DAILY_ID=... DIFY_DATASET_KNOWLEDGE_ID=... DIFY_DATASET_PLANS_ID=... DIFY_DATASET_INVESTIGATIONS_ID=... DIFY_DATASET_SELF_IMPROVEMENT_ID=... ``` -------------------------------- ### Save Lesson Function Source: https://github.com/ctxr-dev/memory/blob/main/README.md Use `save_lesson` immediately after user correction to capture lessons learned. The `error_pattern` in metadata is crucial for deduping and merging lessons. ```javascript save_lesson(title, body, metadata, tags?, evidence?) ``` -------------------------------- ### Recall Lessons Source: https://github.com/ctxr-dev/memory/blob/main/templates/skills/self-improvement.md Searches for self-improvement lessons relevant to a given task before execution. Lessons are applied silently, and a confirmation is added to the user's reply if a lesson is applied. ```APIDOC ## recall_lessons ### Description Searches for self-improvement lessons relevant to a given task before execution. Lessons are applied silently, and a confirmation is added to the user's reply if a lesson is applied. ### Method `recall_lessons` ### Parameters #### Query Parameters - **query** (string) - Required - A short description of the task to be performed. - **project_module** (string) - Required - The module of the project the task relates to (e.g., 'auth', 'billing', 'infra'). - **language** (string) - Optional - The programming language relevant to the task (e.g., 'swift', 'python', 'typescript'). - **task_type** (string) - Required - The type of task (e.g., 'planning', 'implementation', 'debugging'). - **error_pattern** (string) - Optional - A short kebab-case slug representing a known error pattern, if applicable. ### Request Example ```json { "query": "Implement user authentication", "project_module": "auth", "language": "python", "task_type": "implementation", "error_pattern": "common-auth-bug" } ``` ### Response #### Success Response - **lessons** (array) - A list of recalled lessons. Each lesson might contain a title and content. #### Response Example ```json { "lessons": [ { "title": "Secure Password Handling", "content": "Always use bcrypt for password hashing and never store plain text passwords." } ] } ``` ``` -------------------------------- ### Retrieve Dify UI URL Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md This script dynamically retrieves the current URL for the Dify UI. It's recommended to use this command as the port can change after container recreation. ```bash ./.memory/src/scripts/ui-url.sh ``` -------------------------------- ### Memory Architecture Diagram Source: https://github.com/ctxr-dev/memory/blob/main/README.md Visual representation of the memory building process, showing data flow between capture, promotion, on-demand, and exit plan stages. ```mermaid flowchart TB subgraph Capture["① Capture (per session)"] direction TB Hook["PreCompact / PostCompact / SessionEnd"] --> Flush["scripts/hooks/flush.mjs"] Flush --> LLM1["LLM extract (typed atoms)"] end LLM1 --> DailyDataset[("Dify dataset 'daily'"
daily-<date>.md (one per UTC day))] subgraph Promote["② Promote (lazy, once/UTC day)"] direction TB Start["SessionStart"] --> Compile["scripts/compile.mjs"] Compile --> ReadDaily["Read completed-day daily-*.md (not today)"] ReadDaily --> LLM2["LLM dedup-merge vs 'knowledge'"] end DailyDataset --> ReadDaily LLM2 --> KnowledgeDataset[("Dify dataset 'knowledge'"
knowledge-<slug>-<ts>.md)] LLM2 --> SelfImprovement[("Dify dataset 'self_improvement'"
lesson-<slug>-<ts>.md)] Compile --> DisableDaily["Disable dailies older than MEMORY_DAILY_ACTIVE_DAYS"] subgraph OnDemand["③ On-demand (any session)"] direction TB Absorb["MCP absorb_files"] Save["MCP save_to_dataset / save_memory / write_memory"] end subgraph PlanCapture["④ ExitPlanMode auto-capture (per approval)"] direction TB ExitPlan["PostToolUse: ExitPlanMode (approved=true)"] --> ExitPlanScript["scripts/hooks/exit-plan-mode.mjs"] end Absorb --> KnowledgeDataset Save --> AnyDataset[("Dify named slots"
plans, investigations, ...)] Save --> SelfImprovement ExitPlanScript --> PlansDataset[("Dify dataset 'plans'"
plan-<slug>.md)] DailyDataset --> Search([("MCP search_memory / recall_lessons")]) KnowledgeDataset --> Search SelfImprovement --> Search AnyDataset --> Search PlansDataset --> Search ``` -------------------------------- ### Register Codex MCP Client Source: https://github.com/ctxr-dev/memory/blob/main/README.md Manually registers the Codex MCP client if it was not auto-registered during the bootstrap phase. Requires the project slug. ```bash codex mcp add -memory -- docker exec -i -memory node src/index.js ``` -------------------------------- ### Pre-Compact Hook Script Source: https://github.com/ctxr-dev/memory/blob/main/STACK.md Shell script for the pre-compaction lifecycle event. It primarily uses the transcript path, with optional session ID, CWD, and reason. ```bash ./.memory/src/scripts/hooks/pre-compact.sh ``` -------------------------------- ### Save Lesson Source: https://github.com/ctxr-dev/memory/blob/main/templates/skills/self-improvement.md Persists a new self-improvement lesson, typically used when the user corrects the AI. ```APIDOC ## save_lesson ### Description Persists a new self-improvement lesson, typically used when the user corrects the AI or provides new information. ### Method `save_lesson` ### Parameters #### Request Body - **lesson_title** (string) - Required - The title of the lesson to be saved. - **lesson_content** (string) - Required - The detailed content of the lesson. - **project_module** (string) - Required - The module of the project this lesson pertains to. - **tags** (array of strings) - Optional - Keywords or tags associated with the lesson. ### Request Example ```json { "lesson_title": "Corrected API Endpoint Usage", "lesson_content": "The correct endpoint for user data is /api/v2/users, not /api/v1/users.", "project_module": "api", "tags": ["api", "users", "correction"] } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation (e.g., 'saved'). #### Response Example ```json { "status": "saved" } ``` ``` -------------------------------- ### Save Lesson Object Structure Source: https://github.com/ctxr-dev/memory/blob/main/templates/skills/self-improvement.md Use this structure to save a lesson when a user corrects the system. Ensure 'error_pattern' is always set for proper deduplication. ```javascript save_lesson({ title: "", body: "", metadata: { project_module: "", task_type: "", error_pattern: "", language: "" }, tags: ["", ""], evidence: "" }) ``` -------------------------------- ### Annotated Git Tagging and Pushing Source: https://github.com/ctxr-dev/memory/blob/main/RELEASING.md Commands to create an annotated Git tag and push it to the remote repository. Annotated tags are required for proper version tracking and GitHub release integration. ```bash git tag -a v0.1.0 -m "v0.1.0 — typed memory pipeline + plan-capture + audit tools" git push origin v0.1.0 ``` -------------------------------- ### Recall Lessons Function Source: https://github.com/ctxr-dev/memory/blob/main/README.md Call `recall_lessons` before non-trivial work to retrieve relevant self-improvement lessons. It filters the `self_improvement` dataset and can optionally include knowledge from other datasets. ```javascript recall_lessons(query, project_module?, language?, task_type?, error_pattern?, tags?, includeKnowledge?, scoreThreshold?, maxResults?) ```