{
  "canonical_name": "danielsimonjr/memory-mcp",
  "compilation_id": "pack_02f2933514b04964a48c1649a42abe0d",
  "created_at": "2026-05-24T13:34:51.893718+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `npm install -g @danielsimonjr/memory-mcp` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "npm install -g @danielsimonjr/memory-mcp",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_b66f6c24f51c4be6aa1ee68feec7a242"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_a7ea2dadbf21fea1d8967a96b0942d26",
    "canonical_name": "danielsimonjr/memory-mcp",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/danielsimonjr/memory-mcp",
    "slug": "memory-mcp",
    "source_packet_id": "phit_7dcd0b8a90bc424597533084105fbaae",
    "source_validation_id": "dval_34874bd3c6f3464c8fd118ee38eb5781"
  },
  "merchandising": {
    "best_for": "需要工具连接与集成能力，并使用 mcp_host的用户",
    "github_forks": 1,
    "github_stars": 2,
    "one_liner_en": "Enhanced Model Context Protocol memory server with timestamps, tags, importance, search, and export capabilities",
    "one_liner_zh": "Enhanced Model Context Protocol memory server with timestamps, tags, importance, search, and export capabilities",
    "primary_category": {
      "category_id": "tool-integrations",
      "confidence": "high",
      "name_en": "Tool Integrations",
      "name_zh": "工具连接与集成",
      "reason": "matched_keywords:mcp, server, github"
    },
    "target_user": "使用 mcp_host 等宿主 AI 的用户",
    "title_en": "memory-mcp",
    "title_zh": "memory-mcp 能力包",
    "visible_tags": [
      {
        "label_en": "MCP Tools",
        "label_zh": "MCP 工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-mcp-tools",
        "type": "product_domain"
      },
      {
        "label_en": "Knowledge Base Q&A",
        "label_zh": "知识库问答",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-knowledge-base-q-a",
        "type": "user_job"
      },
      {
        "label_en": "Structured Data Extraction",
        "label_zh": "结构化数据提取",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-structured-data-extraction",
        "type": "core_capability"
      },
      {
        "label_en": "Multi-role Workflow",
        "label_zh": "多角色协作流程",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-multi-role-workflow",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Open Source Tool",
        "label_zh": "开源工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-open-source-tool",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_7dcd0b8a90bc424597533084105fbaae",
  "page_model": {
    "artifacts": {
      "artifact_slug": "memory-mcp",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "npm install -g @danielsimonjr/memory-mcp",
          "label": "Node.js / npm · 官方安装入口",
          "source": "https://github.com/danielsimonjr/memory-mcp#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "MCP 工具",
        "知识库问答",
        "结构化数据提取",
        "多角色协作流程",
        "开源工具"
      ],
      "eyebrow": "工具连接与集成",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要工具连接与集成能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Enhanced Model Context Protocol memory server with timestamps, tags, importance, search, and export capabilities"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "mcp_host",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | last_activity_observed missing"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "downstream_validation.risk_items | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | issue_or_pr_quality=unknown"
            ],
            "severity": "low",
            "suggested_check": "抽样最近 issue/PR，判断是否长期无人处理。",
            "title": "issue/PR 响应质量未知",
            "user_impact": "用户无法判断遇到问题后是否有人维护。"
          },
          {
            "body": "release_recency=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 6 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：能力坑 - 能力判断依赖假设。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 936,
        "forks": 1,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 2
      },
      "source_url": "https://github.com/danielsimonjr/memory-mcp",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Enhanced Model Context Protocol memory server with timestamps, tags, importance, search, and export capabilities",
      "title": "memory-mcp 能力包",
      "trial_prompt": "# memory-mcp - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for danielsimonjr/memory-mcp.\n\nProject:\n- Name: memory-mcp\n- Repository: https://github.com/danielsimonjr/memory-mcp\n- Summary: Enhanced Model Context Protocol memory server with timestamps, tags, importance, search, and export capabilities\n- Host target: mcp_host\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Enhanced Model Context Protocol memory server with timestamps, tags, importance, search, and export capabilities\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Enhanced Model Context Protocol memory server with timestamps, tags, importance, search, and export capabilities\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. getting-started: Getting Started. Produce one small intermediate artifact and wait for confirmation.\n2. architecture-overview: Architecture Overview. Produce one small intermediate artifact and wait for confirmation.\n3. storage-backends: Storage Backends. Produce one small intermediate artifact and wait for confirmation.\n4. entity-model: Entity-Relation-Observation Model. Produce one small intermediate artifact and wait for confirmation.\n5. tool-reference: Tool Reference. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/danielsimonjr/memory-mcp\n- https://github.com/danielsimonjr/memory-mcp#readme\n- README.md\n- package.json\n- src/index.ts\n- src/server/MCPServer.ts\n- docs/architecture/ARCHITECTURE.md\n- docs/architecture/COMPONENTS.md\n- docs/architecture/dependency-graph.json\n- tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：reddit。reddit: MCP server that indexes codebases into a knowledge graph - Reddit（https://www.reddit.com/r/LocalLLaMA/comments/1rjt4hh/mcp_server_that_indexes_codebases_into_a/）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "searxng_indexed",
              "source": "reddit",
              "title": "MCP server that indexes codebases into a knowledge graph - Reddit",
              "url": "https://www.reddit.com/r/LocalLLaMA/comments/1rjt4hh/mcp_server_that_indexes_codebases_into_a/"
            }
          ],
          "status": "已收录 1 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "工具连接与集成",
      "desc": "Enhanced Model Context Protocol memory server with timestamps, tags, importance, search, and export capabilities",
      "effort": "安装已验证",
      "forks": 1,
      "icon": "link",
      "name": "memory-mcp 能力包",
      "risk": "需复核",
      "slug": "memory-mcp",
      "stars": 2,
      "tags": [
        "MCP 工具",
        "知识库问答",
        "结构化数据提取",
        "多角色协作流程",
        "开源工具"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/danielsimonjr/memory-mcp 项目说明书\n\n生成时间：2026-05-16 09:20:25 UTC\n\n## 目录\n\n- [Getting Started](#getting-started)\n- [Project Structure](#project-structure)\n- [Architecture Overview](#architecture-overview)\n- [Storage Backends](#storage-backends)\n- [Entity-Relation-Observation Model](#entity-model)\n- [Tool Reference](#tool-reference)\n- [Search Capabilities](#search-capabilities)\n- [Temporal and Advanced Features](#temporal-features)\n- [Collaboration and Security](#collaboration-security)\n- [Development Guide](#development-guide)\n\n<a id='getting-started'></a>\n\n## Getting Started\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Development Guide](#development-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/README.md)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)\n- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n- [tools/create-dependency-graph/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md)\n</details>\n\n# Getting Started\n\nThis guide provides everything you need to install, configure, and begin using the Enhanced Memory MCP server.\n\n## Overview\n\nMemory MCP is a Model Context Protocol (MCP) server that provides persistent memory and knowledge graph capabilities for AI agents and applications. It exposes 213 tools across 58 categories for entity management, semantic search, hierarchy traversal, graph algorithms, and context compression. 资料来源：[CLAUDE.md:1]()\n\nThe server acts as a bridge between AI applications and a knowledge graph storage layer, enabling:\n\n- Persistent entity and relation storage\n- Semantic and ranked search capabilities\n- Time-based memory decay and importance scoring\n- Context compression for large inputs\n- Multi-format data import/export\n\n## Prerequisites\n\nBefore installing Memory MCP, ensure your environment meets these requirements:\n\n| Requirement | Minimum Version | Notes |\n|-------------|-----------------|-------|\n| Node.js | 18.0+ | ES2022 features required |\n| npm | 9.0+ | For package management |\n| SQLite | 3.39+ | Only if using SQLite storage |\n| TypeScript | 5.0+ | For development work |\n\n资料来源：[CLAUDE.md:20]()\n\n## Installation\n\n### From npm (Recommended for Users)\n\n```bash\nnpm install @danielsimonjr/memory-mcp\n```\n\nThis installs the pre-built package with all dependencies. The core library `@danielsimonjr/memoryjs` is automatically included. 资料来源：[CLAUDE.md:24]()\n\n### From Source (Recommended for Development)\n\n```bash\n# Clone the repository\ngit clone https://github.com/danielsimonjr/memory-mcp.git\ncd memory-mcp\n\n# Install dependencies\nnpm install\n\n# Build the project\nnpm run build\n```\n\nThe `prepare` script runs automatically on `npm install`, triggering the build process. 资料来源：[CONTRIBUTING.md:1]()\n\n### Verify Installation\n\nAfter installation, verify the CLI is available:\n\n```bash\nmcp-server-memory --help\n```\n\n## Configuration\n\n### Environment Variables\n\nMemory MCP supports several environment variables for configuration:\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `MEMORY_STORAGE_TYPE` | `jsonl` | Storage backend: `jsonl` or `sqlite` |\n| `MEMORY_DB_PATH` | `memory.db` | Path to SQLite database (when using SQLite) |\n| `MEMORY_JSONL_PATH` | `memory.jsonl` | Path to JSONL file (when using JSONL) |\n\n资料来源：[CLAUDE.md:14]()\n\n### Storage Options\n\nMemory MCP supports two storage backends:\n\n**JSONL Storage (Default)**\n\n- Data stored in human-readable JSONL files\n- Files: `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl`\n- Location: Project root directory 资料来源：[CLAUDE.md:14]()\n\n**SQLite Storage**\n\n- Set `MEMORY_STORAGE_TYPE=sqlite` to enable\n- Uses `better-sqlite3` for native performance\n- Single database file: `memory.db` 资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:1]()\n\n## Architecture Overview\n\n### System Layers\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (this repo)\"\n        A[\"src/index.ts\"] --> B[\"MCPServer.ts\"]\n        B --> C[\"toolDefs.ts\"]\n        C --> D[\"toolHandlers.ts\"]\n    end\n    \n    subgraph \"@danielsimonjr/memoryjs (npm dependency)\"\n        E[\"ManagerContext<br/>(lazy init)\"] --> F[\"EntityManager\"]\n        E --> G[\"RelationManager\"]\n        E --> H[\"SearchManager\"]\n        E --> I[\"IOManager\"]\n        E --> J[\"GraphStorage / SQLiteStorage\"]\n    end\n    \n    D --> E\n```\n\n资料来源：[CLAUDE.md:4-13]()\n\n### Entry Points\n\n| Entry Point | Purpose |\n|-------------|---------|\n| `dist/index.js` | Main build output |\n| `mcp-server-memory` | CLI binary (defined in package.json `bin`) |\n| `src/index.ts` | Source entry point |\n\n资料来源：[CLAUDE.md:17]()\n\n### Manager Accessors\n\nThe `ManagerContext` provides access to all core managers:\n\n| Accessor | Purpose |\n|----------|---------|\n| `ctx.entityManager` | Core CRUD for graph nodes |\n| `ctx.relationManager` | Directed edges between entities |\n| `ctx.observationManager` | Facts attached to entities |\n| `ctx.searchManager` | Basic, ranked, boolean, fuzzy search |\n| `ctx.semanticSearch` | Embedding similarity via OpenAI or local models |\n| `ctx.tagManager` | Tag management with importance scores |\n| `ctx.hierarchyManager` | Parent-child trees, subtree traversal |\n| `ctx.compressionManager` | Duplicate detection, merge, archive |\n| `ctx.graphTraversal` | BFS/DFS path finding, centrality |\n| `ctx.analyticsManager` | Graph stats and integrity validation |\n| `ctx.storage` | Direct GraphStorage access |\n\n资料来源：[CLAUDE.md:1]()\n\n## Tool Categories Overview\n\nMemory MCP exposes tools organized into 58 categories with 213 total tools:\n\n| Category | Count | Key Purpose |\n|----------|-------|-------------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities |\n| Search | 7 | Basic, ranked, boolean, fuzzy |\n| Semantic Search | 3 | Embedding similarity |\n| Intelligent Search | 3 | Hybrid multi-layer, query analysis |\n| Saved Searches | 5 | Store and re-execute queries |\n| Tag Management | 6 | Tags, bulk ops, importance scores |\n| Tag Aliases | 5 | Tag synonym/alias management |\n| Hierarchy | 9 | Parent-child trees, subtree traversal |\n| Graph Algorithms | 4 | BFS/DFS, centrality, connected components |\n| Analytics | 2 | Graph stats and integrity validation |\n| Compression | 4 | Dedup, merge, auto-compress, archive |\n| Import/Export | 2 | 7 export formats |\n| Decay & Salience | 3 | Time-based importance decay |\n\n资料来源：[CLAUDE.md:3]()\n\n## Quick Start with MCP Client\n\nOnce Memory MCP is installed and configured, integrate it with your MCP-compatible client:\n\n```json\n{\n  \"mcpServers\": {\n    \"memory\": {\n      \"command\": \"mcp-server-memory\",\n      \"args\": []\n    }\n  }\n}\n```\n\nFor SQLite storage:\n\n```json\n{\n  \"mcpServers\": {\n    \"memory\": {\n      \"command\": \"mcp-server-memory\",\n      \"env\": {\n        \"MEMORY_STORAGE_TYPE\": \"sqlite\"\n      }\n    }\n  }\n}\n```\n\n## Basic Operations\n\n### Creating Entities\n\n```typescript\n// Via tool handler (internal usage example)\nawait ctx.entityManager.createEntity({\n  name: \"project_alpha\",\n  entityType: \"project\",\n  observations: [\"Initial setup complete\"]\n});\n```\n\n### Searching\n\n```typescript\n// Ranked search (TF-IDF)\nconst results = await ctx.searchManager.rankedSearch(\"query text\");\n\n// Semantic search\nconst semanticResults = await ctx.semanticSearch.query({\n  text: \"query text\",\n  limit: 10\n});\n```\n\n### Context Compression\n\n```typescript\nconst compressed = ctx.contextWindowManager.compressForContext(\n  largeText,\n  { level: 'medium' }\n);\n```\n\n## Standalone Tools\n\nThe `tools/` directory contains standalone utilities:\n\n| Tool | Purpose |\n|------|---------|\n| `chunking-for-files` | Split/merge large files for context-limited editing |\n| `compress-for-context` | CTON compression for LLM context windows |\n| `create-dependency-graph` | Generate TypeScript project dependency graphs |\n| `migrate-from-jsonl-to-sqlite` | Convert between JSONL and SQLite formats |\n\n资料来源：[CLAUDE.md:18]()\n\nEach tool has its own `package.json` and can be built to Windows executables via `pkg`. 资料来源：[CLAUDE.md:18]()\n\n## Development Setup\n\n### Cloning and Initial Setup\n\n```bash\ngit clone https://github.com/danielsimonjr/memory-mcp.git\ncd memory-mcp\nnpm install\n```\n\n### Creating a Feature Branch\n\n```bash\ngit checkout -b feature/your-feature-name\n```\n\n### Development Workflow\n\n```bash\n# Make your changes\n\n# Commit your changes\ncd c:/mcp-servers/memory-mcp\ngit add .\ngit commit -m \"Description of your changes\"\n\n# Push and create PR\ngit push origin feature/your-feature-name\n```\n\n资料来源：[CONTRIBUTING.md:1-7]()\n\n### Code Style Guidelines\n\n- Follow TypeScript best practices\n- Use meaningful variable names\n- Add JSDoc comments for public methods\n- Keep functions focused and small\n- Maintain consistent indentation (2 spaces)\n\n资料来源：[CONTRIBUTING.md:12-16]()\n\n## Testing\n\n### Test Requirements\n\nWhen testing new features:\n\n- Test new features thoroughly\n- Include edge cases\n- Test backward compatibility\n- Verify export formats are valid\n- Test with empty graphs and large graphs\n\n资料来源：[CONTRIBUTING.md:18-22]()\n\n### Running Tests\n\n```bash\nnpm test\n```\n\nNote: Test runs create/modify `memory.jsonl`, `memory.db` files in the project root. These are in `.gitignore` and won't appear in `git status`. 资料来源：[CLAUDE.md:22]()\n\n## Building for Distribution\n\n### Package Structure\n\n- **Build output**: `dist/index.js`\n- **CLI binary**: `mcp-server-memory` (defined in package.json `bin`)\n- **Source entry**: `src/index.ts`\n- **TypeScript target**: ES2022 with Node16 module resolution\n\n资料来源：[CLAUDE.md:17,23]()\n\n### Publishing to npm\n\n```bash\n# Set authentication token\nnpm config set //registry.npmjs.org/:_authToken=$(cat c:\\mcp-servers\\npm_key.txt)\n\n# Publish with public access\nnpm publish --access public\n```\n\nThe `prepare` script auto-builds, so separate `npm run build` is not needed before publish. 资料来源：[CLAUDE.md:25]()\n\n### Verifying Package Contents\n\nBefore publishing:\n\n```bash\nnpm pack --dry-run 2>&1 | grep -E \"jsonl|\\.db|total files|package size\"\n```\n\n资料来源：[CLAUDE.md:25]()\n\n## Data Migration\n\n### JSONL to SQLite\n\n```bash\nnpx tsx tools/migrate-from-jsonl-to-sqlite.ts \\\n  --from memory.jsonl \\\n  --to memory.db \\\n  --verbose\n```\n\n### Command Line Arguments\n\n| Argument | Short | Description |\n|----------|-------|-------------|\n| `--from <path>` | `-f` | Source file path (JSONL or SQLite) |\n| `--to <path>` | `-t` | Target file path (JSONL or SQLite) |\n| `--verbose` | `-v` | Show detailed progress |\n| `--help` | `-h` | Show help message |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:1-30]()\n\n## Documentation\n\nWhen adding features:\n\n- Update README.md with new tools/functionality\n- Add entries to CHANGELOG.md\n- Update WORKFLOW.md if development process changes\n- Include usage examples\n\n资料来源：[CONTRIBUTING.md:28-32]()\n\n## Pull Request Process\n\n1. **Title**: Clear, descriptive summary\n2. **Description**: What changed, why it changed, how to test it\n3. **Tests**: Include test results\n4. **Documentation**: Update relevant docs\n5. **Backward Compatibility**: Confirm no breaking changes\n\n资料来源：[CONTRIBUTING.md:37-44]()\n\n## Error Handling\n\nError handling in dispatch catches exceptions from handlers and returns them as MCP-formatted error responses. Check the MCP response `isError` field when debugging. 资料来源：[CLAUDE.md:23]()\n\n## Next Steps\n\nAfter setting up your environment:\n\n1. Explore the [Tool Categories](#tool-categories-overview) to understand available operations\n2. Review the [Architecture Overview](#architecture-overview) for system design\n3. Set up your preferred [Storage Configuration](#configuration)\n4. Run the standalone [Dependency Graph Tool](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md) to visualize project structure\n5. Consult the project's issues for feature requests or bug reports\n\n---\n\n<a id='project-structure'></a>\n\n## Project Structure\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Development Guide](#development-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/index.ts)\n- [src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [tools/create-dependency-graph/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n</details>\n\n# Project Structure\n\n## Overview\n\nThe memory-mcp project implements a Model Context Protocol (MCP) server that provides a knowledge graph-based memory system for AI agents. The repository exposes over 200 tools across 58 categories, enabling persistent memory management with features including entity/relation CRUD, semantic search, bitemporal validity, and causal reasoning.\n\n## Repository Layout\n\n```\nmemory-mcp/\n├── src/                          # Main TypeScript source code\n│   ├── index.ts                  # Entry point and exports\n│   └── server/\n│       ├── MCPServer.ts          # Core MCP server implementation\n│       ├── toolDefinitions.ts    # Tool schemas (input/output specifications)\n│       └── toolHandlers.ts      # Tool implementation handlers\n├── tools/                        # Standalone utility tools\n│   ├── create-dependency-graph/ # TypeScript dependency analysis\n│   ├── compress-for-context/    # LLM context window compression\n│   ├── chunking-for-files/      # Large file splitting utilities\n│   └── migrate-from-jsonl-to-sqlite/ # Storage format migration\n├── dist/                         # Build output (npm published)\n├── docs/architecture/            # Generated documentation\n├── memory.jsonl                  # JSONL storage (project root)\n├── memory.db                     # SQLite storage (optional)\n├── package.json                  # npm package configuration\n└── CLAUDE.md                     # Developer documentation\n```\n\n## Core Architecture\n\n### Layered Architecture\n\nThe project follows a layered architecture where memory-mcp acts as an MCP interface wrapper around the core `@danielsimonjr/memoryjs` library.\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (this repo)\"\n        A[src/index.ts] --> B[src/server/MCPServer.ts]\n        B --> C[src/server/toolDefs.ts]\n        B --> D[src/server/toolHandlers.ts]\n    end\n    \n    subgraph \"@danielsimonjr/memoryjs (npm dependency)\"\n        E[ManagerContext] --> F[EntityManager]\n        E --> G[RelationManager]\n        E --> H[SearchManager]\n        E --> I[ObservationManager]\n        E --> J[TagManager]\n        E --> K[CompressionManager]\n        E --> L[GraphStorage]\n        E --> M[SQLiteStorage]\n    end\n    \n    D --> E\n    C --> E\n```\n\n资料来源：[CLAUDE.md:layered-architecture]()\n\n### Accessor Hierarchy\n\nThe `ManagerContext` provides lazy-initialized accessors for all subsystems:\n\n| Accessor | Purpose |\n|----------|---------|\n| `ctx.entityManager` | Graph node CRUD operations |\n| `ctx.relationManager` | Directed edge management |\n| `ctx.observationManager` | Facts attached to entities |\n| `ctx.searchManager` | Basic, ranked, boolean, fuzzy search |\n| `ctx.tagManager` | Tag CRUD and bulk operations |\n| `ctx.hierarchyManager` | Parent-child tree structures |\n| `ctx.analyticsManager` | Graph statistics and validation |\n| `ctx.compressionManager` | Duplicate detection and merging |\n| `ctx.archiveManager` | Historical data archival |\n| `ctx.ioManager` | Import/export operations |\n| `ctx.graphTraversal` | BFS/DFS path finding |\n| `ctx.semanticSearch` | Embedding similarity search |\n| `ctx.rankedSearch` | TF-IDF ranking |\n| `ctx.storage` | Direct GraphStorage access |\n\n资料来源：[CLAUDE.md:accessors]()\n\n## Source Code Organization\n\n### Entry Point (`src/index.ts`)\n\nThe main entry point handles:\n- Package exports and re-exports\n- Backward compatibility aliases (exports `ManagerContext` as `KnowledgeGraphManager`)\n- Core type re-exports\n\n### MCP Server (`src/server/MCPServer.ts`)\n\nThe `MCPServer` class is responsible for:\n- Initializing the ManagerContext with storage configuration\n- Tool dispatch and request handling\n- Error formatting and response generation\n\nKey aspects:\n- **Error handling**: `handleToolCall` catches exceptions from handlers and returns them as MCP-formatted error responses (checks `isError` field in responses)\n- **Storage initialization**: Supports both JSONL and SQLite storage backends\n- **Tool registration**: Dynamically registers tools from definitions\n\n资料来源：[CLAUDE.md:entry-points](), [CLAUDE.md:error-handling]()\n\n### Tool Definitions (`src/server/toolDefinitions.ts`)\n\nThe tool definitions file contains JSON Schema specifications for all 213 tools. Tools are organized into categories:\n\n| Category | Count | Description |\n|----------|-------|-------------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities |\n| Search | 7 | Basic, ranked, boolean, fuzzy search |\n| Intelligent Search | 3 | Hybrid multi-layer search |\n| Semantic Search | 3 | Embedding-based similarity |\n| Saved Searches | 5 | Stored query execution |\n| Tag Management | 6 | Tag CRUD and bulk operations |\n| Tag Aliases | 5 | Tag synonym management |\n| Hierarchy | 9 | Tree structures and traversal |\n| Graph Algorithms | 4 | Path finding, centrality |\n| Analytics | 2 | Stats and validation |\n| Compression | 4 | Duplicate detection, merge |\n| Import/Export | 2+ | Multiple format support |\n\n资料来源：[CLAUDE.md:tool-categories](), [src/server/toolDefinitions.ts]()\n\n### Tool Handlers (`src/server/toolHandlers.ts`)\n\nTool handlers implement the actual logic for each tool. Each handler:\n1. Validates input arguments using Zod schemas\n2. Accesses appropriate ManagerContext accessors\n3. Returns formatted responses\n\nExample handler pattern:\n```typescript\ntool_name: async (ctx, args) => {\n  // Input validation\n  const param = validateWithSchema(args.param, z.string(), 'Invalid param');\n  \n  // Business logic via ManagerContext\n  const result = await getSomeManager(ctx).someOperation(param);\n  \n  // Response formatting\n  return formatToolResponse(result);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts]()\n\n## Standalone Tools\n\nThe `tools/` directory contains independent utilities, each with its own `package.json` and compilable to Windows executables via `pkg`:\n\n### create-dependency-graph\n\nAnalyzes TypeScript source files and generates dependency documentation.\n\n| Output | Description |\n|--------|-------------|\n| `docs/architecture/DEPENDENCY_GRAPH.md` | Human-readable Markdown documentation |\n| `docs/architecture/dependency-graph.json` | Machine-readable JSON structure |\n\nFeatures:\n- Scans all TypeScript files in `src/`\n- Parses imports and exports\n- Categorizes files into logical modules\n- Detects circular dependencies\n- Generates statistics\n\nUsage:\n```bash\nnpm run docs:deps\n# or\nnpx tsx tools/create-dependency-graph.ts\n```\n\n资料来源：[tools/create-dependency-graph/README.md]()\n\n### compress-for-context\n\nCTON (Context Token Optimization Notation) compression for reducing LLM context window usage.\n\n| Option | Description |\n|--------|-------------|\n| `-o, --output <file>` | Output file path |\n| `-f, --format <fmt>` | Force format: json, yaml, markdown, csv, etc. |\n| `-l, --level <lvl>` | Compression level: light, medium, aggressive |\n| `-b, --batch` | Batch mode for multiple files |\n| `-d, --decompress` | Restore compressed file |\n\n### chunking-for-files\n\nSplits large files into editable sections for context-limited editing.\n\nCommands:\n- `chunker split <file>` - Split file into chunks\n- `chunker merge <manifest.json>` - Merge chunks back\n- `chunker status <manifest.json>` - Show chunk status\n\n### migrate-from-jsonl-to-sqlite\n\nConverts between JSONL and SQLite storage formats using `better-sqlite3`.\n\n```bash\nmigrate-from-jsonl-to-sqlite --from <source> --to <target> [--verbose]\n```\n\n## Storage System\n\nData files reside in the **project root** (not `dist/`):\n\n| Storage Type | File | Environment Variable |\n|--------------|------|---------------------|\n| JSONL (default) | `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl` | `MEMORY_STORAGE_TYPE=jsonl` |\n| SQLite | `memory.db` | `MEMORY_STORAGE_TYPE=sqlite` |\n\nThe `memory.db` and `*.jsonl` files are gitignored—they are created/modified at runtime but not tracked by version control.\n\n资料来源：[CLAUDE.md:storage]()\n\n## Build and Publication\n\n### Build Output\n\n| Artifact | Description |\n|----------|-------------|\n| `dist/index.js` | Main build output |\n| `mcp-server-memory` | CLI binary (package.json `bin` field) |\n\nThe TypeScript target is ES2022 with Node16 module resolution. The `prepare` script auto-runs `npm run build` on `npm install`, ensuring `dist/` is always rebuilt.\n\n### Publishing to npm\n\n```bash\n# Token with \"bypass 2FA\" required\nnpm config set //registry.npmjs.org/:_authToken=$(cat ~/.npm_token)\nnpm publish --access public\n```\n\nThe `prepare` script handles builds automatically, so separate `npm run build` is unnecessary before publishing.\n\n资料来源：[CLAUDE.md:publishing-to-npm]()\n\n## Development Guidelines\n\n### Code Style\n\n| Guideline | Standard |\n|-----------|----------|\n| Language | TypeScript best practices |\n| Indentation | 2 spaces |\n| Documentation | JSDoc comments for public methods |\n| Function design | Small, focused functions |\n| Naming | Meaningful variable names |\n\n### Testing Requirements\n\nWhen adding features:\n- Test with empty graphs and large graphs\n- Include edge cases\n- Verify backward compatibility\n- Ensure export formats are valid\n\n### Documentation Checklist\n\n| File | When to Update |\n|------|----------------|\n| `README.md` | New tools/functionality |\n| `CHANGELOG.md` | Version changes |\n| `WORKFLOW.md` | Development process changes |\n\n## File Naming Conventions\n\n| Pattern | Example | Purpose |\n|---------|---------|---------|\n| `*.ts` | `MCPServer.ts`, `toolHandlers.ts` | TypeScript source files |\n| `*.md` | `DEPENDENCY_GRAPH.md` | Generated documentation |\n| `*.json` | `dependency-graph.json` | Machine-readable data |\n| `*.compact` | output.compact | Compressed files |\n\n## Summary\n\nThe memory-mcp project is structured as a thin MCP wrapper around the `@danielsimonjr/memoryjs` library. The core source in `src/` contains only 5 TypeScript files, while the `tools/` directory provides standalone utilities for dependency analysis, context compression, file chunking, and storage migration. The architecture prioritizes backward compatibility, lazy initialization of managers, and clean separation between tool definitions, handlers, and the underlying knowledge graph implementation.\n\n---\n\n<a id='architecture-overview'></a>\n\n## Architecture Overview\n\n### 相关页面\n\n相关主题：[Storage Backends](#storage-backends), [Entity-Relation-Observation Model](#entity-model)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/index.ts)\n- [src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)\n- [src/server/toolDefs.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefs.ts)\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [docs/architecture/ARCHITECTURE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/docs/architecture/ARCHITECTURE.md)\n</details>\n\n# Architecture Overview\n\nThe memory-mcp project implements a Model Context Protocol (MCP) server that provides a persistent knowledge graph for AI agents. The system enables structured memory management with 213 tools across 58 categories, supporting entity management, relationships, observations, search, tagging, hierarchy traversal, analytics, and compression capabilities.\n\n## High-Level Architecture\n\nThe project follows a layered architecture that separates concerns between the MCP protocol interface, business logic, and storage implementation. The core knowledge graph functionality is delegated to the `@danielsimonjr/memoryjs` library (currently v2.1.0+), while memory-mcp serves as the protocol adapter and tool layer.\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (This Repository)\"\n        A[\"src/index.ts<br/>Entry Point\"] --> B[\"MCPServer.ts<br/>Protocol Handler\"]\n        B --> C[\"toolDefs.ts<br/>Tool Definitions\"]\n        B --> D[\"toolHandlers.ts<br/>Tool Handlers\"]\n        C --> D\n    end\n    \n    subgraph \"@danielsimonjr/memoryjs (npm Dependency)\"\n        E[\"ManagerContext<br/>Lazy Initialization\"]\n        E --> F[\"EntityManager\"]\n        E --> G[\"RelationManager\"]\n        E --> H[\"ObservationManager\"]\n        E --> I[\"SearchManager\"]\n        E --> J[\"TagManager\"]\n        E --> K[\"HierarchyManager\"]\n        E --> L[\"AnalyticsManager\"]\n        E --> M[\"CompressionManager\"]\n        E --> N[\"IOManager\"]\n    end\n    \n    D --> E\n    \n    O[\"GraphStorage/SQLiteStorage\"] --> E\n    \n    style A fill:#e1f5fe\n    style E fill:#fff3e0\n```\n\n资料来源：[CLAUDE.md:Layered Architecture]()\n\n## Core Components\n\n### Entry Point (src/index.ts)\n\nThe `src/index.ts` file serves as the primary entry point for the application. It exports the `ManagerContext` under an alias `KnowledgeGraphManager` for backward compatibility, along with all core types needed by consumers of the library.\n\nThe exports enable external consumers to:\n- Import the main context manager class\n- Access type definitions for entities, relations, observations, and search operations\n- Use the manager without knowledge of internal implementation details\n\n资料来源：[src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/index.ts)\n\n### MCPServer (src/server/MCPServer.ts)\n\nThe `MCPServer` class implements the Model Context Protocol server interface. It handles:\n\n- Protocol message parsing and routing\n- Tool registration and discovery\n- Request/response lifecycle management\n- Error handling and validation\n\nThe server initializes lazy-loaded managers through `ManagerContext`, ensuring resources are only allocated when actually needed.\n\n资料来源：[src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)\n\n### ManagerContext (memoryjs)\n\nThe `ManagerContext` provides access to all core managers through a unified interface. It implements lazy initialization to optimize startup time and resource usage.\n\n| Manager | Purpose |\n|---------|---------|\n| `entityManager` | Core CRUD operations for graph nodes |\n| `relationManager` | Directed edges between entities |\n| `observationManager` | Facts attached to entities with normalization |\n| `searchManager` | Basic, ranked, boolean, fuzzy, and auto-select search |\n| `tagManager` | Tag operations, bulk operations, importance scores |\n| `hierarchyManager` | Parent-child trees, subtree traversal |\n| `analyticsManager` | Graph statistics and integrity validation |\n| `compressionManager` | Duplicate detection, merge, auto-compress, archive |\n| `archiveManager` | Long-term storage management |\n| `ioManager` | Import/export operations |\n| `graphTraversal` | Graph algorithm utilities |\n| `semanticSearch` | Embedding-based similarity search |\n| `rankedSearch` | TF-IDF weighted search |\n| `storage` | Direct GraphStorage access for advanced use cases |\n\n资料来源：[CLAUDE.md:Accessors]()\n\n## Tool System Architecture\n\n### Tool Definitions (src/server/toolDefs.ts)\n\nTool definitions describe the interface contract for each capability. Each definition includes:\n\n- **name**: Unique identifier for the tool\n- **description**: Human-readable explanation of functionality\n- **inputSchema**: JSON Schema describing required and optional parameters\n\n### Tool Handlers (src/server/toolHandlers.ts)\n\nTool handlers implement the business logic for each tool. They receive the `ManagerContext` and validated arguments, then execute the appropriate manager operations.\n\nExample handler pattern:\n```typescript\ncreate_entity: async (ctx, args) => {\n  const name = validateWithSchema(args.name, z.string().min(1), 'Invalid name');\n  const entity = await ctx.entityManager.createEntity({ name, ... });\n  return formatToolResponse(entity);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:tool pattern]()\n\n### Tool Categories\n\nThe system organizes its 213 tools into 58 categories:\n\n| Category | Count | Key Purpose |\n|----------|-------|-------------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities, with normalization |\n| Search | 7 | Basic, ranked, boolean, fuzzy, auto-select |\n| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |\n| Semantic Search | 3 | Embedding similarity via OpenAI or local models |\n| Saved Searches | 5 | Store and re-execute frequent queries |\n| Tag Management | 6 | Tags, bulk ops, importance scores |\n| Tag Aliases | 5 | Tag synonym/alias management |\n| Hierarchy | 9 | Parent-child trees, subtree traversal |\n| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |\n| Analytics | 2 | Graph stats and integrity validation |\n| Compression | 4 | Duplicate detection, merge, auto-compress, archive |\n| Import/Export | 2 | 7 export formats |\n\n资料来源：[CLAUDE.md:Tool Categories]()\n\n## Storage Layer\n\nThe storage layer supports two backends controlled by the `MEMORY_STORAGE_TYPE` environment variable.\n\n### JSONL Storage (Default)\n\nData files are stored in the project root directory:\n\n| File | Purpose |\n|------|---------|\n| `memory.jsonl` | Main knowledge graph data |\n| `memory-saved-searches.jsonl` | Saved search definitions |\n| `memory-tag-aliases.jsonl` | Tag synonym mappings |\n\n### SQLite Storage\n\nWhen `MEMORY_STORAGE_TYPE=sqlite`, the system uses:\n- `memory.db` - Single-file relational database\n\nThe SQLite backend provides better performance for large datasets and supports advanced query capabilities through the storage layer.\n\n资料来源：[CLAUDE.md:Storage]()\n\n## Entry Points\n\n| Entry Point | Description |\n|-------------|-------------|\n| `dist/index.js` | Built output for npm distribution |\n| `mcp-server-memory` | CLI binary defined in package.json `bin` field |\n| `src/index.ts` | Source entry point |\n\n资料来源：[CLAUDE.md:Entry Points]()\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant ToolHandler\n    participant ManagerContext\n    participant Manager\n    participant Storage\n    \n    Client->>MCPServer: MCP Request\n    MCPServer->>ToolHandler: Route to handler\n    ToolHandler->>ManagerContext: Access manager\n    ManagerContext->>Manager: Lazy initialization\n    Manager->>Storage: Read/Write operations\n    Storage-->>Manager: Data\n    Manager-->>ManagerContext: Result\n    ManagerContext-->>ToolHandler: Structured response\n    ToolHandler-->>MCPServer: Formatted response\n    MCPServer-->>Client: MCP Response\n```\n\n## Standalone Tools\n\nThe `tools/` directory contains standalone utilities with their own `package.json` files, buildable to Windows executables via pkg:\n\n| Tool | Purpose |\n|------|---------|\n| `chunking-for-files` | Split/merge large files for context-limited editing |\n| `compress-for-context` | CTON compression for LLM context windows |\n| `create-dependency-graph` | Generate TypeScript project dependency graphs |\n| `migrate-from-jsonl-to-sqlite` | Convert between JSONL and SQLite formats |\n\n资料来源：[CLAUDE.md:Standalone Tools]()\n\n## Version History\n\nThe architecture has evolved through multiple phases:\n\n| Phase | Version | Key Changes |\n|-------|---------|-------------|\n| Phase 13 | Initial | 5 TypeScript source files, memoryjs v2.1.0+ |\n| Phase 15 | v12.2.0 | 23 tools for memoryjs v1.14+ features (bitemporal, OCC, RBAC) |\n| Phase 16 | v12.3.0 | 53 tools for memoryjs v2.1.0 (exclusions, ADR, context, heuristics) |\n\n资料来源：[CLAUDE.md:Phase History]()\n\n## npm Package Information\n\n- **Package**: `@danielsimonjr/memory-mcp`\n- **Core Dependency**: `@danielsimonjr/memoryjs` (version specified in package.json)\n\n资料来源：[CLAUDE.md:npm Information]()\n\n---\n\n<a id='storage-backends'></a>\n\n## Storage Backends\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Entity-Relation-Observation Model](#entity-model)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts)\n- [tools/migrate-from-jsonl-to-sqlite/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/migrate-from-jsonl-to-sqlite/README.md)\n- [tools/migrate-from-jsonl-to-sqlite/package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/migrate-from-jsonl-to-sqlite/package.json)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [SECURITY.md](https://github.com/danielsimonjr/memory-mcp/blob/main/SECURITY.md)\n</details>\n\n# Storage Backends\n\nThe Memory MCP server implements a dual-storage backend architecture that supports both **JSONL (JSON Lines)** and **SQLite** formats for persisting knowledge graph data. This flexible design allows users to choose the most appropriate storage mechanism based on dataset size, performance requirements, and debugging preferences.\n\n## Architecture Overview\n\nThe storage layer handles all persistence operations for entities, relations, and associated metadata within the knowledge graph. The architecture separates the storage format from the core application logic, enabling seamless migration between formats without losing data integrity.\n\n```mermaid\ngraph TD\n    A[Memory MCP Server] --> B[Storage Abstraction Layer]\n    B --> C[JSONL Backend]\n    B --> D[SQLite Backend]\n    C --> E[memory.jsonl]\n    D --> F[memory.db]\n    D --> G[FTS5 Index]\n    \n    style A fill:#e1f5fe\n    style B fill:#fff3e0\n    style E fill:#f3e5f5\n    style F fill:#e8f5e9\n    style G fill:#e8f5e9\n```\n\n## Data Models\n\n### KnowledgeGraph Structure\n\nThe knowledge graph comprises two primary collections that together represent the complete state of the memory system.\n\n| Collection | Type | Description |\n|------------|------|-------------|\n| `entities` | Entity[] | Individual memory items with observations and metadata |\n| `relations` | Relation[] | Connections between entities defining semantic relationships |\n\n### Entity Model\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `name` | string | Yes | Unique identifier for the entity |\n| `entityType` | string | Yes | Classification category (e.g., \"person\", \"concept\", \"task\") |\n| `observations` | string[] | Yes | Array of recorded facts or data points |\n| `createdAt` | string | No | ISO timestamp of entity creation |\n| `lastModified` | string | No | ISO timestamp of last modification |\n| `tags` | string[] | No | Optional categorization labels |\n| `importance` | number | No | Priority score (null if unspecified) |\n| `parentId` | string | No | Hierarchical parent reference |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:50-58]()\n\n### Relation Model\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `from` | string | Yes | Source entity name or ID |\n| `to` | string | Yes | Target entity name or ID |\n| `relationType` | string | Yes | Semantic relationship type (e.g., \"related_to\", \"part_of\") |\n| `createdAt` | string | No | ISO timestamp of relation creation |\n| `lastModified` | string | No | ISO timestamp of last modification |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:60-66]()\n\n## Supported Storage Formats\n\n### JSONL Format\n\nThe **JSONL (JSON Lines)** backend stores each entity and relation as a separate JSON object on its own line within plain text files. This format provides human-readable data and simple version control compatibility.\n\n**File Locations (Project Root):**\n\n| File | Purpose |\n|------|---------|\n| `memory.jsonl` | Primary knowledge graph storage |\n| `memory-saved-searches.jsonl` | Stored search configurations |\n| `memory-tag-aliases.jsonl` | Tag normalization mappings |\n\n资料来源：[CLAUDE.md:2-9]()\n\n**Characteristics:**\n\n- Default storage format when no configuration is provided\n- Each line contains a valid JSON object\n- Easy to inspect, edit, and debug\n- Direct compatibility with text editors and version control systems\n- Recommended for datasets under 1,000 entities\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/README.md:45-55]()\n\n### SQLite Format\n\nThe **SQLite** backend provides a relational database optimized for larger datasets and concurrent access patterns. It offers ACID transaction support and full-text search capabilities through FTS5.\n\n**File Location (Project Root):**\n\n| File | Purpose |\n|------|---------|\n| `memory.db` | Primary SQLite database |\n\n资料来源：[CLAUDE.md:6]()\n\n**SQLite Backend Features:**\n\n| Feature | Description |\n|---------|-------------|\n| FTS5 Index | Automatic full-text search indexing for fast entity lookups |\n| WAL Mode | Write-Ahead Logging for improved concurrent read/write performance |\n| Atomic Transactions | Ensures data integrity during write operations |\n| Native Performance | Uses better-sqlite3 for 3-10x faster operations compared to WASM alternatives |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:14-15]()\n\n## Environment Configuration\n\nStorage behavior is controlled through environment variables that must be set before server initialization.\n\n### Configuration Variables\n\n| Variable | Values | Default | Description |\n|----------|--------|---------|-------------|\n| `MEMORY_STORAGE_TYPE` | `jsonl`, `sqlite` | `jsonl` | Determines which storage backend to use |\n| `MEMORY_FILE_PATH` | Valid file path | `memory.jsonl` (cwd) | Absolute or relative path to primary storage file |\n\n资料来源：[CLAUDE.md:24-28]()\n\n### Configuration Examples\n\n**JSONL (Default):**\n```bash\n# No environment variables needed - defaults to JSONL\n```\n\n**SQLite:**\n```json\n{\n  \"mcpServers\": {\n    \"memory\": {\n      \"command\": \"node\",\n      \"args\": [\"/path/to/memory-mcp/src/memory/dist/index.js\"],\n      \"env\": {\n        \"MEMORY_STORAGE_TYPE\": \"sqlite\",\n        \"MEMORY_FILE_PATH\": \"/path/to/memory.db\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/README.md:70-79]()\n\n## Migration Between Formats\n\nThe `migrate-from-jsonl-to-sqlite` tool provides bidirectional conversion between JSONL and SQLite storage formats. This enables users to start with simple JSONL storage and migrate to SQLite as their dataset grows.\n\n### Supported File Extensions\n\n| Format | Extensions | Detection Logic |\n|--------|------------|-----------------|\n| JSONL | `.jsonl`, `.json` | Extension-based detection |\n| SQLite | `.db`, `.sqlite`, `.sqlite3` | Extension-based detection |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:97-103]()\n\n### Migration Tool Usage\n\n```bash\n# JSONL to SQLite migration\nmigrate-from-jsonl-to-sqlite --from memory.jsonl --to memory.db\n\n# SQLite to JSONL migration\nmigrate-from-jsonl-to-sqlite --from memory.db --to memory.jsonl\n\n# Using positional arguments\nmigrate-from-jsonl-to-sqlite memory.jsonl memory.db\n\n# Verbose output for troubleshooting\nmigrate-from-jsonl-to-sqlite -f memory.jsonl -t memory.db -v\n```\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:1-30]()\n\n### Migration Options\n\n| Argument | Short | Description |\n|----------|-------|-------------|\n| `--from` | `-f` | Source file path (JSONL or SQLite) |\n| `--to` | `-t` | Target file path (JSONL or SQLite) |\n| `--verbose` | `-v` | Show detailed progress information |\n| `--help` | `-h` | Display help message |\n\n### Migration Workflow\n\n```mermaid\ngraph TD\n    A[Start Migration] --> B{Detect Source Format}\n    B -->|JSONL| C[loadFromJsonl]\n    B -->|SQLite| D[loadFromSqlite]\n    C --> E[Parse Knowledge Graph]\n    D --> E\n    E --> F{Validate Timestamps}\n    F -->|Missing createdAt| G[Set to migration time + warn]\n    F -->|Missing lastModified| H[Set to migration time + warn]\n    G --> I\n    H --> I[Write to Target Format]\n    I -->|JSONL| J[writeToJsonl]\n    I -->|SQLite| K[Initialize FTS5 + WAL]\n    J --> L[Migration Complete]\n    K --> L\n```\n\n### Migration Notes and Limitations\n\n| Aspect | Behavior |\n|--------|----------|\n| **Target Creation** | Target file is created if it doesn't exist |\n| **Existing Targets** | Target file will be overwritten if it exists |\n| **Data Integrity** | Atomic transactions ensure no data loss during migration |\n| **Timestamp Handling** | Missing `createdAt` or `lastModified` fields are populated with migration timestamp and a warning is displayed |\n| **Saved Searches** | NOT migrated (stored in separate `memory-saved-searches.jsonl` file) |\n| **Tag Aliases** | NOT migrated (stored in separate `memory-tag-aliases.jsonl` file) |\n| **Large Datasets** | Recommended for graphs with 10,000+ entities |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/README.md:20-25]()\n\n## Format Selection Guide\n\nChoose the appropriate storage backend based on your specific use case and dataset characteristics.\n\n| Criteria | JSONL | SQLite |\n|----------|-------|--------|\n| Dataset Size | < 1,000 entities | 10,000+ entities |\n| Transaction Needs | Simple append operations | ACID transactions required |\n| Data Inspection | Human-readable preferred | Structured queries needed |\n| Concurrent Access | Single process | Multiple readers/writers |\n| Debugging | Direct file inspection | Requires SQLite tools |\n| Performance | Sufficient for small datasets | Optimized for large graphs |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/README.md:45-55]()\n\n## Security Considerations\n\nWhen configuring storage backends, consider the following security implications documented in the project's security guidelines.\n\n### File Permissions\n\nThe storage files contain all knowledge graph data and should be protected with appropriate file system permissions:\n\n```json\n{\n  \"mcpServers\": {\n    \"memory\": {\n      \"command\": \"node\",\n      \"args\": [\"/path/to/memory-mcp/src/memory/dist/index.js\"],\n      \"env\": {\n        \"MEMORY_FILE_PATH\": \"/secure/path/memory.jsonl\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[SECURITY.md:8-18]()\n\n### Data Sensitivity\n\n| Format | Export Considerations |\n|--------|----------------------|\n| JSONL/JSON | Full entity data visible in plain text |\n| SQLite | Database contents require database tools to inspect |\n| CSV/GraphML Exports | Full data included; filter parameters can limit exported data |\n\n资料来源：[SECURITY.md:19-26]()\n\n## Tool Dependencies\n\nThe SQLite backend and migration tool rely on the `better-sqlite3` package for native performance:\n\n```json\n{\n  \"name\": \"migrate-from-jsonl-to-sqlite\",\n  \"version\": \"1.1.0\",\n  \"dependencies\": {\n    \"better-sqlite3\": \"^11.7.0\"\n  },\n  \"devDependencies\": {\n    \"@types/better-sqlite3\": \"^7.6.12\"\n  }\n}\n```\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/package.json:1-12]()\n\nThe package is configured with `yao-pkg/pkg` for building standalone executables targeting `node22-win-x64`.\n\n## Related Documentation\n\n| Document | Description |\n|----------|-------------|\n| [CLAUDE.md](CLAUDE.md) | Project architecture and development guidelines |\n| [tools/migrate-from-jsonl-to-sqlite/README.md](tools/migrate-from-jsonl-to-sqlite/README.md) | Detailed migration tool documentation |\n| [SECURITY.md](SECURITY.md) | Security considerations for data storage |\n\n---\n\n<a id='entity-model'></a>\n\n## Entity-Relation-Observation Model\n\n### 相关页面\n\n相关主题：[Search Capabilities](#search-capabilities), [Temporal and Advanced Features](#temporal-features)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/index.ts)\n- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n</details>\n\n# Entity-Relation-Observation Model\n\nThe Entity-Relation-Observation (ERO) Model is the core data architecture powering the Enhanced Memory MCP server. It implements a temporal knowledge graph where **entities** represent nodes in a graph, **relations** represent directed edges between entities, and **observations** attach factual metadata to entities.\n\n## Architecture Overview\n\nThe ERO Model is built on the layered architecture of memoryjs (v^2.1.0), where the `ManagerContext` provides lazy-initialized access to specialized managers:\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (MCP Server Layer)\"\n        MCPS[MCPServer]\n        TH[ToolHandlers]\n        TD[ToolDefinitions]\n    end\n    \n    subgraph \"memoryjs (Core Library Layer)\"\n        MC[ManagerContext]\n        EM[EntityManager]\n        RM[RelationManager]\n        OM[ObservationManager]\n        SM[SearchManager]\n    end\n    \n    MCPS --> TH\n    TH --> TD\n    TH --> MC\n    MC --> EM\n    MC --> RM\n    MC --> OM\n    MC --> SM\n    \n    subgraph \"Storage Layer\"\n        GS[GraphStorage]\n        SS[SQLiteStorage]\n        JL[JSONLStorage]\n    end\n    \n    MC --> GS\n    GS --> SS\n    GS --> JL\n```\n\n资料来源：[CLAUDE.md:layered-architecture](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Core Components\n\n### Entity Manager\n\nEntities are the primary nodes in the knowledge graph. The EntityManager provides core CRUD operations:\n\n| Operation | Tool Name | Description |\n|-----------|-----------|-------------|\n| Create | `create_entity` | Add a new entity to the graph |\n| Read | `get_entity` | Retrieve entity by name or ref |\n| Update | `update_entity` | Modify entity properties |\n| Delete | `delete_entities` | Remove entity from graph |\n| List | `list_entities` | Get entities with optional filters |\n\n资料来源：[toolDefinitions.ts:entity-tools](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n\n**Entity Properties:**\n- `name` (required): Unique identifier\n- `memoryType`: Classification type (default: `semantic`)\n- `confidence`: Trust score (0.0 - 1.0, default: 0.8)\n- `tags`: Array of associated tags\n- `observations`: Attached factual metadata\n- `createdAt` / `updatedAt`: Temporal timestamps\n- `accessCount`: Usage tracking\n- `confirmationCount`: Verification count\n\n### Relation Manager\n\nRelations are directed edges connecting entities with typed relationships. The RelationManager handles:\n\n```mermaid\ngraph LR\n    E1[Entity A] -->|\"created_by\"| R[Relation]\n    R -->|\"part_of\"| E2[Entity B]\n    E1 -->|\"depends_on\"| R2[Relation]\n    R2 -->|\"implements\"| E3[Entity C]\n```\n\n| Operation | Tool Name | Description |\n|-----------|-----------|-------------|\n| Create | `create_relations` | Batch create directed edges |\n| Delete | `delete_relations` | Remove relations by criteria |\n| Invalidate | `invalidate_relation` | Bitemporal validity - end a relation |\n| Chain | `get_entity_chain` | Traverse relation paths between entities |\n\n资料来源：[toolHandlers.ts:relation-handlers](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n**Relation Schema:**\n```typescript\ninterface Relation {\n  from: string;      // Source entity name/ref\n  relationType: string; // Relationship type (e.g., \"depends_on\", \"part_of\")\n  to: string;        // Target entity name/ref\n  ended?: string;    // Bitemporal end timestamp (undefined = active)\n}\n```\n\n### Observation Manager\n\nObservations are factual statements attached to entities, providing evidence and context:\n\n| Property | Description |\n|----------|-------------|\n| `content` | The factual statement |\n| `normalized` | Canonical form for comparison |\n| `source` | Origin of the observation |\n| `confirmed` | Verification status |\n| `attachedAt` | Timestamp when attached |\n\n资料来源：[CLAUDE.md:observation](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n**Key Features:**\n- Content normalization for deduplication\n- Source tracking for provenance\n- Confirmation counting for consensus-based truth\n\n## Tool Categories\n\nThe ERO Model exposes 213 tools across 58 categories:\n\n| Category | Count | Purpose |\n|----------|-------|---------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities |\n| Search | 7 | Query graph data |\n| Intelligent Search | 3 | Advanced query processing |\n| Semantic Search | 3 | Embedding-based retrieval |\n| Tag Management | 6 | Entity categorization |\n| Hierarchy | 9 | Parent-child tree structures |\n| Graph Algorithms | 4 | Path finding, centrality |\n| Analytics | 2 | Graph statistics |\n| Compression | 4 | Deduplication, archiving |\n\n资料来源：[CLAUDE.md:tool-categories](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPS as MCPServer\n    participant TH as ToolHandlers\n    participant MC as ManagerContext\n    participant Storage as GraphStorage\n\n    Client->>MCPS: create_entity({ name, tags, observations })\n    MCPS->>TH: Route to create_entity handler\n    TH->>MC: ctx.entityManager.createEntity()\n    MC->>Storage: saveGraph(graph)\n    Storage-->>MC: Success\n    MC-->>TH: Entity result\n    TH-->>MCPS: Formatted response\n    MCPS-->>Client: { content: [...] }\n```\n\n## Storage Layer\n\nThe ERO Model supports two storage backends:\n\n### JSONL Storage (Default)\n- **File**: `memory.jsonl` (project root)\n- **Format**: One JSON object per line\n- **Additional files**: `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl`\n\n### SQLite Storage\n- **File**: `memory.db` (project root)\n- **Enable**: Set `MEMORY_STORAGE_TYPE=sqlite`\n- **Benefits**: Queryable, relational operations\n\n资料来源：[CLAUDE.md:storage](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Bitemporal Validity\n\nRelations support bitemporal validity for tracking historical state:\n\n```mermaid\ngraph TD\n    A[Entity A] -->|created: 2024-01-01| R1[Active Relation]\n    A -->|ended: 2024-02-15| R2[Historical Relation]\n    \n    subgraph \"Timeline\"\n        T1[Jan 2024]\n        T2[Feb 2024]\n        T3[Current]\n    end\n    \n    R1 --> T3\n    R2 --> T2\n```\n\nThe `invalidate_relation` tool terminates a relation at a specified timestamp:\n```typescript\ninvalidate_relation(from, relationType, to, ended?)\n```\n\n资料来源：[toolHandlers.ts:invalidate-relation](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n## Hierarchy Integration\n\nEntities can form hierarchical trees through the HierarchyManager:\n\n| Tool | Purpose |\n|------|---------|\n| `set_entity_parent` | Assign parent entity |\n| `get_children` | Direct descendants |\n| `get_parent` | Direct ancestor |\n| `get_ancestors` | Full ancestry path |\n| `get_descendants` | All descendants (recursive) |\n| `get_subtree` | Subtree structure |\n\n资料来源：[toolHandlers.ts:hierarchy-handlers](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n## Search Capabilities\n\nThe ERO Model provides layered search:\n\n```mermaid\ngraph TD\n    Q[Query] --> BS[Basic Search]\n    Q --> RS[Ranked Search]\n    Q --> FS[Fuzzy Search]\n    Q --> SS[Semantic Search]\n    \n    BS -->|TF-IDF| R1[Results]\n    RS -->|Ranked| R2[Results]\n    FS -->|Edit Distance| R3[Results]\n    SS -->|Embeddings| R4[Results]\n    \n    subgraph \"Intelligent Search\"\n        QA[Query Analysis]\n        QR[Query Reflection]\n    end\n    \n    Q --> QA\n    QA --> QR\n    QR --> R5[Intelligent Results]\n```\n\n**Search Types:**\n1. **Basic**: Exact and substring matching\n2. **Ranked (TF-IDF)**: Term frequency-inverse document frequency\n3. **Fuzzy**: Edit distance tolerance\n4. **Semantic**: Embedding similarity (OpenAI or local models)\n5. **Intelligent**: Multi-layer hybrid with query analysis\n\n资料来源：[CLAUDE.md:search](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Environment Configuration\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `MEMORY_FILE_PATH` | Storage file path | `memory.jsonl` |\n| `MEMORY_STORAGE_TYPE` | Backend type | `jsonl` |\n| `MEMORY_EMBEDDING_PROVIDER` | Embedding service | `none` |\n| `MEMORY_OPENAI_API_KEY` | API key for OpenAI | — |\n| `MEMORY_EMBEDDING_MODEL` | Model name | `text-embedding-3-small` |\n| `MEMORY_AUTO_INDEX_EMBEDDINGS` | Auto-index on create | `false` |\n\n资料来源：[CLAUDE.md:env-vars](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## API Entry Points\n\n| Endpoint | Description |\n|----------|-------------|\n| `dist/index.js` | Build output entry |\n| `src/index.ts` | Source entry (exports ManagerContext as KnowledgeGraphManager) |\n| `mcp-server-memory` | CLI binary |\n\n资料来源：[package.json:exports](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n\n## Adding Custom Tools\n\nTo extend the ERO Model with new functionality:\n\n1. **Define Schema** in `toolDefinitions.ts`:\n```typescript\n{\n  name: 'new_tool',\n  description: 'Tool description',\n  inputSchema: {\n    type: 'object',\n    properties: { /* parameters */ },\n    required: ['param1']\n  }\n}\n```\n\n2. **Implement Handler** in `toolHandlers.ts`:\n```typescript\nnew_tool: async (ctx, args) => {\n  // Validate arguments\n  // Call manager methods\n  // Return formatted response\n}\n```\n\n3. **Add Tests** in `tests/e2e/tools/`\n\n资料来源：[CLAUDE.md:adding-tools](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n---\n\n<a id='tool-reference'></a>\n\n## Tool Reference\n\n### 相关页面\n\n相关主题：[Search Capabilities](#search-capabilities), [Temporal and Advanced Features](#temporal-features), [Collaboration and Security](#collaboration-security)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)\n- [src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)\n</details>\n\n# Tool Reference\n\n## Overview\n\nThe Tool Reference documents the 213 MCP tools exposed by memory-mcp, organized across 58 categories. These tools provide a comprehensive interface for managing a persistent knowledge graph that supports entity storage, relationship mapping, semantic search, and temporal reasoning capabilities.\n\nThe tool layer acts as a bridge between MCP clients and the underlying `ManagerContext` system, which provides access to specialized managers for entities, relations, observations, search, tags, hierarchies, analytics, compression, and I/O operations. 资料来源：[CLAUDE.md:1-5]()\n\n## Architecture\n\n### Layered Design\n\n```mermaid\ngraph TD\n    A[MCP Client] --> B[MCPServer]\n    B --> C[Tool Definitions]\n    B --> D[Tool Handlers]\n    C --> E[Schema Validation]\n    D --> F[ManagerContext]\n    F --> G[memoryjs Library]\n    F --> H[GraphStorage]\n    G --> I[SQLite/JSONL]\n    \n    subgraph Managers\n        F --> J[EntityManager]\n        F --> K[RelationManager]\n        F --> L[SearchManager]\n        F --> M[ObservationManager]\n        F --> N[TagManager]\n        F --> O[HierarchyManager]\n        F --> P[AnalyticsManager]\n    end\n```\n\nThe architecture follows a layered approach where tool definitions declare schemas using JSON Schema format, handlers implement business logic by calling manager methods, and the `ManagerContext` provides lazy-initialized access to specialized subsystems. 资料来源：[CLAUDE.md:8-12]()\n\n### Tool Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant Handler\n    participant Manager\n    participant Storage\n    \n    Client->>MCPServer: Tool Call Request\n    MCPServer->>Handler: Dispatch with args\n    Handler->>Handler: Validate with Zod schema\n    Handler->>Manager: Call manager method\n    Manager->>Storage: Read/Write data\n    Storage-->>Manager: Result\n    Manager-->>Handler: Response\n    Handler->>Handler: Format response\n    Handler-->>MCPServer: ToolResponse\n    MCPServer-->>Client: MCP-formatted result\n```\n\nError handling in dispatch catches exceptions from handlers and returns them as MCP-formatted error responses rather than throwing. The MCP response `isError` field indicates failures. 资料来源：[CLAUDE.md:85-87]()\n\n## Tool Categories\n\nThe tools are organized into 58 categories spanning core graph operations to advanced features like bitemporal validity and causal reasoning.\n\n| Category | Count | Key Purpose |\n|----------|-------|-------------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities, with normalization |\n| Search | 7 | Basic, ranked (TF-IDF), boolean, fuzzy, auto-select |\n| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |\n| Semantic Search | 3 | Embedding similarity via OpenAI or local models |\n| Saved Searches | 5 | Store and re-execute frequent queries |\n| Tag Management | 6 | Tags, bulk ops, importance scores |\n| Tag Aliases | 5 | Tag synonym/alias management |\n| Hierarchy | 9 | Parent-child trees, subtree traversal |\n| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |\n| Analytics | 2 | Graph stats and integrity validation |\n| Compression | 4 | Duplicate detection, merge, auto-compress, archive |\n| Import/Export | 2 | 7 export formats |\n\n资料来源：[CLAUDE.md:30-44]()\n\n## Tool Definition Schema\n\nEach tool is defined with a JSON Schema that specifies input parameters. The schema follows a consistent pattern:\n\n```typescript\n{\n  name: 'tool_name',\n  description: 'Human-readable description of tool purpose',\n  inputSchema: {\n    type: 'object',\n    properties: {\n      paramName: { \n        type: 'string', \n        description: 'Parameter description',\n        enum: ['option1', 'option2'] // optional for constrained values\n      },\n    },\n    required: ['paramName'], // mandatory parameters\n    additionalProperties: false,\n  },\n}\n```\n\n资料来源：[src/server/toolDefinitions.ts:1-20]()\n\n### Example: Artifact Tool Definition\n\n```typescript\n{\n  name: 'create_artifact',\n  description: 'Create an artifact entity (tool output, code snippet, API response, etc.) with a stable auto-generated ref',\n  inputSchema: {\n    type: 'object',\n    properties: {\n      content: { type: 'string', description: 'Artifact content stored as an entity observation' },\n      toolName: { type: 'string', description: 'Name of the tool or source that produced this artifact' },\n      artifactType: {\n        type: 'string',\n        enum: ['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input'],\n        description: 'Category of artifact for structured filtering',\n      },\n      description: { type: 'string', description: 'Optional human-readable description' },\n      sessionId: { type: 'string', description: 'Optional session context for grouping related artifacts' },\n    },\n    required: ['content', 'toolName', 'artifactType'],\n    additionalProperties: false,\n  },\n}\n```\n\n资料来源：[src/server/toolDefinitions.ts:90-115]()\n\n## Handler Implementation Pattern\n\nTool handlers follow a consistent implementation pattern across all 213 tools:\n\n```typescript\ntool_name: async (ctx, args) => {\n  // 1. Validate required arguments\n  const param = validateWithSchema(args.param, z.string().min(1), 'Invalid param');\n  \n  // 2. Build filter/options objects\n  const filter: FilterType = {};\n  if (args.optionalParam !== undefined) {\n    filter.optionalParam = validateWithSchema(args.optionalParam, z.string(), 'Invalid optionalParam');\n  }\n  \n  // 3. Call manager method\n  const result = await getManager(ctx).method(filter);\n  \n  // 4. Format and return response\n  return formatToolResponse(result);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:1-30]()\n\n### Validation with Zod\n\nHandlers use Zod schemas for runtime validation:\n\n| Zod Function | Usage |\n|--------------|-------|\n| `z.string().min(1)` | Non-empty string |\n| `z.number().int().min(1).max(1000)` | Bounded integer |\n| `z.enum(['option1', 'option2'])` | Constrained string |\n| `z.boolean()` | Boolean flag |\n| `z.string().regex(/pattern/)` | Pattern-matched string |\n| `z.record(z.string(), z.unknown())` | Dictionary object |\n\n```typescript\nconst ref = validateWithSchema(args.ref, z.string().min(1), 'Invalid ref');\nconst limit = validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit');\nconst artifactType = validateWithSchema(\n  args.artifactType,\n  z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n  'Invalid artifactType'\n);\n```\n\n资料来源：[src/server/toolHandlers.ts:5-25]()\n\n## Artifact Tools\n\nArtifact tools manage tool outputs, code snippets, API responses, and other generated content with stable references.\n\n### create_artifact\n\nCreates an artifact entity with a stable auto-generated reference.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `content` | string | Yes | Artifact content stored as an entity observation |\n| `toolName` | string | Yes | Name of the tool or source that produced this artifact |\n| `artifactType` | enum | Yes | Category: `tool_output`, `code_snippet`, `api_response`, `search_result`, `file_content`, `user_input` |\n| `description` | string | No | Human-readable description |\n| `sessionId` | string | No | Session context for grouping related artifacts |\n\n```typescript\ncreate_artifact: async (ctx, args) => {\n  const content = validateWithSchema(args.content, z.string().min(1), 'Invalid content');\n  const toolName = validateWithSchema(args.toolName, z.string().min(1), 'Invalid toolName');\n  const artifactType = validateWithSchema(\n    args.artifactType,\n    z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n    'Invalid artifactType'\n  );\n  const description = args.description !== undefined\n    ? validateWithSchema(args.description, z.string(), 'Invalid description')\n    : undefined;\n  const sessionId = args.sessionId !== undefined\n    ? validateWithSchema(args.sessionId, z.string(), 'Invalid sessionId')\n    : undefined;\n  const artifact = await getArtifactManager(ctx).createArtifact({\n    content, toolName, artifactType, description, sessionId,\n  });\n  return formatToolResponse(artifact);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:290-315]()\n\n### get_artifact\n\nRetrieves an artifact entity by its stable ref or entity name.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `ref` | string | Yes | Stable ref or entity name (e.g. \"bash-2026-03-24-a3f2\") |\n\n```typescript\nget_artifact: async (ctx, args) => {\n  const ref = validateWithSchema(args.ref, z.string().min(1), 'Invalid ref');\n  const artifact = await getArtifactManager(ctx).getArtifact(ref);\n  if (!artifact) {\n    return formatTextResponse(`Artifact \"${ref}\" not found`);\n  }\n  return formatToolResponse(artifact);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:318-328]()\n\n### list_artifacts\n\nLists artifacts with optional filtering by tool name, type, or time.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `toolName` | string | No | Filter by originating tool |\n| `artifactType` | enum | No | Filter by artifact category |\n| `since` | string | No | ISO 8601 timestamp for time-based filtering |\n\n```typescript\nlist_artifacts: async (ctx, args) => {\n  const filter: ArtifactFilter = {};\n  if (args.toolName !== undefined) {\n    filter.toolName = validateWithSchema(args.toolName, z.string(), 'Invalid toolName');\n  }\n  if (args.artifactType !== undefined) {\n    filter.artifactType = validateWithSchema(\n      args.artifactType,\n      z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n      'Invalid artifactType'\n    );\n  }\n  if (args.since !== undefined) {\n    const sinceStr = validateWithSchema(args.since, z.string().regex(/^\\d{4}-\\d{2}-\\d{2}(T[\\d:.Z+-]+)?$/, 'since must be an ISO 8601 date string'), 'Invalid since');\n    const sinceDate = new Date(sinceStr);\n    if (isNaN(sinceDate.getTime())) {\n      throw new Error(`Invalid since date: \"${sinceStr}\" is not a valid date`);\n    }\n    filter.since = sinceDate;\n  }\n  const artifacts = await getArtifactManager(ctx).listArtifacts(Object.keys(filter).length > 0 ? filter : undefined);\n  return formatToolResponse({ artifacts, count: artifacts.length });\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:330-360]()\n\n## Decay and Salience Tools\n\nThese tools manage memory importance over time using time-based decay algorithms.\n\n### run_decay_cycle\n\nRuns a single pass of time-based importance decay across all agent memories.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| (none) | - | - | No parameters required |\n\nReturns the count of decayed and forgotten memories. 资料来源：[src/server/toolDefinitions.ts:180-195]()\n\n### get_decayed_memories\n\nLists memories whose importance has fallen below a threshold due to time-based decay.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `threshold` | number | No | Importance threshold (default: 0.1) |\n\nUnlike `get_stale_entities` which uses freshness timestamps, this tool uses decay engine importance calculations. 资料来源：[src/server/toolDefinitions.ts:197-208]()\n\n### forget_weak_memories\n\nBulk-deletes memories that fell below a decay threshold.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `threshold` | number | No | Importance threshold below which to forget |\n| `maxCount` | number | No | Maximum number of memories to forget |\n| `dryRun` | boolean | No | If true, report what would be forgotten without deleting |\n\nUnlike `forget_memory` (content match) or `archive_entities` (criteria-based move), this uses decay-based importance scoring. 资料来源：[src/server/toolDefinitions.ts:210-222]()\n\n## Governance and Audit Tools\n\n### audit_query\n\nQueries the audit log for operations matching specified criteria.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `operation` | enum | No | Filter by: `create`, `update`, `delete`, `merge`, `archive` |\n| `agentId` | string | No | Filter by agent identifier |\n| `entityName` | string | No | Filter by entity name |\n| `since` | string | No | Start time (ISO 8601) |\n| `until` | string | No | End time (ISO 8601) |\n| `limit` | number | No | Maximum entries to return (default: 50, max: 1000) |\n\n```typescript\naudit_query: async (ctx, args) => {\n  const filter: AuditFilter = {};\n  if (args.operation !== undefined) {\n    filter.operation = validateWithSchema(\n      args.operation,\n      z.enum(['create', 'update', 'delete', 'merge', 'archive']),\n      'Invalid operation'\n    ) as AuditFilter['operation'];\n  }\n  if (args.agentId !== undefined) {\n    filter.agentId = validateWithSchema(args.agentId, z.string(), 'Invalid agentId');\n  }\n  if (args.entityName !== undefined) {\n    filter.entityName = validateWithSchema(args.entityName, z.string(), 'Invalid entityName');\n  }\n  // AuditFilter uses fromTime/toTime (not since/until)\n  if (args.since !== undefined) {\n    filter.fromTime = validateWithSchema(args.since, z.string(), 'Invalid since');\n  }\n  if (args.until !== undefined) {\n    filter.toTime = validateWithSchema(args.until, z.string(), 'Invalid until');\n  }\n  const limit = args.limit !== undefined\n    ? validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit')\n    : 50;\n  const al = getAuditLog(ctx);\n  let entries = await al.query(filter);\n  entries = entries.slice(0, limit);\n  return formatToolResponse({ entries, count: entries.length });\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:400-440]()\n\n## Adding New Tools\n\nThe development workflow for adding a new tool follows a three-step process:\n\n```mermaid\ngraph LR\n    A[1. Add schema to toolDefinitions.ts] --> B[2. Add handler to toolHandlers.ts]\n    B --> C[3. Add e2e test in tests/e2e/tools/]\n```\n\n1. **Add schema to `toolDefinitions.ts`** — Define the tool name, description, and input schema in the appropriate category section\n2. **Add handler to `toolHandlers.ts`** — Register handler in the `TOOL_HANDLERS` registry with the pattern: validate args → call manager method → return formatted response\n3. **Add e2e test** — Create test coverage in `tests/e2e/tools/` 资料来源：[CONTRIBUTING.md:55-62]()\n\n### Handler Pattern Template\n\n```typescript\n// ==================== CATEGORY_NAME ====================\ntool_name: async (ctx, args) => {\n  // Validate required arguments\n  const required = validateWithSchema(args.required, z.string().min(1), 'Invalid required');\n  \n  // Build options object with optional parameters\n  const options: OptionsType = {};\n  if (args.optional !== undefined) {\n    options.optional = validateWithSchema(args.optional, z.string(), 'Invalid optional');\n  }\n  \n  // Call manager method\n  const result = await getManager(ctx).method(options);\n  \n  // Return formatted response\n  return formatToolResponse(result);\n},\n```\n\nIf the response can be large, wrap the handler result with `withCompression()`. 资料来源：[CONTRIBUTING.md:58-60]()\n\n## Environment Configuration\n\nTools honor the following environment variables:\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `MEMORY_FILE_PATH` | Path to storage file | `memory.jsonl` (cwd) |\n| `MEMORY_STORAGE_TYPE` | `jsonl` or `sqlite` | `jsonl` |\n| `MEMORY_EMBEDDING_PROVIDER` | `openai`, `local`, or `none` | `none` |\n| `MEMORY_OPENAI_API_KEY` | Required if provider is `openai` | — |\n| `MEMORY_EMBEDDING_MODEL` | Embedding model name | `text-embedding-3-small` / `Xenova/all-MiniLM-L6-v2` |\n| `MEMORY_AUTO_INDEX_EMBEDDINGS` | Auto-index on entity creation | `false` |\n\n资料来源：[CLAUDE.md:66-73]()\n\n## ManagerContext Accessors\n\nHandlers access underlying functionality through the ManagerContext:\n\n| Accessor | Purpose |\n|----------|---------|\n| `ctx.entityManager` | Core entity CRUD operations |\n| `ctx.relationManager` | Relationship management |\n| `ctx.observationManager` | Fact attachment to entities |\n| `ctx.searchManager` | Full-text and ranked search |\n| `ctx.tagManager` | Tag CRUD and bulk operations |\n| `ctx.hierarchyManager` | Tree structures and traversal |\n| `ctx.analyticsManager` | Graph statistics |\n| `ctx.compressionManager` | Deduplication and archiving |\n| `ctx.archiveManager` | Historical data management |\n| `ctx.ioManager` | Import/export operations |\n| `ctx.graphTraversal` | Path finding algorithms |\n| `ctx.semanticSearch` | Embedding-based similarity |\n| `ctx.rankedSearch` | TF-IDF ranking |\n| `ctx.storage` | Direct GraphStorage access |\n\n资料来源：[CLAUDE.md:13-26]()\n\n## Storage Backend\n\nTools persist data to the **project root** (not `dist/`):\n\n| Format | Files |\n|--------|-------|\n| JSONL | `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl` |\n| SQLite | `memory.db` (set `MEMORY_STORAGE_TYPE=sqlite`) |\n\nThe `prepare` script runs `npm run build` on install, so `dist/` is rebuilt automatically. 资料来源：[CLAUDE.md:48-55]()\n\n## Response Formatting\n\nHandlers return responses using two formatting functions:\n\n| Function | Usage |\n|----------|-------|\n| `formatToolResponse(data)` | Structured data response (objects, arrays) |\n| `formatTextResponse(text)` | Simple text response (errors, confirmations) |\n\n```typescript\n// Success with data\nreturn formatToolResponse(artifact);\n\n// Not found / error message\nreturn formatTextResponse(`Artifact \"${ref}\" not found`);\n\n// List results\nreturn formatToolResponse({ artifacts, count: artifacts.length });\n```\n\n资料来源：[src/server/toolHandlers.ts:318-328]()\n\n## TypeScript Configuration\n\nTools are built with the following TypeScript configuration:\n\n- **Target**: ES2022\n- **Module resolution**: Node16\n- **Build output**: `dist/index.js`\n- **Source entry**: `src/index.ts` 资料来源：[CLAUDE.md:88-90]()\n\nBackward compatibility is maintained by re-exporting `ManagerContext` as `KnowledgeGraphManager` alias, plus core types. 资料来源：[CLAUDE.md:27-29]()\n\n---\n\n<a id='search-capabilities'></a>\n\n## Search Capabilities\n\n### 相关页面\n\n相关主题：[Entity-Relation-Observation Model](#entity-model), [Temporal and Advanced Features](#temporal-features)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n</details>\n\n# Search Capabilities\n\n## Overview\n\nThe memory-mcp repository provides a comprehensive multi-layered search system with 13 search tools across 6 categories. These capabilities enable users to query the knowledge graph using various matching strategies, from simple text matching to advanced semantic similarity using embeddings.\n\n资料来源：[CLAUDE.md:18]()\n\n## Architecture\n\nThe search system is built on a layered architecture that provides progressive enhancement from basic keyword matching to intelligent semantic understanding.\n\n```mermaid\ngraph TD\n    A[Search Query] --> B[Search Category]\n    A --> C[Intelligent Search]\n    A --> D[Semantic Search]\n    \n    B --> B1[Basic Search]\n    B --> B2[Ranked Search TF-IDF]\n    B --> B3[Boolean Search]\n    B --> B4[Fuzzy Search]\n    B --> B5[Auto-Select]\n    \n    C --> C1[Hybrid Multi-Layer]\n    C --> C2[Query Analysis]\n    C --> C3[Reflection-Based]\n    \n    D --> D1[OpenAI Embeddings]\n    D --> D2[Local Model Embeddings]\n    \n    style A fill:#e1f5fe\n    style B fill:#fff3e0\n    style C fill:#e8f5e9\n    style D fill:#f3e5f5\n```\n\n## Search Tool Categories\n\n| Category | Tool Count | Primary Use Case |\n|----------|------------|------------------|\n| Search | 7 | Core text-based query operations |\n| Intelligent Search | 3 | Advanced query analysis and multi-layer approaches |\n| Semantic Search | 3 | Embedding-based similarity matching |\n| Saved Searches | 5 | Store and reuse frequent queries |\n\n资料来源：[CLAUDE.md:18-22]()\n\n## Basic Search Operations\n\n### Core Search Handler\n\nThe primary search functionality is implemented in `toolHandlers.ts` and supports multiple query types:\n\n```typescript\nsearch: async (ctx, args) => {\n  const query = validateWithSchema(args.query, SearchQuerySchema, 'Invalid search query');\n  const limit = args.limit !== undefined\n    ? validateWithSchema(args.limit, z.number().int().min(1).max(100), 'Invalid limit')\n    : undefined;\n  const graph = await ctx.storage.loadGraph();\n  const results = await ctx.searchManager.search(graph, query, limit);\n  return formatToolResponse({ query, results, count: results.length });\n}\n```\n\n资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n### Search Tool Definition\n\nThe MCP tool definition specifies the input schema for the search interface:\n\n```typescript\n{\n  name: 'semantic_search',\n  description: 'Search for entities using semantic similarity. Requires embedding provider to be configured via MEMORY_EMBEDDING_PROVIDER.',\n  inputSchema: {\n    type: 'object',\n    properties: {\n      query: { type: 'string', description: 'Natural language search query' },\n      limit: { type: 'number', description: 'Maximum number of results (default: 10, max: 100)' },\n      minSimilarity: {\n        type: 'number',\n        description: 'Minimum similarity score threshold (0.0-1.0, default: 0)',\n      },\n    },\n    required: ['query'],\n    additionalProperties: false,\n  },\n}\n```\n\n资料来源：[src/server/toolDefinitions.ts:1-30]()\n\n## Semantic Search\n\nSemantic search provides embedding-based similarity matching for natural language queries.\n\n### Configuration Requirements\n\nSemantic search requires an embedding provider to be configured via the `MEMORY_EMBEDDING_PROVIDER` environment variable:\n\n| Provider | Description |\n|----------|-------------|\n| `openai` | Use OpenAI embedding models |\n| `local` | Use locally deployed embedding models |\n\n### Handler Implementation\n\nThe semantic search handler validates configuration and executes embedding-based queries:\n\n```typescript\nsemantic_search: async (ctx, args) => {\n  const semanticSearch = ctx.semanticSearch;\n  if (!semanticSearch) {\n    return formatTextResponse(\n      'Semantic search is not available. Set MEMORY_EMBEDDING_PROVIDER environment variable to \"openai\" or \"local\".'\n    );\n  }\n\n  const query = validateWithSchema(args.query, SearchQuerySchema, 'Invalid search query');\n  const limit = args.limit !== undefined\n    ? validateWithSchema(args.limit, z.number().int().min(1).max(100), 'Invalid limit (1-100)')\n    : undefined;\n  const minSimilarity = args.minSimilarity !== undefined\n    ? validateWithSchema(args.minSimilarity, z.number().min(0).max(1), 'Invalid minSimilarity (0-1)')\n    : undefined;\n\n  const graph = await ctx.storage.loadGraph();\n  const results = await semanticSearch.search(graph, query, limit, minSimilarity);\n\n  return formatToolResponse({\n    query,\n    results: results.map(r => ({\n      entity: r.entity,\n      similarity: r.similarity,\n    })),\n    count: results.length,\n  });\n}\n```\n\n资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n### Similar Entity Discovery\n\nThe `find_similar_entities` tool extends semantic search to discover entities similar to a given reference entity:\n\n```typescript\nfind_similar_entities: async (ctx, args) => {\n  const semanticSearch = ctx.semanticSearch;\n  if (!semanticSearch) {\n    return formatTextResponse(\n      'Semantic search is not available. Set MEMORY_EMBEDDING_PROVIDER environment variable...'\n    );\n  }\n  // Implementation continues...\n}\n```\n\n## Search Manager Architecture\n\nThe search functionality is provided through the `ManagerContext` which exposes the `searchManager` and `semanticSearch` accessors:\n\n```typescript\n// Available accessors in ManagerContext\nctx.entityManager\nctx.relationManager\nctx.observationManager\nctx.searchManager        // Basic search operations\nctx.tagManager\nctx.hierarchyManager\nctx.analyticsManager\nctx.compressionManager\nctx.archiveManager\nctx.ioManager\nctx.graphTraversal\nctx.semanticSearch       // Embedding-based search\nctx.rankedSearch\nctx.storage              // Direct GraphStorage access\n```\n\n资料来源：[CLAUDE.md:10-13]()\n\n## Search Parameters\n\n### Input Validation Schema\n\nAll search operations use Zod schemas for input validation to ensure type safety:\n\n| Parameter | Type | Constraints | Default |\n|-----------|------|-------------|---------|\n| query | string | min(1) | required |\n| limit | number | int, min(1), max(100) | undefined |\n| minSimilarity | number | min(0), max(1) | undefined |\n\n### Validation Pattern\n\nThe tool handlers use a consistent validation pattern:\n\n```typescript\nconst validateWithSchema = (value, schema, errorMessage) => {\n  const result = schema.safeParse(value);\n  if (!result.success) {\n    throw new Error(`${errorMessage}: ${result.error.message}`);\n  }\n  return result.data;\n};\n```\n\n## Search Result Format\n\nResults are formatted consistently across all search operations:\n\n```typescript\nreturn formatToolResponse({\n  query,\n  results: results.map(r => ({\n    entity: r.entity,\n    similarity: r.similarity,  // Only for semantic search\n  })),\n  count: results.length,\n});\n```\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Required | Values | Purpose |\n|----------|----------|--------|---------|\n| `MEMORY_EMBEDDING_PROVIDER` | For semantic search | `openai`, `local` | Select embedding backend |\n| `MEMORY_STORAGE_TYPE` | No | `jsonl`, `sqlite` | Storage format for graph data |\n\n### Storage Integration\n\nSearch operations load the graph from storage before executing queries:\n\n```typescript\nconst graph = await ctx.storage.loadGraph();\n```\n\nThe storage layer supports both JSONL and SQLite backends for persistent graph storage.\n\n资料来源：[CLAUDE.md:38-42]()\n\n## Workflow Diagram\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant MCPServer\n    participant SearchManager\n    participant Storage\n    participant SemanticSearch\n\n    User->>MCPServer: search query\n    MCPServer->>MCPServer: Validate input schema\n    MCPServer->>Storage: loadGraph()\n    Storage-->>MCPServer: graph data\n    alt Basic Search\n        MCPServer->>SearchManager: search(graph, query, limit)\n        SearchManager-->>MCPServer: text match results\n    else Semantic Search\n        MCPServer->>SemanticSearch: search(graph, query, limit, minSimilarity)\n        SemanticSearch-->>MCPServer: similarity results\n    end\n    MCPServer-->>User: formatted response\n```\n\n## Related Documentation\n\n- [Query Language Guide](docs/guides/QUERY_LANGUAGE.md) - Syntax and operators for advanced queries\n- [Compression Guide](docs/guides/COMPRESSION.md) - Search optimization through deduplication\n\n---\n\n<a id='temporal-features'></a>\n\n## Temporal and Advanced Features\n\n### 相关页面\n\n相关主题：[Entity-Relation-Observation Model](#entity-model), [Tool Reference](#tool-reference)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [tools/create-dependency-graph/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md)\n</details>\n\n# Temporal and Advanced Features\n\nThis page documents the temporal, governance, and advanced cognitive features available in the memory-mcp system. These features extend beyond basic entity and relation management to provide sophisticated memory lifecycle management, access control, and intelligent decay mechanisms.\n\n## Overview\n\nThe memory-mcp system implements advanced features introduced in two major phases:\n\n- **Phase 15 (v12.2.0)**: Added 23 tools surfacing memoryjs v1.14+ features including bitemporal validity, OCC (Optimistic Concurrency Control), RBAC (Role-Based Access Control), procedural memory, active retrieval, causal reasoning, and world model capabilities.\n- **Phase 16 (v12.3.0)**: Added 53 tools surfacing memoryjs v2.1.0 features including decision rationale, ADR markdown dual-write, structured project context, heuristic guidelines, tool affordance observation pipeline, observation deduplication, and spell correction.\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Architecture\n\nThe advanced features are built upon the layered architecture where memory-mcp acts as the MCP server layer while the core graph logic resides in the `@danielsimonjr/memoryjs` package.\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (MCP Server Layer)\"\n        A[toolHandlers.ts] --> B[ManagerContext Accessors]\n        C[toolDefinitions.ts] --> B\n    end\n    \n    subgraph \"@danielsimonjr/memoryjs (Core Library)\"\n        B --> D[EntityManager]\n        B --> E[RelationManager]\n        B --> F[ObservationManager]\n        B --> G[SearchManager]\n        B --> H[CompressionManager]\n        B --> I[ArchiveManager]\n        B --> J[GraphTraversal]\n        B --> K[SemanticSearch]\n    end\n    \n    subgraph \"Temporal Features\"\n        L[Bitemporal Validity]\n        M[OCC - Optimistic Concurrency Control]\n        N[Decay Engine]\n    end\n    \n    subgraph \"Advanced Features\"\n        O[RBAC Governance]\n        P[Audit Logging]\n        Q[Artifact Management]\n        R[Procedural Memory]\n    end\n    \n    D --> L\n    E --> M\n    F --> N\n    G --> O\n    H --> P\n    I --> Q\n    J --> R\n```\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Governance and Access Control\n\n### Role-Based Access Control (RBAC)\n\nThe system implements RBAC through governance policy settings that control what operations agents can perform on memory entities.\n\n#### Governance Policy Tool\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `allowCreate` | boolean | Permission to create new entities |\n| `allowUpdate` | boolean | Permission to update existing entities |\n| `allowDelete` | boolean | Permission to delete entities |\n\n**Handler Implementation:**\n\n```typescript\ngovernance_policy_set: async (ctx, args) => {\n  const allowCreate = validateWithSchema(args.allowCreate, z.boolean(), 'Invalid allowCreate');\n  const allowUpdate = validateWithSchema(args.allowUpdate, z.boolean(), 'Invalid allowUpdate');\n  const allowDelete = validateWithSchema(args.allowDelete, z.boolean(), 'Invalid allowDelete');\n  \n  const { setGovernancePolicy } = await import('@danielsimonjr/memoryjs');\n  await setGovernancePolicy(ctx.storage, {\n    canCreate: allowCreate ? undefined : () => false,\n    canUpdate: allowUpdate ? undefined : () => false,\n    canDelete: allowDelete ? undefined : () => false,\n  });\n  return formatTextResponse(`Governance policy set: canCreate=${allowCreate}, canUpdate=${allowUpdate}, canDelete=${allowDelete}`);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:1-50](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n### Audit Logging\n\nThe audit system tracks all operations performed on the knowledge graph for compliance and debugging purposes.\n\n#### Audit Query Parameters\n\n| Parameter | Type | Description | Default |\n|-----------|------|-------------|---------|\n| `operation` | enum | create, update, delete, merge, archive | — |\n| `agentId` | string | Filter by agent identifier | — |\n| `entityName` | string | Filter by entity name | — |\n| `since` | string | Start time (maps to fromTime) | — |\n| `until` | string | End time (maps to toTime) | — |\n| `limit` | number | Maximum entries to return | 50 |\n\n**Handler Implementation:**\n\n```typescript\naudit_query: async (ctx, args) => {\n  const filter: AuditFilter = {};\n  if (args.operation !== undefined) {\n    filter.operation = validateWithSchema(args.operation, z.enum(['create', 'update', 'delete', 'merge', 'archive']), 'Invalid operation');\n  }\n  if (args.agentId !== undefined) {\n    filter.agentId = validateWithSchema(args.agentId, z.string(), 'Invalid agentId');\n  }\n  if (args.entityName !== undefined) {\n    filter.entityName = validateWithSchema(args.entityName, z.string(), 'Invalid entityName');\n  }\n  if (args.since !== undefined) {\n    filter.fromTime = validateWithSchema(args.since, z.string(), 'Invalid since');\n  }\n  if (args.until !== undefined) {\n    filter.toTime = validateWithSchema(args.until, z.string(), 'Invalid until');\n  }\n  const limit = args.limit !== undefined\n    ? validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit')\n    : 50;\n  const al = getAuditLog(ctx);\n  let entries = await al.query(filter);\n  entries = entries.slice(0, limit);\n  // ...\n}\n```\n\n资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n## Temporal Validity and Bitemporal Data\n\n### Bitemporal Validity\n\nBitemporal validity tracks two dimensions of time:\n\n1. **Valid Time**: When facts were true in the real world\n2. **Transaction Time**: When facts were recorded in the system\n\nThis enables accurate historical queries and audit trails that reflect the state of knowledge at any point in time.\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n### Optimistic Concurrency Control (OCC)\n\nOCC prevents conflicting updates by checking whether the data has changed since it was last read, ensuring data consistency without requiring locks.\n\n## Memory Decay and Salience\n\nThe decay engine implements time-based importance scoring that automatically reduces the importance of memories over time.\n\n### Decay Cycle Tool\n\nThe `run_decay_cycle` tool executes a single pass of time-based importance decay across all agent memories.\n\n```typescript\n{\n  name: 'run_decay_cycle',\n  description: 'Run a single pass of time-based importance decay across all agent memories. Returns count of decayed and forgotten memories.',\n  inputSchema: {\n    type: 'object',\n    properties: {},\n    additionalProperties: false,\n  },\n}\n```\n\n资料来源：[src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n\n### Decay-Based Memory Queries\n\n| Tool | Purpose | Key Parameters |\n|------|---------|----------------|\n| `get_decayed_memories` | List memories below decay threshold | `threshold` (default: 0.1) |\n| `forget_weak_memories` | Bulk-delete memories below threshold | `threshold`, `maxCount`, `dryRun` |\n\n**Difference from other deletion mechanisms:**\n\n- `forget_memory`: Uses content matching\n- `archive_entities`: Uses criteria-based move to archive\n- `forget_weak_memories`: Uses decay-based importance scoring\n\n```typescript\n{\n  name: 'get_decayed_memories',\n  description: 'List memories whose importance has fallen below a threshold due to time-based decay. Unlike get_stale_entities (which uses freshness timestamps), this uses decay engine importance calculations.',\n  inputSchema: {\n    type: 'object',\n    properties: {\n      threshold: { type: 'number', description: 'Importance threshold (default: 0.1)' },\n    },\n    additionalProperties: false,\n  },\n}\n```\n\n资料来源：[src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n\n## Artifact Management\n\nArtifacts capture structured outputs from tool executions for later retrieval and analysis.\n\n### Artifact Types\n\n| Type | Description |\n|------|-------------|\n| `tool_output` | Results from tool invocations |\n| `code_snippet` | Generated or analyzed code |\n| `api_response` | External API responses |\n| `search_result` | Search query results |\n| `file_content` | File read contents |\n| `user_input` | User-provided prompts |\n\n### Artifact Tools\n\n```typescript\ncreate_artifact: async (ctx, args) => {\n  const content = validateWithSchema(args.content, z.string().min(1), 'Invalid content');\n  const toolName = validateWithSchema(args.toolName, z.string().min(1), 'Invalid toolName');\n  const artifactType = validateWithSchema(\n    args.artifactType,\n    z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n    'Invalid artifactType'\n  );\n  const description = args.description !== undefined\n    ? validateWithSchema(args.description, z.string(), 'Invalid description')\n    : undefined;\n  const sessionId = args.sessionId !== undefined\n    ? validateWithSchema(args.sessionId, z.string(), 'Invalid sessionId')\n    : undefined;\n  const artifact = await getArtifactManager(ctx).createArtifact({\n    content, toolName, artifactType, description, sessionId,\n  });\n  return formatToolResponse(artifact);\n},\n\nget_artifact: async (ctx, args) => {\n  const ref = validateWithSchema(args.ref, z.string().min(1), 'Invalid ref');\n  const artifact = await getArtifactManager(ctx).getArtifact(ref);\n  if (!artifact) {\n    return formatTextResponse(`Artifact \"${ref}\" not found`);\n  }\n  return formatToolResponse(artifact);\n},\n\nlist_artifacts: async (ctx, args) => {\n  const filter: ArtifactFilter = {};\n  if (args.toolName !== undefined) {\n    filter.toolName = validateWithSchema(args.toolName, z.string(), 'Invalid toolName');\n  }\n  // ...\n}\n```\n\n资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n## Phase 16 Advanced Features (v12.3.0)\n\n### Decision Rationale and ADR Dual-Write\n\nThe system supports dual-writing decision rationale in both structured format and Architecture Decision Records (ADR) markdown format.\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n### Tool Affordance and Observation Pipeline\n\n| Component | Description |\n|-----------|-------------|\n| `ToolCallObserver` | Pipeline for observing and analyzing tool calls |\n| Tool Affordance | Metadata describing available tool capabilities |\n| Observation Dedup | Prevents duplicate observations in the system |\n| Spell Correction | 3 tools for automatic typo correction in queries |\n\n### Structured Project Context\n\n12 tools providing structured access to project metadata and context for better decision-making.\n\n### Heuristic Guidelines\n\n10 tools implementing rule-based guidance for memory management and retrieval decisions.\n\n## Tool Categories Summary\n\nThe system organizes its 213 tools across 58 categories, with the advanced features distributed across:\n\n| Category | Feature Type |\n|----------|--------------|\n| Governance | RBAC, audit logging |\n| Compression | Duplicate detection, merge, auto-compress |\n| Analytics | Graph stats, integrity validation |\n| Decay & Salience | Time-based importance decay |\n| Import/Export | Multi-format data handling |\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Storage Considerations\n\nAdvanced features persist data in the same storage backends as core entities:\n\n| Storage Type | File Location | Configuration |\n|--------------|---------------|---------------|\n| JSONL | `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl` | Default |\n| SQLite | `memory.db` | Set `MEMORY_STORAGE_TYPE=sqlite` |\n\nData files reside in the project root (not `dist/`), and are gitignored to prevent accidental commits.\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Manager Context Accessors\n\nAdvanced features access the core library through the `ManagerContext`:\n\n| Accessor | Purpose |\n|----------|---------|\n| `ctx.analyticsManager` | Graph statistics and validation |\n| `ctx.compressionManager` | Duplicate detection and merging |\n| `ctx.archiveManager` | Long-term memory archival |\n| `ctx.ioManager` | Import/export operations |\n| `ctx.graphTraversal` | Advanced graph navigation |\n| `ctx.semanticSearch` | Embedding-based search |\n| `ctx.rankedSearch` | TF-IDF based search |\n| `ctx.storage` | Direct GraphStorage access |\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Testing Coverage\n\nAdvanced features are covered by the test suite with the following coverage metrics:\n\n| Metric | Coverage |\n|--------|----------|\n| Statements | 80.7% |\n| Lines | 81.4% |\n| Functions | 79.5% |\n| Branches | 68.3% |\n\nTest files are organized in `tests/e2e/tools/` with one file per tool group including governance, freshness, and entropy categories.\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n---\n\n<a id='collaboration-security'></a>\n\n## Collaboration and Security\n\n### 相关页面\n\n相关主题：[Tool Reference](#tool-reference), [Temporal and Advanced Features](#temporal-features)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)\n- [src/server/toolDefs.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefs.ts)\n- [docs/architecture/API.md](https://github.com/danielsimonjr/memory-mcp/blob/main/docs/architecture/API.md)\n- [docs/architecture/TEST_COVERAGE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/docs/architecture/TEST_COVERAGE.md)\n</details>\n\n# Collaboration and Security\n\nThe memory-mcp system provides a comprehensive suite of collaboration and security features designed to enable multi-agent workflows while maintaining data integrity, access control, and auditability. These features are built on the underlying memoryjs library (v1.14+) and exposed through 213 MCP tools across 58 categories.\n\n## Overview\n\nCollaboration and Security in memory-mcp encompasses four primary domains:\n\n| Domain | Purpose | Key Components |\n|--------|---------|----------------|\n| **Governance** | Access control policies | RBAC, CRUD permissions |\n| **Audit** | Activity tracking | Operation logs, agent attribution |\n| **Artifacts** | Collaboration artifacts | Tool outputs, code snippets, session data |\n| **Data Integrity** | Export security | PII redaction, format validation |\n\n资料来源：[CLAUDE.md:14-16]()\n\n## Architecture\n\n```graph TD\n    subgraph \"MCP Client Layer\"\n        A[AI Agent 1] \n        B[AI Agent 2]\n        C[Human User]\n    end\n    \n    subgraph \"memory-mcp Server\"\n        D[MCP Protocol Handler]\n        E[Tool Router]\n        F[Governance Layer]\n    end\n    \n    subgraph \"memoryjs Core\"\n        G[EntityManager]\n        H[RelationManager]\n        I[AuditManager]\n        J[ArtifactManager]\n    end\n    \n    subgraph \"Storage\"\n        K[(JSONL/SQLite)]\n    end\n    \n    A --> D\n    B --> D\n    C --> D\n    D --> E\n    E --> F\n    F --> G\n    F --> H\n    E --> I\n    E --> J\n    G --> K\n    H --> K\n    I --> K\n    J --> K\n```\n\n## Governance and Access Control\n\n### Role-Based Access Control (RBAC)\n\nmemory-mcp implements RBAC through the memoryjs library, providing granular control over entity and relation operations. 资料来源：[CLAUDE.md:16]()\n\n### Governance Policy Management\n\nThe `governance_set_policy` tool enables administrators to configure CRUD permissions for the knowledge graph:\n\n```typescript\ngovernance_set_policy: async (ctx, args) => {\n    const { \n        allowCreate = true, \n        allowUpdate = true, \n        allowDelete = true \n    } = args;\n    \n    const governance = getGovernance(ctx);\n    await governance.setPolicy({\n        canCreate: allowCreate ? undefined : () => false,\n        canUpdate: allowUpdate ? undefined : () => false,\n        canDelete: allowDelete ? undefined : () => false,\n    });\n    return formatTextResponse(\n        `Governance policy set: canCreate=${allowCreate}, canUpdate=${allowUpdate}, canDelete=${allowDelete}`\n    );\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:1-20]()\n\n### Governance Tool Definition\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `allowCreate` | boolean | No | Enable entity creation (default: true) |\n| `allowUpdate` | boolean | No | Enable entity updates (default: true) |\n| `allowDelete` | boolean | No | Enable entity deletion (default: true) |\n\nWhen a permission flag is `false`, the governance layer installs a deny function that blocks the operation.\n\n## Audit System\n\n### Audit Log Architecture\n\nThe audit system tracks all graph mutations with full attribution:\n\n```graph TD\n    A[Graph Operation] --> B{AuditManager}\n    B --> C[Create Entry]\n    B --> D[Update Entry]\n    B --> E[Delete Entry]\n    B --> F[Merge Entry]\n    B --> G[Archive Entry]\n    \n    C --> H[AuditStore]\n    D --> H\n    E --> H\n    F --> H\n    G --> H\n```\n\n### Audit Query Handler\n\nThe `audit_query` tool provides filtered access to audit entries:\n\n```typescript\naudit_query: async (ctx, args) => {\n    const filter: AuditFilter = {};\n    if (args.operation !== undefined) {\n        filter.operation = validateWithSchema(\n            args.operation,\n            z.enum(['create', 'update', 'delete', 'merge', 'archive']),\n            'Invalid operation'\n        );\n    }\n    if (args.agentId !== undefined) {\n        filter.agentId = validateWithSchema(args.agentId, z.string(), 'Invalid agentId');\n    }\n    if (args.entityName !== undefined) {\n        filter.entityName = validateWithSchema(args.entityName, z.string(), 'Invalid entityName');\n    }\n    if (args.since !== undefined) {\n        filter.fromTime = validateWithSchema(args.since, z.string(), 'Invalid since');\n    }\n    if (args.until !== undefined) {\n        filter.toTime = validateWithSchema(args.until, z.string(), 'Invalid until');\n    }\n    const limit = args.limit !== undefined\n        ? validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit')\n        : 50;\n    const al = getAuditLog(ctx);\n    let entries = await al.query(filter);\n    entries = entries.slice(0, limit);\n    // ...\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:22-57]()\n\n### Audit Query Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `operation` | enum | No | Filter by: `create`, `update`, `delete`, `merge`, `archive` |\n| `agentId` | string | No | Filter by responsible agent |\n| `entityName` | string | No | Filter by affected entity |\n| `since` | string | No | Start time (ISO 8601) |\n| `until` | string | No | End time (ISO 8601) |\n| `limit` | number | No | Max results (1-1000, default: 50) |\n\n### Supported Audit Operations\n\nThe audit system records the complete lifecycle of graph entities:\n\n| Operation | Description |\n|-----------|-------------|\n| `create` | New entity or relation creation |\n| `update` | Modification of existing entities |\n| `delete` | Permanent removal from graph |\n| `merge` | Entity consolidation operations |\n| `archive` | Soft deletion with retention |\n\n## Artifact Management\n\n### Purpose\n\nArtifacts enable collaboration by persisting tool outputs, code snippets, API responses, and user inputs across sessions. This supports multi-agent workflows where one agent's output becomes another agent's context.\n\n### Artifact Types\n\n| Type | Use Case |\n|------|----------|\n| `tool_output` | Raw outputs from MCP tool invocations |\n| `code_snippet` | Generated or referenced code |\n| `api_response` | External API responses |\n| `search_result` | Search query results |\n| `file_content` | File contents for reference |\n| `user_input` | User-provided content |\n\n资料来源：[src/server/toolHandlers.ts:59-75]()\n\n### Artifact CRUD Operations\n\n#### Create Artifact\n\n```typescript\ncreate_artifact: async (ctx, args) => {\n    const content = validateWithSchema(args.content, z.string().min(1), 'Invalid content');\n    const toolName = validateWithSchema(args.toolName, z.string().min(1), 'Invalid toolName');\n    const artifactType = validateWithSchema(\n        args.artifactType,\n        z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n        'Invalid artifactType'\n    );\n    const description = args.description !== undefined\n        ? validateWithSchema(args.description, z.string(), 'Invalid description')\n        : undefined;\n    const sessionId = args.sessionId !== undefined\n        ? validateWithSchema(args.sessionId, z.string(), 'Invalid sessionId')\n        : undefined;\n    const artifact = await getArtifactManager(ctx).createArtifact({\n        content, toolName, artifactType, description, sessionId,\n    });\n    return formatToolResponse(artifact);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:59-80]()\n\n#### List Artifacts with Filtering\n\n```typescript\nlist_artifacts: async (ctx, args) => {\n    const filter: ArtifactFilter = {};\n    if (args.toolName !== undefined) {\n        filter.toolName = validateWithSchema(args.toolName, z.string(), 'Invalid toolName');\n    }\n    if (args.artifactType !== undefined) {\n        filter.artifactType = validateWithSchema(\n            args.artifactType,\n            z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n            'Invalid artifactType'\n        );\n    }\n    if (args.since !== undefined) {\n        const sinceStr = validateWithSchema(args.since, z.string().regex(/^\\d{4}-\\d{2}-\\d{2}(T[\\d:.Z+-]+)?$/, 'since must be an ISO 8601 date string'), 'Invalid since');\n        const sinceDate = new Date(sinceStr);\n        if (isNaN(sinceDate.getTime())) {\n            throw new Error(`Invalid since date: \"${sinceStr}\" is not a valid date`);\n        }\n        filter.since = sinceDate;\n    }\n    const artifacts = await getArtifactManager(ctx).listArtifacts(\n        Object.keys(filter).length > 0 ? filter : undefined\n    );\n    return formatToolResponse({ artifacts, count: artifacts.length });\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:95-125]()\n\n### Artifact Filter Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `toolName` | string | No | Filter by originating tool |\n| `artifactType` | enum | No | Filter by artifact type |\n| `since` | string | No | ISO 8601 date for time-based filtering |\n\n## Data Integrity and Export Security\n\n### PII Redaction\n\nWhen exporting graph data, memory-mcp supports automatic PII redaction to prevent sensitive information leakage:\n\n```graph TD\n    A[Export Request] --> B{Export Format}\n    B -->|XML| C[memoryjs η.5.4]\n    B -->|JSON-LD| C\n    C --> D{redactPii: true}\n    D -->|Yes| E[Redaction Engine]\n    D -->|No| F[Raw Export]\n    E --> F\n    F --> G[Exported File]\n```\n\n资料来源：[CLAUDE.md:34-35]()\n\n### Export Configuration\n\n| Option | Type | Description | Version |\n|--------|------|-------------|---------|\n| `redactPii` | boolean | Enable PII redaction on export | memoryjs η.6.3+ |\n| Export formats | enum | `xml`, `json-ld` | memoryjs η.5.4+ |\n\n### Compression for Context\n\nThe standalone `compress-for-context` tool provides CTON (Compact Textual Object Notation) compression for managing context windows during multi-agent collaboration:\n\n```bash\n# Single file compression\nnode compress-for-context.js data.json\n\n# Aggressive compression for maximum context savings\nnode compress-for-context.js README.md -l aggressive\n\n# Batch processing\nnode compress-for-context.js -b -p \"*.json\" ./src\n```\n\n资料来源：[tools/compress-for-context/compress-for-context.ts:1-25]()\n\n## Security Architecture\n\n```graph TD\n    subgraph \"Security Layers\"\n        A[Authentication]\n        B[Authorization]\n        C[Audit Logging]\n        D[Data Encryption]\n    end\n    \n    subgraph \"Access Control Points\"\n        E[governance_set_policy]\n        F[RBAC via memoryjs]\n        G[Operation Validation]\n    end\n    \n    subgraph \"Audit Trail\"\n        H[Operation Tracking]\n        I[Agent Attribution]\n        J[Time-based Queries]\n    end\n    \n    A --> B\n    B --> C\n    C --> D\n    E --> F\n    F --> G\n    G --> H\n    H --> I\n    I --> J\n```\n\n## Environment Variables for Security\n\n| Variable | Description | Default | Security Impact |\n|----------|-------------|---------|-----------------|\n| `MEMORY_FILE_PATH` | Storage file location | `memory.jsonl` | Data isolation |\n| `MEMORY_STORAGE_TYPE` | Storage backend | `jsonl` | Persistence security |\n| `MEMORY_EMBEDDING_PROVIDER` | Embedding service | `none` | External data exposure |\n| `MEMORY_OPENAI_API_KEY` | API authentication | — | External service auth |\n\n资料来源：[CLAUDE.md:58-64]()\n\n## Testing Coverage\n\nThe collaboration and security features are validated through the test suite:\n\n| Test Category | Location | Coverage Focus |\n|---------------|----------|----------------|\n| Integration | `tests/integration/` | MCP server lifecycle, security hooks |\n| E2E | `tests/e2e/tools/` | Per-tool handler validation |\n| Governance | `tests/e2e/tools/governance.test.ts` | Policy enforcement |\n| Audit | `tests/e2e/tools/audit.test.ts` | Log integrity |\n| Artifacts | `tests/e2e/tools/artifact.test.ts` | CRUD operations |\n\n资料来源：[CLAUDE.md:46-50](), [docs/architecture/TEST_COVERAGE.md]()\n\n## Best Practices for Multi-Agent Collaboration\n\n1. **Configure Governance Early**: Set appropriate `allowCreate`, `allowUpdate`, and `allowDelete` policies before enabling multi-agent access.\n\n2. **Enable Audit Logging**: Use `audit_query` with appropriate filters to monitor agent activity and detect anomalies.\n\n3. **Use Artifacts for Context**: Store intermediate results as artifacts with descriptive `sessionId` values to enable context sharing.\n\n4. **Enable PII Redaction**: Set `redactPii: true` when exporting data containing sensitive information.\n\n5. **Rotate Storage Files**: Implement periodic rotation of `memory.jsonl` or `memory.db` with archival to maintain audit history.\n\n## Pull Request Security Requirements\n\nWhen contributing security-related changes:\n\n1. **Title**: Clear, descriptive summary of the security impact\n2. **Description**: Document what changed, why, and potential security implications\n3. **Tests**: Include test results demonstrating security controls\n4. **Documentation**: Update relevant security documentation\n5. **Backward Compatibility**: Confirm no breaking security changes\n\n资料来源：[CONTRIBUTING.md:37-44]()\n\n---\n\n<a id='development-guide'></a>\n\n## Development Guide\n\n### 相关页面\n\n相关主题：[Getting Started](#getting-started)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n- [tsconfig.json](https://github.com/danielsimonjr/memory-mcp/blob/main/tsconfig.json)\n- [vitest.config.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/vitest.config.ts)\n- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n</details>\n\n# Development Guide\n\nThis guide provides comprehensive information for developers contributing to the memory-mcp project. It covers project setup, architecture, coding standards, testing practices, and the development workflow.\n\n## Project Overview\n\nmemory-mcp is a Model Context Protocol (MCP) server that provides memory and knowledge graph capabilities. The server exposes 213 tools across 58 categories for managing entities, relations, observations, searches, tags, hierarchies, and analytics.\n\n**npm Package:** `@danielsimonjr/memory-mcp`\n**Core Dependency:** `@danielsimonjr/memoryjs` (currently `^2.1.0`)\n\n资料来源：[CLAUDE.md:1]()\n\n## Architecture Overview\n\n### Layered Architecture\n\nThe project follows a layered architecture where memory-mcp serves as the MCP interface layer on top of the memoryjs core library.\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (this repo)\"\n        A[\"src/index.ts\"] --> B[\"src/server/MCPServer.ts\"]\n        B --> C[\"src/server/toolDefs.ts\"]\n        B --> D[\"src/server/toolHandlers.ts\"]\n        C --> E[\"Tool Definitions\"]\n        D --> F[\"Tool Handlers\"]\n    end\n    \n    subgraph \"@danielsimonjr/memoryjs (npm dependency)\"\n        G[\"ManagerContext\"]\n        G --> H[\"EntityManager\"]\n        G --> I[\"RelationManager\"]\n        G --> J[\"ObservationManager\"]\n        G --> K[\"SearchManager\"]\n        G --> L[\"TagManager\"]\n        G --> M[\"HierarchyManager\"]\n        G --> N[\"AnalyticsManager\"]\n        G --> O[\"GraphStorage/SQLiteStorage\"]\n    end\n    \n    F -->|imports| G\n```\n\n资料来源：[CLAUDE.md:15-25]()\n\n### Key Source Files\n\n| File | Purpose |\n|------|---------|\n| `src/index.ts` | Entry point, re-exports `ManagerContext` as `KnowledgeGraphManager` |\n| `src/server/MCPServer.ts` | MCP server implementation |\n| `src/server/toolDefs.ts` | JSON schema definitions for all 213 tools |\n| `src/server/toolHandlers.ts` | Implementation handlers for each tool |\n\n资料来源：[CLAUDE.md:28-31]()\n\n## Project Setup\n\n### Prerequisites\n\n- Node.js (compatible with ES2022)\n- npm\n\n### Installation\n\n```bash\ncd c:/mcp-servers/memory-mcp\nnpm install\n```\n\nThe `prepare` script automatically runs `npm run build` on install, so the `dist/` directory is rebuilt automatically.\n\n资料来源：[CLAUDE.md:54]()\n\n### TypeScript Configuration\n\nThe project uses ES2022 target with Node16 module resolution:\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"ES2022\",\n    \"module\": \"Node16\",\n    \"moduleResolution\": \"Node16\",\n    \"outDir\": \"./dist\",\n    \"rootDir\": \"./src\"\n  },\n  \"include\": [\"src/**/*\"]\n}\n```\n\n资料来源：[tsconfig.json](https://github.com/danielsimonjr/memory-mcp/blob/main/tsconfig.json)\n\n### Build Scripts\n\n| Script | Purpose |\n|--------|---------|\n| `npm run build` | Compile TypeScript to `dist/` |\n| `npm run typecheck` | Run TypeScript type checking |\n| `npm run test` | Run all tests |\n| `npm run test:unit` | Run unit tests only |\n| `npm run test:e2e` | Run end-to-end tests |\n| `npm run docs:deps` | Generate dependency graph documentation |\n\n资料来源：[package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n\n## Environment Configuration\n\nThe MCP server uses environment variables for configuration:\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `MEMORY_FILE_PATH` | Path to storage file | `memory.jsonl` (cwd) |\n| `MEMORY_STORAGE_TYPE` | `jsonl` or `sqlite` | `jsonl` |\n| `MEMORY_EMBEDDING_PROVIDER` | `openai`, `local`, or `none` | `none` |\n| `MEMORY_OPENAI_API_KEY` | Required if provider is `openai` | — |\n| `MEMORY_EMBEDDING_MODEL` | Embedding model name | `text-embedding-3-small` / `Xenova/all-MiniLM-L6-v2` |\n| `MEMORY_AUTO_INDEX_EMBEDDINGS` | Auto-index on entity creation | `false` |\n\n资料来源：[CLAUDE.md:60-67]()\n\n### Storage\n\nData files live in the **project root** (not `dist/`):\n- **JSONL**: `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl`\n- **SQLite**: `memory.db` (set `MEMORY_STORAGE_TYPE=sqlite`)\n\n资料来源：[CLAUDE.md:37-42]()\n\n## Code Style Guidelines\n\n### TypeScript Best Practices\n\n- Follow TypeScript best practices\n- Use meaningful variable names\n- Add JSDoc comments for public methods\n- Keep functions focused and small\n- Maintain consistent indentation (2 spaces)\n\n资料来源：[CONTRIBUTING.md:21-25]()\n\n### ManagerContext Access Pattern\n\nWhen implementing tool handlers, use the ManagerContext accessors to access various managers:\n\n| Accessor | Purpose |\n|----------|---------|\n| `ctx.entityManager` | Core CRUD for graph nodes |\n| `ctx.relationManager` | Directed edges between entities |\n| `ctx.observationManager` | Facts attached to entities |\n| `ctx.searchManager` | Search operations |\n| `ctx.tagManager` | Tag management |\n| `ctx.hierarchyManager` | Parent-child trees |\n| `ctx.analyticsManager` | Graph stats and validation |\n| `ctx.compressionManager` | Duplicate detection, merge |\n| `ctx.archiveManager` | Archive operations |\n| `ctx.ioManager` | Import/Export operations |\n| `ctx.graphTraversal` | BFS/DFS path finding |\n| `ctx.semanticSearch` | Embedding similarity search |\n| `ctx.rankedSearch` | TF-IDF ranked search |\n| `ctx.storage` | Direct GraphStorage access |\n\n资料来源：[CLAUDE.md:53-55]()\n\n## Testing Guidelines\n\n### Test Structure\n\nThe project has 26 test files with 665 tests, achieving approximately 81% statement coverage.\n\n| Tier | Location | Purpose |\n|------|----------|---------|\n| Unit | `tests/unit/` | Isolated module tests (e.g., response compressor) |\n| Integration | `tests/integration/` | MCP server lifecycle tests |\n| E2E | `tests/e2e/tools/` | Per-category tool tests |\n| Root | `tests/` | Core graph operations and storage path handling |\n\n资料来源：[CLAUDE.md:71-80]()\n\n### Test Coverage\n\nCoverage verification is done via `coverage/coverage-summary.json`:\n\n| Metric | Coverage |\n|--------|----------|\n| Statements | 80.7% |\n| Lines | 81.4% |\n| Functions | 79.5% |\n| Branches | 68.3% |\n\n资料来源：[CLAUDE.md:71-72]()\n\n### Vitest Configuration\n\nTests use Vitest with custom reporting. Configuration file: `vitest.config.ts`. Coverage targets `src/**/*.ts` (excludes index barrel files).\n\n资料来源：[CLAUDE.md:81-82]()\n\n### Testing Best Practices\n\n- Test new features thoroughly\n- Include edge cases\n- Test backward compatibility\n- Verify export formats are valid\n- Test with empty graphs and large graphs\n\n资料来源：[CONTRIBUTING.md:14-18]()\n\n### Testing Notes\n\n- **Storage files**: JSONL and SQLite files created during tests are in the project root but excluded in `.gitignore` — they won't appear in `git status`.\n- **Error handling in dispatch**: `handleToolCall` catches exceptions from handlers and returns them as MCP-formatted error responses. Check MCP response `isError` field when debugging.\n\n资料来源：[CLAUDE.md:84-87]()\n\n## Adding a New Tool\n\n### Step-by-Step Process\n\n```mermaid\ngraph LR\n    A[\"1. Add schema to<br/>toolDefinitions.ts\"] --> B[\"2. Add handler to<br/>toolHandlers.ts\"]\n    B --> C[\"3. Add e2e test in<br/>tests/e2e/tools/\"]\n    C --> D[\"4. Update documentation\"]\n```\n\n### Tool Handler Pattern\n\nHandlers follow this pattern:\n\n1. **Validate arguments** with schema validation\n2. **Call manager method** via appropriate accessor\n3. **Return formatted response**\n\n```typescript\nconst TOOL_HANDLERS = {\n  tool_name: async (ctx, args) => {\n    // 1. Validate arguments\n    const param = validateWithSchema(args.param, z.string().min(1), 'Invalid param');\n    \n    // 2. Call manager method\n    const result = await getManager(ctx).method(param);\n    \n    // 3. Return formatted response\n    return formatToolResponse(result);\n  },\n};\n```\n\nIf the response can be large, wrap with `withCompression()`.\n\n资料来源：[CLAUDE.md:47-52]()\n\n### Tool Categories Overview\n\nThe project exposes 213 tools across 58 categories:\n\n| Category | Count | Key Purpose |\n|----------|-------|-------------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities, with normalization |\n| Search | 7 | Basic, ranked (TF-IDF), boolean, fuzzy, auto-select |\n| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |\n| Semantic Search | 3 | Embedding similarity via OpenAI or local models |\n| Saved Searches | 5 | Store and re-execute frequent queries |\n| Tag Management | 6 | Tags, bulk ops, importance scores |\n| Tag Aliases | 5 | Tag synonym/alias management |\n| Hierarchy | 9 | Parent-child trees, subtree traversal |\n| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |\n| Analytics | 2 | Graph stats and integrity validation |\n| Compression | 4 | Duplicate detection, merge, auto-compress, archive |\n| Import/Export | 2 | 7 export formats (xml, json-ld, etc.) |\n\n资料来源：[CLAUDE.md:33-46]()\n\n## Documentation Guidelines\n\nWhen adding features, update the following documentation:\n\n| File | Purpose |\n|------|---------|\n| `README.md` | Update with new tools/functionality |\n| `CHANGELOG.md` | Document changes |\n| `WORKFLOW.md` | Update if development process changes |\n| Usage examples | Include practical examples |\n\n资料来源：[CONTRIBUTING.md:30-34]()\n\n## Pull Request Process\n\n### PR Checklist\n\n| Step | Requirement |\n|------|-------------|\n| **Title** | Clear, descriptive summary |\n| **Description** | What changed, why it changed, how to test it |\n| **Tests** | Include test results |\n| **Documentation** | Update relevant docs |\n| **Backward Compatibility** | Confirm no breaking changes |\n\n资料来源：[CONTRIBUTING.md:36-45]()\n\n### PR Workflow\n\n```bash\n# 1. Create feature branch\ngit checkout -b feature/your-feature-name\n\n# 2. Make changes and commit\ncd c:/mcp-servers/memory-mcp\ngit add .\ngit commit -m \"Description of your changes\"\n\n# 3. Push and create PR\ngit push origin feature/your-feature-name\n# Create PR on GitHub\n```\n\n资料来源：[CONTRIBUTING.md:1-8]()\n\n## Standalone Tools\n\nThe `tools/` directory contains standalone utilities, each with its own `package.json` and buildable to Windows exes via pkg:\n\n| Tool | Purpose |\n|------|---------|\n| `chunking-for-files` | Split/merge large files for context-limited editing |\n| `compress-for-context` | CTON compression for LLM context windows |\n| `create-dependency-graph` | Generate TypeScript project dependency graphs |\n| `migrate-from-jsonl-to-sqlite` | Convert between JSONL and SQLite formats |\n\n资料来源：[CLAUDE.md:44-51]()\n\n## Publishing to npm\n\n```bash\n# Token with \"bypass 2FA\" required — classic tokens are revoked\nnpm config set //registry.npmjs.org/:_authToken=$(cat c:\\mcp-servers\\npm_key.txt)\nnpm publish --access public\n```\n\n**Important Notes:**\n- The `prepare` script auto-builds, so separate `npm run build` is not needed before publish\n- Always bump version in `package.json` before publishing\n- Verify tarball contents before publishing\n\n资料来源：[CLAUDE.md:52-58]()\n\n### Verify Tarball Contents\n\n```bash\nnpm pack --dry-run 2>&1 | grep -E \"jsonl|\\.db|total files|package size\"\n```\n\n资料来源：[CLAUDE.md:59]()\n\n## Reporting Issues\n\n| Type | Action |\n|------|--------|\n| **Bug Reports** | Open an issue with detailed reproduction steps |\n| **Feature Requests** | Open an issue describing the use case |\n| **Questions** | Check existing issues or open a new one |\n\nThis project follows the [Model Context Protocol community guidelines](https://modelcontextprotocol.io/community/communication).\n\n资料来源：[CONTRIBUTING.md:60-65]()\n\n## License\n\nBy contributing, you agree that your contributions will be licensed under the MIT License.\n\n资料来源：[CONTRIBUTING.md:68-70]()\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: danielsimonjr/memory-mcp\n\nSummary: Found 6 potential pitfall items; 0 are high/blocking. Highest priority: capability - 能力判断依赖假设.\n\n## 1. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | README/documentation is current enough for a first validation pass.\n\n## 2. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | last_activity_observed missing\n\n## 3. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium\n\n## 4. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium\n\n## 5. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | issue_or_pr_quality=unknown\n\n## 6. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | release_recency=unknown\n\n<!-- canonical_name: danielsimonjr/memory-mcp; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "memory-mcp",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:1093926095",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/danielsimonjr/memory-mcp"
        },
        {
          "evidence_id": "art_fc807c0c51ad4a7c841e0addd977c506",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/danielsimonjr/memory-mcp#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "memory-mcp 说明书",
      "toc": [
        "https://github.com/danielsimonjr/memory-mcp 项目说明书",
        "目录",
        "Getting Started",
        "Overview",
        "Prerequisites",
        "Installation",
        "Clone the repository",
        "Install dependencies",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "9142e62df28a75bf2cceb4033b96f770888494ce",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "package.json",
      "README.md",
      "docs/README.md",
      "docs/architecture/dependency-graph.json",
      "docs/architecture/API.md",
      "docs/architecture/TEST_COVERAGE.md",
      "docs/architecture/dependency-summary.compact.json",
      "docs/architecture/OVERVIEW.md",
      "docs/architecture/ARCHITECTURE.md",
      "docs/architecture/DATAFLOW.md",
      "docs/architecture/dependency-graph.yaml",
      "docs/architecture/DEPENDENCY_GRAPH.md",
      "docs/architecture/COMPONENTS.md",
      "docs/architecture/test-coverage.json",
      "docs/architecture/unused-analysis.md",
      "docs/analysis/Comprehensive_Codebase_Review.md",
      "docs/analysis/BRUTALLY_HONEST_ANALYSIS.md",
      "docs/analysis/IMPLEMENTATION_VERIFICATION.md",
      "docs/guides/COMPRESSION.md",
      "docs/guides/HIERARCHY.md",
      "docs/guides/ARCHIVING.md",
      "docs/guides/MIGRATION.md",
      "docs/guides/QUERY_LANGUAGE.md",
      "docs/guides/TASKSCHEDULER_INTEGRATION.md",
      "docs/planning/PHASE_1_SPRINT_3_TODO.json",
      "docs/planning/PHASE_13_SPRINT_20_TODO.json",
      "docs/planning/PHASE_12_INDEX.json",
      "docs/planning/PHASE_8_INDEX.json",
      "docs/planning/PHASE_8_SPRINT_1_TODO.json",
      "docs/planning/PHASE_13_SPRINT_2_TODO.json",
      "docs/planning/PHASE_6_PERFORMANCE_OPTIMIZATION_PLAN.md",
      "docs/planning/PHASE_7_SPRINT_2_TODO.json",
      "docs/planning/PHASE_13_SPRINT_14_TODO.json",
      "docs/planning/PHASE_1_SPRINT_6_TODO.json",
      "docs/planning/PHASE_1_SPRINT_12_TODO.json",
      "docs/planning/PHASE_4_SPRINT_12_TODO.json",
      "docs/planning/PHASE_7_SPRINT_3_TODO.json",
      "docs/planning/PHASE_2B_SPRINT_2_TODO.json",
      "docs/planning/PHASE_13_SPRINT_3_TODO.json",
      "docs/planning/PHASE_4_PERFORMANCE_CACHING_PLAN.md"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [
      "community_discussion_evidence_below_public_threshold"
    ],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# @danielsimonjr/memory-mcp - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 @danielsimonjr/memory-mcp 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 它能做什么\n\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `npm install -g @danielsimonjr/memory-mcp` 证据：`README.md` Claim：`clm_0003` supported 0.86\n- `npx @danielsimonjr/memory-mcp` 证据：`README.md` Claim：`clm_0004` supported 0.86\n- `git clone https://github.com/danielsimonjr/memory-mcp.git` 证据：`README.md` Claim：`clm_0005` supported 0.86\n- `npm install && npm run build` 证据：`README.md` Claim：`clm_0006` supported 0.86\n- `npm install           # Install dependencies` 证据：`README.md` Claim：`clm_0007` supported 0.86\n- `npm install           # Install all dependencies` 证据：`CLAUDE.md` Claim：`clm_0008` supported 0.86\n- `npx vitest run tests/e2e/tools/entity-tools.test.ts` 证据：`CLAUDE.md` Claim：`clm_0009` supported 0.86\n- `npx vitest run -t \"should create entities\"` 证据：`CLAUDE.md` Claim：`clm_0010` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：需要管理员/安全审批\n- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。\n\n### 30 秒判断\n\n- **现在怎么做**：需要管理员/安全审批\n- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装\n- **先别相信**：角色质量和任务匹配不能直接相信。\n- **继续会触碰**：角色选择偏差、命令执行、宿主 AI 配置\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n### 现在还不能相信\n\n- **角色质量和任务匹配不能直接相信。**（unverified）：角色库证明有很多角色，不证明每个角色都适合你的具体任务，也不证明角色能产生高质量结果。\n- **不能把角色文案当成真实执行能力。**（unverified）：安装前只能判断角色描述和任务画像是否匹配，不能证明它能在宿主 AI 里完成任务。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`CLAUDE.md`\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n\n### 继续会触碰什么\n\n- **角色选择偏差**：用户对任务应该由哪个专家角色处理的判断。 原因：选错角色会让 AI 从错误专业视角回答，浪费时间或误导决策。\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`CLAUDE.md`, `README.md`\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`CLAUDE.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`CLAUDE.md`, `README.md`\n- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`CHANGELOG.md`, `CLAUDE.md`, `README.md`, `docs/planning/PHASE_4_PERFORMANCE_CACHING_PLAN.md` 等\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：先用交互式试用验证任务画像和角色匹配，不要先导入整套角色库。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **先备份宿主 AI 配置**：Skill、plugin、规则文件可能改变 Claude/Cursor/Codex 的默认行为。（适用：存在插件 manifest、Skill 或宿主规则入口时。）\n- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\n- **保留原始角色选择记录**：如果输出偏题，可以回到任务画像阶段重新选择角色，而不是继续沿着错误角色推进。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **准备撤销测试 API key 或 token**：测试凭证泄露或误用时，可以快速止损。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0011` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0012` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`CLAUDE.md`, `README.md` Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：248\n- 重要文件覆盖：40/248\n- 证据索引条目：80\n- 角色 / Skill 条目：68\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 @danielsimonjr/memory-mcp 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 @danielsimonjr/memory-mcp 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 @danielsimonjr/memory-mcp 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 68 个角色 / Skill / 项目文档条目。\n\n- **Documentation Index**（project_doc）：Welcome to the Enhanced Memory MCP documentation! This directory contains comprehensive documentation for developers, users, and contributors. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/README.md`\n- **CLAUDE.md**（project_doc）：This file provides guidance to Claude Code claude.ai/code when working with code in this repository. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CLAUDE.md`\n- **Memory MCP Server**（project_doc）：! Version https://img.shields.io/badge/version-12.3.0-blue.svg https://github.com/danielsimonjr/memory-mcp ! NPM https://img.shields.io/npm/v/@danielsimonjr/memory-mcp.svg https://www.npmjs.com/package/@danielsimonjr/memory-mcp ! License https://img.shields.io/badge/license-MIT-green.svg LICENSE ! MCP https://img.shields.io/badge/MCP-1.0-purple.svg https://modelcontextprotocol.io ! TypeScript https://img.shields.io/… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **DeepThinking MCP Tools**（project_doc）：This directory contains utility scripts for maintaining the DeepThinking MCP codebase. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tools/create-dependency-graph/README.md`\n- **Memory MCP Migration Tool**（project_doc）：Migrate knowledge graph data between JSONL and SQLite storage formats for the Memory MCP server. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`tools/migrate-from-jsonl-to-sqlite/README.md`\n- **Contributing to Enhanced Memory MCP**（project_doc）：Contributing to Enhanced Memory MCP 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CONTRIBUTING.md`\n- **Brutally Honest Codebase Analysis — Final Cut**（project_doc）：Brutally Honest Codebase Analysis — Final Cut 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/analysis/BRUTALLY_HONEST_ANALYSIS.md`\n- **Comprehensive Codebase Review: memory-mcp**（project_doc）：Comprehensive Codebase Review: memory-mcp 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/analysis/Comprehensive_Codebase_Review.md`\n- **Implementation Verification Report**（project_doc）：Date: 2026-01-01 Original Analysis: 2026-01-01 Version Before: 0.11.5 / 0.59.0 Version After: 8.50.24 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/analysis/IMPLEMENTATION_VERIFICATION.md`\n- **Memory MCP - API Reference**（project_doc）：Version : 12.2.0 Last Updated : 2026-04-26 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/architecture/API.md`\n- **Memory MCP - System Architecture**（project_doc）：Version : 12.2.0 Last Updated : 2026-04-26 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/architecture/ARCHITECTURE.md`\n- **Memory MCP - Component Reference**（project_doc）：Version : 12.2.0 Last Updated : 2026-04-26 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/architecture/COMPONENTS.md`\n- **Memory MCP - Data Flow Documentation**（project_doc）：Memory MCP - Data Flow Documentation 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/architecture/DATAFLOW.md`\n- **@danielsimonjr/memory-mcp - Dependency Graph**（project_doc）：@danielsimonjr/memory-mcp - Dependency Graph 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/architecture/DEPENDENCY_GRAPH.md`\n- **Memory MCP Server - Project Overview**（project_doc）：Memory MCP Server - Project Overview 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/architecture/OVERVIEW.md`\n- **Unused Files and Exports Analysis**（project_doc）：- Potentially unused files : 0 - Potentially unused exports : 9 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/architecture/unused-analysis.md`\n- **Context/Token Optimization Refactoring Plan**（project_doc）：Context/Token Optimization Refactoring Plan 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/development/CONTEXT_OPTIMIZATION_PLAN.md`\n- **Implementation Plan - Memory MCP Server**（project_doc）：Implementation Plan - Memory MCP Server 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/development/IMPLEMENTATION_PLAN.md`\n- **Index.ts Refactoring - Detailed Implementation Tasks**（project_doc）：Index.ts Refactoring - Detailed Implementation Tasks 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/development/IMPLEMENTATION_TASKS.md`\n- **Memory MCP Improvement Plan**（project_doc）：Memory MCP Improvement Plan Comprehensive Roadmap for Advanced Features 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/development/IMPROVEMENT_PLAN.md`\n- **Index.ts Refactoring Plan**（project_doc）：This document outlines a comprehensive plan to refactor the monolithic src/memory/index.ts file 4,187 lines into a modular, maintainable architecture. The refactoring will improve code organization, testability, maintainability, and developer experience while preserving all existing functionality. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/development/REFACTORING_PLAN.md`\n- **Memory MCP Development Workflow**（project_doc）：Updated 2026-04-26 for v12.2.0. The previous version of this file referenced a pre-Phase-13 layout and a 15-tool count — both obsolete. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/development/WORKFLOW.md`\n- **Memory Archiving Guide**（project_doc）：Memory Archiving Guide Managing Memory Lifecycle and Long-Term Storage 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/guides/ARCHIVING.md`\n- **Memory Compression Guide**（project_doc）：Memory Compression Guide Brotli Compression, Response Compression, and Entity Deduplication 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/guides/COMPRESSION.md`\n- **Hierarchical Nesting Guide**（project_doc）：Hierarchical Nesting Guide Organizing Knowledge with Parent-Child Relationships 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/guides/HIERARCHY.md`\n- **Migration Guide: v0.7.0 → v0.8.0**（project_doc）：Migration Guide: v0.7.0 → v0.8.0 Upgrading to Enhanced Memory MCP v0.8.0 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/guides/MIGRATION.md`\n- **Query Language Reference**（project_doc）：Query Language Reference Boolean Search Syntax for Advanced Queries 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/guides/QUERY_LANGUAGE.md`\n- **TaskScheduler Integration Guide**（project_doc）：Phase 9B : This guide documents how to integrate the TaskScheduler's progress tracking and cancellation support with long-running operations in the Memory MCP server. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/guides/TASKSCHEDULER_INTEGRATION.md`\n- **Phase 10: Advanced Features & Developer Experience**（project_doc）：Phase 10: Advanced Features & Developer Experience 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_10_IMPROVEMENT_PLAN.md`\n- **Phase 11: Three-Layer Hybrid Search & Intelligent Retrieval**（project_doc）：Phase 11: Three-Layer Hybrid Search & Intelligent Retrieval 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_11_IMPROVEMENT_PLAN.md`\n- **Phase 12: Performance Optimization Plan**（project_doc）：Phase 12: Performance Optimization Plan 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_12_PERFORMANCE_OPTIMIZATION_PLAN.md`\n- **MemoryJS Extraction Plan**（project_doc）：Project Refactoring: memory-mcp → memoryjs + memory-mcp 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_13_MEMORYJS_EXTRACTION_PLAN.md`\n- **Phase 1 Refactoring Plan: Performance & Architecture Fixes**（project_doc）：Phase 1 Refactoring Plan: Performance & Architecture Fixes 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_1_REFACTORING_PLAN.md`\n- **Phase 2 Test Plan: Achieve 90% Test Coverage**（project_doc）：Phase 2 Test Plan: Achieve 90% Test Coverage 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_2A_TEST_PLAN_SERVER_SIDE.md`\n- **Phase 2B Test Plan: MCP Client-Side Tool Testing**（project_doc）：Phase 2B Test Plan: MCP Client-Side Tool Testing 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_2B_TEST_PLAN_CLIENT_SIDE.md`\n- **Phase 3 Refactoring Plan: Brotli Compression Integration**（project_doc）：Phase 3 Refactoring Plan: Brotli Compression Integration 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_3_REFACTORING_PLAN.md`\n- **Phase 4: Performance Caching & Graph Algorithms Plan**（project_doc）：Phase 4: Performance Caching & Graph Algorithms Plan 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_4_PERFORMANCE_CACHING_PLAN.md`\n- **Phase 5: Folder Restructuring Plan**（project_doc）：Version: 8.57.0 → 8.58.0 Date: 2026-01-02 Status: Planning 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_5_FOLDER_RESTRUCTURING_PLAN.md`\n- **Phase 6: Performance Optimization Plan**（project_doc）：Phase 6: Performance Optimization Plan 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_6_PERFORMANCE_OPTIMIZATION_PLAN.md`\n- **Phase 7: Parallel Processing & Advanced I/O**（project_doc）：Phase 7: Parallel Processing & Advanced I/O 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_7_IMPROVEMENT_PLAN.md`\n- **Phase 8: Workerpool Library Integration**（project_doc）：Phase 8: Workerpool Library Integration 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_8_WORKERPOOL_INTEGRATION.md`\n- **Phase 9B: TaskScheduler Integration**（project_doc）：Phase 9B: TaskScheduler Integration 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_9B_IMPROVEMENT_PLAN.md`\n- **Phase 9: Advanced Optimizations**（project_doc）：Version : 1.0.0 Created : 2026-01-04 Status : PLANNED Total Sprints : 3 Total Tasks : 11 tasks organized into sprints of 3-4 items Prerequisites : Phase 8 Workerpool Integration complete, All 2209+ tests passing 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/planning/PHASE_9_IMPROVEMENT_PLAN.md`\n- **Documentation Inventory & Organization**（project_doc）：Documentation Inventory & Organization 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/reports/DOCUMENTATION_INVENTORY.md`\n- **Code Quality Improvements Summary**（project_doc）：This document provides a comprehensive summary of all code quality improvements made to the memory-mcp project during the systematic code review and enhancement process from November 24, 2025. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/reports/IMPROVEMENTS_SUMMARY.md`\n- **Phase 6 Performance Optimization - Baseline Metrics**（project_doc）：Phase 6 Performance Optimization - Baseline Metrics 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/reports/PHASE_6_BASELINE_METRICS.md`\n- **Refactoring Summary**（project_doc）：Overview Successfully refactored monolithic src/memory/index.ts 4,187 lines into a modular, maintainable architecture with 40 TypeScript files across 8 phases. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/reports/REFACTORING_SUMMARY.md`\n- **Sprint Progress Summary**（project_doc）：Sprint 3: Performance Optimizations ✅ COMPLETE 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/reports/SPRINT_PROGRESS.md`\n- **Sprint Summary: Code Review Implementation v0.11.6 → v0.14.0**（project_doc）：Sprint Summary: Code Review Implementation v0.11.6 → v0.14.0 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/reports/SPRINT_SUMMARY.md`\n- **Refactoring Task Summary**（project_doc）：This document summarizes the comprehensive planning created for the index.ts refactoring project. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/reports/TASK_SUMMARY.md`\n- **Future Features Roadmap**（project_doc）：Version: 3.2.0 Last Updated: 2026-04-26 Current Version: 12.2.0 Target Version: 13.0.0 post-v12.2.0 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/roadmap/FUTURE_FEATURES.md`\n- **Performance & Optimization Roadmap**（project_doc）：Version: 3.1.0 Last Updated: 2026-04-26 Current Version: 12.2.0 Target Version: 13.0.0 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/roadmap/PERFORMANCE_AND_CAPABILITIES.md`\n- **Test Coverage Analysis**（project_doc）：Generated : 2026-01-09 pre-Phase 13 extraction Status : Historical — see note below. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/architecture/TEST_COVERAGE.md`\n- **Comprehensive Code Review - Memory MCP Server**（project_doc）：Comprehensive Code Review - Memory MCP Server 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/CODE_REVIEW.md`\n- **File Size Policy**（project_doc）：This project enforces strict file size limits to maintain code quality, readability, and maintainability. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/FILE_SIZE_POLICY.md`\n- **Description**（project_doc）：Server Details - Server: - Changes to: 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.github/pull_request_template.md`\n- **Changelog**（project_doc）：All notable changes to the Enhanced Memory MCP will be documented in this file. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CHANGELOG.md`\n- **Code of Conduct - Enhanced Memory MCP**（project_doc）：Code of Conduct - Enhanced Memory MCP 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CODE_OF_CONDUCT.md`\n- **Security Policy**（project_doc）：Thank you for helping keep the Enhanced Memory MCP server secure. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`SECURITY.md`\n- **Chunking for Files**（project_doc）：Split or merge large files for editing within context limits 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.claude/commands/CHUNK.md`\n- **Project Commit Workflow**（project_doc）：Full project commit workflow - typecheck, test, version bump, changelog, and push to GitHub 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.claude/commands/COMMIT.md`\n- **Compress for Context CTON**（project_doc）：Compress files using CTON format for LLM context optimization 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.claude/commands/CTON.md`\n- **Dependency Graph Analysis**（project_doc）：Generate and analyze project dependency graph 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.claude/commands/DEPS.md`\n- **Project Exploration & Knowledge Indexing**（project_doc）：Index project and update knowledge graph + CLAUDE.md 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.claude/commands/EXPLORE.md`\n- **Create Dependency Graph**（project_doc）：Generate a dependency graph for a TypeScript project 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.claude/commands/GRAPH.md`\n- **Memory Graph Operations**（project_doc）：Comprehensive memory graph operations - CRUD, search, and maintenance 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.claude/commands/MEMORY.md`\n- **Migrate Storage Format**（project_doc）：Migrate memory storage between JSONL and SQLite formats 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.claude/commands/MIGRATE.md`\n- **File Search**（project_doc）：Search files using Everything fast indexed or fzf fuzzy matching 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`.claude/commands/SEARCH.md`\n\n## 证据索引\n\n- 共索引 80 条证据。\n\n- **Documentation Index**（documentation）：Welcome to the Enhanced Memory MCP documentation! This directory contains comprehensive documentation for developers, users, and contributors. 证据：`docs/README.md`\n- **CLAUDE.md**（documentation）：This file provides guidance to Claude Code claude.ai/code when working with code in this repository. 证据：`CLAUDE.md`\n- **Memory MCP Server**（documentation）：! Version https://img.shields.io/badge/version-12.3.0-blue.svg https://github.com/danielsimonjr/memory-mcp ! NPM https://img.shields.io/npm/v/@danielsimonjr/memory-mcp.svg https://www.npmjs.com/package/@danielsimonjr/memory-mcp ! License https://img.shields.io/badge/license-MIT-green.svg LICENSE ! MCP https://img.shields.io/badge/MCP-1.0-purple.svg https://modelcontextprotocol.io ! TypeScript https://img.shields.io/badge/TypeScript-5.6-blue.svg https://www.typescriptlang.org/ ! Coverage https://img.shields.io/badge/coverage-80.7%25-yellow.svg docs/architecture/TEST COVERAGE.md 证据：`README.md`\n- **DeepThinking MCP Tools**（documentation）：This directory contains utility scripts for maintaining the DeepThinking MCP codebase. 证据：`tools/create-dependency-graph/README.md`\n- **Memory MCP Migration Tool**（documentation）：Migrate knowledge graph data between JSONL and SQLite storage formats for the Memory MCP server. 证据：`tools/migrate-from-jsonl-to-sqlite/README.md`\n- **Package**（package_manifest）：{ \"name\": \"@danielsimonjr/memory-mcp\", \"version\": \"12.3.0\", \"description\": \"Enhanced MCP memory server with hierarchies, compression, archiving, graph algorithms, semantic search, temporal KG, RBAC, bitemporal validity, OCC, procedural memory, causal reasoning, world model, do not remember exclusions, decision rationale, project context, heuristic guidelines, tool affordance + observer, observation dedup, spell correction, and 213 advanced tools\", \"license\": \"MIT\", \"engines\": { \"node\": \" =18.0.0\" }, \"author\": \"Daniel Simon Jr. https://github.com/danielsimonjr \", \"homepage\": \"https://github.com/danielsimonjr/memory-mcp\", \"bugs\": \"https://github.com/danielsimonjr/memory-mcp/issues\", \"reposito… 证据：`package.json`\n- **Contributing to Enhanced Memory MCP**（documentation）：Contributing to Enhanced Memory MCP 证据：`CONTRIBUTING.md`\n- **Package**（package_manifest）：{ \"name\": \"chunking-for-files\", \"version\": \"1.0.0\", \"description\": \"Split and merge large files for editing within context limits\", \"main\": \"./dist/chunking-for-files.js\", \"bin\": { \"chunking-for-files\": \"./dist/chunking-for-files.js\" }, \"scripts\": { \"build\": \"npm run build:ts && npm run build:exe\", \"build:ts\": \"tsc\", \"build:exe\": \"npx @yao-pkg/pkg . --target node22-win-x64 --output chunking-for-files.exe\", \"start\": \"node dist/chunking-for-files.js\" }, \"pkg\": { \"scripts\": \"dist/ / .js\" , \"targets\": \"node22-win-x64\" }, \"keywords\": \"markdown\", \"chunker\", \"chunking\", \"split\", \"merge\", \"llm\", \"context\" , \"author\": \"DeepThinking MCP\", \"license\": \"MIT\", \"devDependencies\": { \"@types/node\": \"^22\", \"… 证据：`tools/chunking-for-files/package.json`\n- **Package**（package_manifest）：{ \"name\": \"compress-for-context\", \"version\": \"1.0.0\", \"description\": \"Compress files for LLM context windows\", \"type\": \"module\", \"scripts\": { \"build\": \"npm run build:ts && npm run build:exe\", \"build:ts\": \"tsc\", \"build:exe\": \"npx @yao-pkg/pkg . --target node22-win-x64 --output compress-for-context.exe\", \"start\": \"node dist/compress-for-context.js\" }, \"bin\": { \"compress-for-context\": \"./dist/compress-for-context.js\" }, \"pkg\": { \"scripts\": \"dist/ / .js\" , \"targets\": \"node22-win-x64\" }, \"devDependencies\": { \"@types/node\": \"^25.0.2\", \"@yao-pkg/pkg\": \"^6.11.0\", \"typescript\": \"^5.3.0\" }, \"engines\": { \"node\": \" =18.0.0\" } } 证据：`tools/compress-for-context/package.json`\n- **Package**（package_manifest）：{ \"name\": \"create-dependency-graph\", \"version\": \"1.0.0\", \"description\": \"Generate dependency graph documentation for TypeScript projects\", \"scripts\": { \"build\": \"npm run build:ts && npm run build:exe\", \"build:ts\": \"tsc\", \"build:exe\": \"npx @yao-pkg/pkg . --target node22-win-x64 --output create-dependency-graph.exe\", \"start\": \"node dist/create-dependency-graph.js\" }, \"bin\": { \"create-dependency-graph\": \"./dist/create-dependency-graph.js\" }, \"pkg\": { \"scripts\": \"dist/ / .js\" , \"targets\": \"node22-win-x64\" }, \"dependencies\": { \"js-yaml\": \"^4.1.0\" }, \"devDependencies\": { \"@types/js-yaml\": \"^4.0.9\", \"@types/node\": \"^25.0.2\", \"@yao-pkg/pkg\": \"^6.11.0\", \"typescript\": \"^5.3.0\" }, \"engines\": { \"node\":… 证据：`tools/create-dependency-graph/package.json`\n- **Package**（package_manifest）：{ \"name\": \"migrate-from-jsonl-to-sqlite\", \"version\": \"1.1.0\", \"description\": \"Migration tool for Memory MCP - converts between JSONL and SQLite storage formats\", \"scripts\": { \"build\": \"npm run build:ts && npm run build:exe\", \"build:ts\": \"tsc\", \"build:exe\": \"npx @yao-pkg/pkg . --target node22-win-x64 --output migrate-from-jsonl-to-sqlite.exe\", \"start\": \"node dist/migrate-from-jsonl-to-sqlite.js\" }, \"bin\": { \"migrate-from-jsonl-to-sqlite\": \"./dist/migrate-from-jsonl-to-sqlite.js\" }, \"pkg\": { \"scripts\": \"dist/ / .js\" , \"assets\": \"node modules/better-sqlite3/build/Release/ .node\", \"node modules/better-sqlite3/prebuilds/ / \" , \"targets\": \"node22-win-x64\" }, \"dependencies\": { \"better-sqlite3\": \"^… 证据：`tools/migrate-from-jsonl-to-sqlite/package.json`\n- **License**（source_file）：Copyright c 2025 Anthropic, PBC Original Memory MCP Server Copyright c 2025 Daniel Simon Jr. Phase 1-4 Enhancements 证据：`LICENSE`\n- **Brutally Honest Codebase Analysis — Final Cut**（documentation）：Brutally Honest Codebase Analysis — Final Cut 证据：`docs/analysis/BRUTALLY_HONEST_ANALYSIS.md`\n- **Comprehensive Codebase Review: memory-mcp**（documentation）：Comprehensive Codebase Review: memory-mcp 证据：`docs/analysis/Comprehensive_Codebase_Review.md`\n- **Implementation Verification Report**（documentation）：Date: 2026-01-01 Original Analysis: 2026-01-01 Version Before: 0.11.5 / 0.59.0 Version After: 8.50.24 证据：`docs/analysis/IMPLEMENTATION_VERIFICATION.md`\n- **Memory MCP - API Reference**（documentation）：Version : 12.2.0 Last Updated : 2026-04-26 证据：`docs/architecture/API.md`\n- **Memory MCP - System Architecture**（documentation）：Version : 12.2.0 Last Updated : 2026-04-26 证据：`docs/architecture/ARCHITECTURE.md`\n- **Memory MCP - Component Reference**（documentation）：Version : 12.2.0 Last Updated : 2026-04-26 证据：`docs/architecture/COMPONENTS.md`\n- **Memory MCP - Data Flow Documentation**（documentation）：Memory MCP - Data Flow Documentation 证据：`docs/architecture/DATAFLOW.md`\n- **@danielsimonjr/memory-mcp - Dependency Graph**（documentation）：@danielsimonjr/memory-mcp - Dependency Graph 证据：`docs/architecture/DEPENDENCY_GRAPH.md`\n- **Memory MCP Server - Project Overview**（documentation）：Memory MCP Server - Project Overview 证据：`docs/architecture/OVERVIEW.md`\n- **Unused Files and Exports Analysis**（documentation）：- Potentially unused files : 0 - Potentially unused exports : 9 证据：`docs/architecture/unused-analysis.md`\n- **Context/Token Optimization Refactoring Plan**（documentation）：Context/Token Optimization Refactoring Plan 证据：`docs/development/CONTEXT_OPTIMIZATION_PLAN.md`\n- **Implementation Plan - Memory MCP Server**（documentation）：Implementation Plan - Memory MCP Server 证据：`docs/development/IMPLEMENTATION_PLAN.md`\n- **Index.ts Refactoring - Detailed Implementation Tasks**（documentation）：Index.ts Refactoring - Detailed Implementation Tasks 证据：`docs/development/IMPLEMENTATION_TASKS.md`\n- **Memory MCP Improvement Plan**（documentation）：Memory MCP Improvement Plan Comprehensive Roadmap for Advanced Features 证据：`docs/development/IMPROVEMENT_PLAN.md`\n- **Index.ts Refactoring Plan**（documentation）：This document outlines a comprehensive plan to refactor the monolithic src/memory/index.ts file 4,187 lines into a modular, maintainable architecture. The refactoring will improve code organization, testability, maintainability, and developer experience while preserving all existing functionality. 证据：`docs/development/REFACTORING_PLAN.md`\n- **Memory MCP Development Workflow**（documentation）：Updated 2026-04-26 for v12.2.0. The previous version of this file referenced a pre-Phase-13 layout and a 15-tool count — both obsolete. 证据：`docs/development/WORKFLOW.md`\n- **Memory Archiving Guide**（documentation）：Memory Archiving Guide Managing Memory Lifecycle and Long-Term Storage 证据：`docs/guides/ARCHIVING.md`\n- **Memory Compression Guide**（documentation）：Memory Compression Guide Brotli Compression, Response Compression, and Entity Deduplication 证据：`docs/guides/COMPRESSION.md`\n- **Hierarchical Nesting Guide**（documentation）：Hierarchical Nesting Guide Organizing Knowledge with Parent-Child Relationships 证据：`docs/guides/HIERARCHY.md`\n- **Migration Guide: v0.7.0 → v0.8.0**（documentation）：Migration Guide: v0.7.0 → v0.8.0 Upgrading to Enhanced Memory MCP v0.8.0 证据：`docs/guides/MIGRATION.md`\n- **Query Language Reference**（documentation）：Query Language Reference Boolean Search Syntax for Advanced Queries 证据：`docs/guides/QUERY_LANGUAGE.md`\n- **TaskScheduler Integration Guide**（documentation）：Phase 9B : This guide documents how to integrate the TaskScheduler's progress tracking and cancellation support with long-running operations in the Memory MCP server. 证据：`docs/guides/TASKSCHEDULER_INTEGRATION.md`\n- **Phase 10: Advanced Features & Developer Experience**（documentation）：Phase 10: Advanced Features & Developer Experience 证据：`docs/planning/PHASE_10_IMPROVEMENT_PLAN.md`\n- **Phase 11: Three-Layer Hybrid Search & Intelligent Retrieval**（documentation）：Phase 11: Three-Layer Hybrid Search & Intelligent Retrieval 证据：`docs/planning/PHASE_11_IMPROVEMENT_PLAN.md`\n- **Phase 12: Performance Optimization Plan**（documentation）：Phase 12: Performance Optimization Plan 证据：`docs/planning/PHASE_12_PERFORMANCE_OPTIMIZATION_PLAN.md`\n- **MemoryJS Extraction Plan**（documentation）：Project Refactoring: memory-mcp → memoryjs + memory-mcp 证据：`docs/planning/PHASE_13_MEMORYJS_EXTRACTION_PLAN.md`\n- **Phase 1 Refactoring Plan: Performance & Architecture Fixes**（documentation）：Phase 1 Refactoring Plan: Performance & Architecture Fixes 证据：`docs/planning/PHASE_1_REFACTORING_PLAN.md`\n- **Phase 2 Test Plan: Achieve 90% Test Coverage**（documentation）：Phase 2 Test Plan: Achieve 90% Test Coverage 证据：`docs/planning/PHASE_2A_TEST_PLAN_SERVER_SIDE.md`\n- **Phase 2B Test Plan: MCP Client-Side Tool Testing**（documentation）：Phase 2B Test Plan: MCP Client-Side Tool Testing 证据：`docs/planning/PHASE_2B_TEST_PLAN_CLIENT_SIDE.md`\n- **Phase 3 Refactoring Plan: Brotli Compression Integration**（documentation）：Phase 3 Refactoring Plan: Brotli Compression Integration 证据：`docs/planning/PHASE_3_REFACTORING_PLAN.md`\n- **Phase 4: Performance Caching & Graph Algorithms Plan**（documentation）：Phase 4: Performance Caching & Graph Algorithms Plan 证据：`docs/planning/PHASE_4_PERFORMANCE_CACHING_PLAN.md`\n- **Phase 5: Folder Restructuring Plan**（documentation）：Version: 8.57.0 → 8.58.0 Date: 2026-01-02 Status: Planning 证据：`docs/planning/PHASE_5_FOLDER_RESTRUCTURING_PLAN.md`\n- **Phase 6: Performance Optimization Plan**（documentation）：Phase 6: Performance Optimization Plan 证据：`docs/planning/PHASE_6_PERFORMANCE_OPTIMIZATION_PLAN.md`\n- **Phase 7: Parallel Processing & Advanced I/O**（documentation）：Phase 7: Parallel Processing & Advanced I/O 证据：`docs/planning/PHASE_7_IMPROVEMENT_PLAN.md`\n- **Phase 8: Workerpool Library Integration**（documentation）：Phase 8: Workerpool Library Integration 证据：`docs/planning/PHASE_8_WORKERPOOL_INTEGRATION.md`\n- **Phase 9B: TaskScheduler Integration**（documentation）：Phase 9B: TaskScheduler Integration 证据：`docs/planning/PHASE_9B_IMPROVEMENT_PLAN.md`\n- **Phase 9: Advanced Optimizations**（documentation）：Version : 1.0.0 Created : 2026-01-04 Status : PLANNED Total Sprints : 3 Total Tasks : 11 tasks organized into sprints of 3-4 items Prerequisites : Phase 8 Workerpool Integration complete, All 2209+ tests passing 证据：`docs/planning/PHASE_9_IMPROVEMENT_PLAN.md`\n- **Documentation Inventory & Organization**（documentation）：Documentation Inventory & Organization 证据：`docs/reports/DOCUMENTATION_INVENTORY.md`\n- **Code Quality Improvements Summary**（documentation）：This document provides a comprehensive summary of all code quality improvements made to the memory-mcp project during the systematic code review and enhancement process from November 24, 2025. 证据：`docs/reports/IMPROVEMENTS_SUMMARY.md`\n- **Phase 6 Performance Optimization - Baseline Metrics**（documentation）：Phase 6 Performance Optimization - Baseline Metrics 证据：`docs/reports/PHASE_6_BASELINE_METRICS.md`\n- **Refactoring Summary**（documentation）：Overview Successfully refactored monolithic src/memory/index.ts 4,187 lines into a modular, maintainable architecture with 40 TypeScript files across 8 phases. 证据：`docs/reports/REFACTORING_SUMMARY.md`\n- **Sprint Progress Summary**（documentation）：Sprint 3: Performance Optimizations ✅ COMPLETE 证据：`docs/reports/SPRINT_PROGRESS.md`\n- **Sprint Summary: Code Review Implementation v0.11.6 → v0.14.0**（documentation）：Sprint Summary: Code Review Implementation v0.11.6 → v0.14.0 证据：`docs/reports/SPRINT_SUMMARY.md`\n- **Refactoring Task Summary**（documentation）：This document summarizes the comprehensive planning created for the index.ts refactoring project. 证据：`docs/reports/TASK_SUMMARY.md`\n- **Future Features Roadmap**（documentation）：Version: 3.2.0 Last Updated: 2026-04-26 Current Version: 12.2.0 Target Version: 13.0.0 post-v12.2.0 证据：`docs/roadmap/FUTURE_FEATURES.md`\n- **Performance & Optimization Roadmap**（documentation）：Version: 3.1.0 Last Updated: 2026-04-26 Current Version: 12.2.0 Target Version: 13.0.0 证据：`docs/roadmap/PERFORMANCE_AND_CAPABILITIES.md`\n- **Test Coverage Analysis**（documentation）：Generated : 2026-01-09 pre-Phase 13 extraction Status : Historical — see note below. 证据：`docs/architecture/TEST_COVERAGE.md`\n- **Comprehensive Code Review - Memory MCP Server**（documentation）：Comprehensive Code Review - Memory MCP Server 证据：`.github/CODE_REVIEW.md`\n- 其余 20 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`docs/README.md`, `CLAUDE.md`, `README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`docs/README.md`, `CLAUDE.md`, `README.md`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\nThe following material strengthens the Repomix/AI Context Pack body. Human Manual is only a reading skeleton; pitfall logs become hard operating constraints for the host AI.\n\n## Human Manual Skeleton\n\nUsage rule: this is only a reading path and salience signal, not factual authority. Concrete facts must still come from repo evidence / Claim Graph.\n\nHard rules for the host AI:\n- Do not treat page titles, order, summaries, or importance as project facts.\n- When explaining the Human Manual skeleton, state that it is only a reading path / salience signal.\n- Capability, installation, compatibility, runtime status, and risk judgments must cite repo evidence, source paths, or Claim Graph.\n\n- **Getting Started**：importance `high`\n  - source_paths: README.md, package.json\n- **Project Structure**：importance `medium`\n  - source_paths: src/index.ts, src/server/MCPServer.ts, src/server/toolDefinitions.ts, src/server/toolHandlers.ts\n- **Architecture Overview**：importance `high`\n  - source_paths: src/index.ts, src/server/MCPServer.ts, docs/architecture/ARCHITECTURE.md, docs/architecture/COMPONENTS.md, docs/architecture/dependency-graph.json\n- **Storage Backends**：importance `high`\n  - source_paths: tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts, src/server/responseCompressor.ts\n- **Entity-Relation-Observation Model**：importance `high`\n  - source_paths: docs/architecture/API.md, docs/guides/HIERARCHY.md\n- **Tool Reference**：importance `high`\n  - source_paths: src/server/toolDefinitions.ts, src/server/toolHandlers.ts, docs/architecture/API.md\n- **Search Capabilities**：importance `high`\n  - source_paths: docs/guides/QUERY_LANGUAGE.md, docs/guides/COMPRESSION.md\n- **Temporal and Advanced Features**：importance `medium`\n  - source_paths: docs/architecture/TEST_COVERAGE.md, docs/planning/PHASE_13_MEMORYJS_EXTRACTION_PLAN.md, docs/planning/PHASE_15_IMPROVEMENT_PLAN.md\n\n## Repo Inspection Evidence\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `9142e62df28a75bf2cceb4033b96f770888494ce`\n- inspected_files: `package.json`, `README.md`, `docs/README.md`, `docs/architecture/dependency-graph.json`, `docs/architecture/API.md`, `docs/architecture/TEST_COVERAGE.md`, `docs/architecture/dependency-summary.compact.json`, `docs/architecture/OVERVIEW.md`, `docs/architecture/ARCHITECTURE.md`, `docs/architecture/DATAFLOW.md`, `docs/architecture/dependency-graph.yaml`, `docs/architecture/DEPENDENCY_GRAPH.md`, `docs/architecture/COMPONENTS.md`, `docs/architecture/test-coverage.json`, `docs/architecture/unused-analysis.md`, `docs/analysis/Comprehensive_Codebase_Review.md`, `docs/analysis/BRUTALLY_HONEST_ANALYSIS.md`, `docs/analysis/IMPLEMENTATION_VERIFICATION.md`, `docs/guides/COMPRESSION.md`, `docs/guides/HIERARCHY.md`\n\nHard rules for the host AI:\n- Without repo_clone_verified=true, do not claim the source code has been read.\n- Without repo_inspection_verified=true, do not turn README/docs/package observations into facts.\n- Without quick_start_verified=true, do not claim the Quick Start has been successfully run.\n\n## Doramagic Pitfall Constraints\n\nThese rules come from Doramagic discovery, validation, or compilation pitfalls. The host AI must treat them as operating constraints, not general background notes.\n\n### Constraint 1: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | README/documentation is current enough for a first validation pass.\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 2: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | last_activity_observed missing\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 3: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 4: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- Evidence: risks.scoring_risks | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 5: issue/PR 响应质量未知\n\n- Trigger: issue_or_pr_quality=unknown。\n- Host AI rule: 抽样最近 issue/PR，判断是否长期无人处理。\n- Why it matters: 用户无法判断遇到问题后是否有人维护。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | issue_or_pr_quality=unknown\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 6: 发布节奏不明确\n\n- Trigger: release_recency=unknown。\n- Host AI rule: 确认最近 release/tag 和 README 安装命令是否一致。\n- Why it matters: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | release_recency=unknown\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n",
      "summary": "Context and operating boundaries for host AI agents.",
      "title": "AI Context Pack"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card\n\nProject: danielsimonjr/memory-mcp\n\n## Doramagic Trial Decision\n\nCurrent decision: it can enter pre-publication recommendation checks. First use should still start with least privilege, a temporary directory, and reversible configuration.\n\n## What The User Can Do Now\n\n- Read the Human Manual first to understand the project purpose and main workflows.\n- Use Prompt Preview for pre-install exploration; it validates interaction shape, not real execution.\n- Run official Quick Start commands only inside an isolated environment, not a primary setup.\n\n## Do Not Do Yet\n\n- Do not treat Prompt Preview as a real project execution result.\n- Do not treat metadata-only validation as sandbox installation validation.\n- Do not describe unverified capabilities as supported, working, or safe to install.\n- Do not provide production data, private files, real secrets, or primary host configuration on first trial.\n\n## Pre-Install Checklist\n\n- Host AI match: mcp_host\n- Official installation entry status: official entry point found\n- Isolated temporary directory, temporary host, or container validation: required\n- Configuration rollback path: required\n- API keys, network access, file access, or host configuration changes: treat as high risk until confirmed\n- Installation command, actual output, and failure logs: must be recorded\n\n## Current Blockers\n\n- review_required: community_discussion_evidence_below_public_threshold\n\n## Project-Specific Pitfalls\n\n- 能力判断依赖假设 (medium): 假设不成立时，用户拿不到承诺的能力。 Suggested check: 将假设转成下游验证清单。\n- 维护活跃度未知 (medium): 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。 Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 下游验证发现风险项 (medium): 下游已经要求复核，不能在页面中弱化。 Suggested check: 进入安全/权限治理复核队列。\n- 存在评分风险 (medium): 风险会影响是否适合普通用户安装。 Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- issue/PR 响应质量未知 (low): 用户无法判断遇到问题后是否有人维护。 Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n\n## Risk And Permission Notes\n\n- no_demo: medium\n\n## Evidence Gaps\n\n- No structured evidence gaps are currently visible.\n",
      "summary": "Installation, permission, validation, and pre-recommendation risks.",
      "title": "Boundary & Risk Card"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/danielsimonjr/memory-mcp 项目说明书\n\n生成时间：2026-05-16 09:20:25 UTC\n\n## 目录\n\n- [Getting Started](#getting-started)\n- [Project Structure](#project-structure)\n- [Architecture Overview](#architecture-overview)\n- [Storage Backends](#storage-backends)\n- [Entity-Relation-Observation Model](#entity-model)\n- [Tool Reference](#tool-reference)\n- [Search Capabilities](#search-capabilities)\n- [Temporal and Advanced Features](#temporal-features)\n- [Collaboration and Security](#collaboration-security)\n- [Development Guide](#development-guide)\n\n<a id='getting-started'></a>\n\n## Getting Started\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Development Guide](#development-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/README.md)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)\n- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n- [tools/create-dependency-graph/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md)\n</details>\n\n# Getting Started\n\nThis guide provides everything you need to install, configure, and begin using the Enhanced Memory MCP server.\n\n## Overview\n\nMemory MCP is a Model Context Protocol (MCP) server that provides persistent memory and knowledge graph capabilities for AI agents and applications. It exposes 213 tools across 58 categories for entity management, semantic search, hierarchy traversal, graph algorithms, and context compression. 资料来源：[CLAUDE.md:1]()\n\nThe server acts as a bridge between AI applications and a knowledge graph storage layer, enabling:\n\n- Persistent entity and relation storage\n- Semantic and ranked search capabilities\n- Time-based memory decay and importance scoring\n- Context compression for large inputs\n- Multi-format data import/export\n\n## Prerequisites\n\nBefore installing Memory MCP, ensure your environment meets these requirements:\n\n| Requirement | Minimum Version | Notes |\n|-------------|-----------------|-------|\n| Node.js | 18.0+ | ES2022 features required |\n| npm | 9.0+ | For package management |\n| SQLite | 3.39+ | Only if using SQLite storage |\n| TypeScript | 5.0+ | For development work |\n\n资料来源：[CLAUDE.md:20]()\n\n## Installation\n\n### From npm (Recommended for Users)\n\n```bash\nnpm install @danielsimonjr/memory-mcp\n```\n\nThis installs the pre-built package with all dependencies. The core library `@danielsimonjr/memoryjs` is automatically included. 资料来源：[CLAUDE.md:24]()\n\n### From Source (Recommended for Development)\n\n```bash\n# Clone the repository\ngit clone https://github.com/danielsimonjr/memory-mcp.git\ncd memory-mcp\n\n# Install dependencies\nnpm install\n\n# Build the project\nnpm run build\n```\n\nThe `prepare` script runs automatically on `npm install`, triggering the build process. 资料来源：[CONTRIBUTING.md:1]()\n\n### Verify Installation\n\nAfter installation, verify the CLI is available:\n\n```bash\nmcp-server-memory --help\n```\n\n## Configuration\n\n### Environment Variables\n\nMemory MCP supports several environment variables for configuration:\n\n| Variable | Default | Description |\n|----------|---------|-------------|\n| `MEMORY_STORAGE_TYPE` | `jsonl` | Storage backend: `jsonl` or `sqlite` |\n| `MEMORY_DB_PATH` | `memory.db` | Path to SQLite database (when using SQLite) |\n| `MEMORY_JSONL_PATH` | `memory.jsonl` | Path to JSONL file (when using JSONL) |\n\n资料来源：[CLAUDE.md:14]()\n\n### Storage Options\n\nMemory MCP supports two storage backends:\n\n**JSONL Storage (Default)**\n\n- Data stored in human-readable JSONL files\n- Files: `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl`\n- Location: Project root directory 资料来源：[CLAUDE.md:14]()\n\n**SQLite Storage**\n\n- Set `MEMORY_STORAGE_TYPE=sqlite` to enable\n- Uses `better-sqlite3` for native performance\n- Single database file: `memory.db` 资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:1]()\n\n## Architecture Overview\n\n### System Layers\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (this repo)\"\n        A[\"src/index.ts\"] --> B[\"MCPServer.ts\"]\n        B --> C[\"toolDefs.ts\"]\n        C --> D[\"toolHandlers.ts\"]\n    end\n    \n    subgraph \"@danielsimonjr/memoryjs (npm dependency)\"\n        E[\"ManagerContext<br/>(lazy init)\"] --> F[\"EntityManager\"]\n        E --> G[\"RelationManager\"]\n        E --> H[\"SearchManager\"]\n        E --> I[\"IOManager\"]\n        E --> J[\"GraphStorage / SQLiteStorage\"]\n    end\n    \n    D --> E\n```\n\n资料来源：[CLAUDE.md:4-13]()\n\n### Entry Points\n\n| Entry Point | Purpose |\n|-------------|---------|\n| `dist/index.js` | Main build output |\n| `mcp-server-memory` | CLI binary (defined in package.json `bin`) |\n| `src/index.ts` | Source entry point |\n\n资料来源：[CLAUDE.md:17]()\n\n### Manager Accessors\n\nThe `ManagerContext` provides access to all core managers:\n\n| Accessor | Purpose |\n|----------|---------|\n| `ctx.entityManager` | Core CRUD for graph nodes |\n| `ctx.relationManager` | Directed edges between entities |\n| `ctx.observationManager` | Facts attached to entities |\n| `ctx.searchManager` | Basic, ranked, boolean, fuzzy search |\n| `ctx.semanticSearch` | Embedding similarity via OpenAI or local models |\n| `ctx.tagManager` | Tag management with importance scores |\n| `ctx.hierarchyManager` | Parent-child trees, subtree traversal |\n| `ctx.compressionManager` | Duplicate detection, merge, archive |\n| `ctx.graphTraversal` | BFS/DFS path finding, centrality |\n| `ctx.analyticsManager` | Graph stats and integrity validation |\n| `ctx.storage` | Direct GraphStorage access |\n\n资料来源：[CLAUDE.md:1]()\n\n## Tool Categories Overview\n\nMemory MCP exposes tools organized into 58 categories with 213 total tools:\n\n| Category | Count | Key Purpose |\n|----------|-------|-------------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities |\n| Search | 7 | Basic, ranked, boolean, fuzzy |\n| Semantic Search | 3 | Embedding similarity |\n| Intelligent Search | 3 | Hybrid multi-layer, query analysis |\n| Saved Searches | 5 | Store and re-execute queries |\n| Tag Management | 6 | Tags, bulk ops, importance scores |\n| Tag Aliases | 5 | Tag synonym/alias management |\n| Hierarchy | 9 | Parent-child trees, subtree traversal |\n| Graph Algorithms | 4 | BFS/DFS, centrality, connected components |\n| Analytics | 2 | Graph stats and integrity validation |\n| Compression | 4 | Dedup, merge, auto-compress, archive |\n| Import/Export | 2 | 7 export formats |\n| Decay & Salience | 3 | Time-based importance decay |\n\n资料来源：[CLAUDE.md:3]()\n\n## Quick Start with MCP Client\n\nOnce Memory MCP is installed and configured, integrate it with your MCP-compatible client:\n\n```json\n{\n  \"mcpServers\": {\n    \"memory\": {\n      \"command\": \"mcp-server-memory\",\n      \"args\": []\n    }\n  }\n}\n```\n\nFor SQLite storage:\n\n```json\n{\n  \"mcpServers\": {\n    \"memory\": {\n      \"command\": \"mcp-server-memory\",\n      \"env\": {\n        \"MEMORY_STORAGE_TYPE\": \"sqlite\"\n      }\n    }\n  }\n}\n```\n\n## Basic Operations\n\n### Creating Entities\n\n```typescript\n// Via tool handler (internal usage example)\nawait ctx.entityManager.createEntity({\n  name: \"project_alpha\",\n  entityType: \"project\",\n  observations: [\"Initial setup complete\"]\n});\n```\n\n### Searching\n\n```typescript\n// Ranked search (TF-IDF)\nconst results = await ctx.searchManager.rankedSearch(\"query text\");\n\n// Semantic search\nconst semanticResults = await ctx.semanticSearch.query({\n  text: \"query text\",\n  limit: 10\n});\n```\n\n### Context Compression\n\n```typescript\nconst compressed = ctx.contextWindowManager.compressForContext(\n  largeText,\n  { level: 'medium' }\n);\n```\n\n## Standalone Tools\n\nThe `tools/` directory contains standalone utilities:\n\n| Tool | Purpose |\n|------|---------|\n| `chunking-for-files` | Split/merge large files for context-limited editing |\n| `compress-for-context` | CTON compression for LLM context windows |\n| `create-dependency-graph` | Generate TypeScript project dependency graphs |\n| `migrate-from-jsonl-to-sqlite` | Convert between JSONL and SQLite formats |\n\n资料来源：[CLAUDE.md:18]()\n\nEach tool has its own `package.json` and can be built to Windows executables via `pkg`. 资料来源：[CLAUDE.md:18]()\n\n## Development Setup\n\n### Cloning and Initial Setup\n\n```bash\ngit clone https://github.com/danielsimonjr/memory-mcp.git\ncd memory-mcp\nnpm install\n```\n\n### Creating a Feature Branch\n\n```bash\ngit checkout -b feature/your-feature-name\n```\n\n### Development Workflow\n\n```bash\n# Make your changes\n\n# Commit your changes\ncd c:/mcp-servers/memory-mcp\ngit add .\ngit commit -m \"Description of your changes\"\n\n# Push and create PR\ngit push origin feature/your-feature-name\n```\n\n资料来源：[CONTRIBUTING.md:1-7]()\n\n### Code Style Guidelines\n\n- Follow TypeScript best practices\n- Use meaningful variable names\n- Add JSDoc comments for public methods\n- Keep functions focused and small\n- Maintain consistent indentation (2 spaces)\n\n资料来源：[CONTRIBUTING.md:12-16]()\n\n## Testing\n\n### Test Requirements\n\nWhen testing new features:\n\n- Test new features thoroughly\n- Include edge cases\n- Test backward compatibility\n- Verify export formats are valid\n- Test with empty graphs and large graphs\n\n资料来源：[CONTRIBUTING.md:18-22]()\n\n### Running Tests\n\n```bash\nnpm test\n```\n\nNote: Test runs create/modify `memory.jsonl`, `memory.db` files in the project root. These are in `.gitignore` and won't appear in `git status`. 资料来源：[CLAUDE.md:22]()\n\n## Building for Distribution\n\n### Package Structure\n\n- **Build output**: `dist/index.js`\n- **CLI binary**: `mcp-server-memory` (defined in package.json `bin`)\n- **Source entry**: `src/index.ts`\n- **TypeScript target**: ES2022 with Node16 module resolution\n\n资料来源：[CLAUDE.md:17,23]()\n\n### Publishing to npm\n\n```bash\n# Set authentication token\nnpm config set //registry.npmjs.org/:_authToken=$(cat c:\\mcp-servers\\npm_key.txt)\n\n# Publish with public access\nnpm publish --access public\n```\n\nThe `prepare` script auto-builds, so separate `npm run build` is not needed before publish. 资料来源：[CLAUDE.md:25]()\n\n### Verifying Package Contents\n\nBefore publishing:\n\n```bash\nnpm pack --dry-run 2>&1 | grep -E \"jsonl|\\.db|total files|package size\"\n```\n\n资料来源：[CLAUDE.md:25]()\n\n## Data Migration\n\n### JSONL to SQLite\n\n```bash\nnpx tsx tools/migrate-from-jsonl-to-sqlite.ts \\\n  --from memory.jsonl \\\n  --to memory.db \\\n  --verbose\n```\n\n### Command Line Arguments\n\n| Argument | Short | Description |\n|----------|-------|-------------|\n| `--from <path>` | `-f` | Source file path (JSONL or SQLite) |\n| `--to <path>` | `-t` | Target file path (JSONL or SQLite) |\n| `--verbose` | `-v` | Show detailed progress |\n| `--help` | `-h` | Show help message |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:1-30]()\n\n## Documentation\n\nWhen adding features:\n\n- Update README.md with new tools/functionality\n- Add entries to CHANGELOG.md\n- Update WORKFLOW.md if development process changes\n- Include usage examples\n\n资料来源：[CONTRIBUTING.md:28-32]()\n\n## Pull Request Process\n\n1. **Title**: Clear, descriptive summary\n2. **Description**: What changed, why it changed, how to test it\n3. **Tests**: Include test results\n4. **Documentation**: Update relevant docs\n5. **Backward Compatibility**: Confirm no breaking changes\n\n资料来源：[CONTRIBUTING.md:37-44]()\n\n## Error Handling\n\nError handling in dispatch catches exceptions from handlers and returns them as MCP-formatted error responses. Check the MCP response `isError` field when debugging. 资料来源：[CLAUDE.md:23]()\n\n## Next Steps\n\nAfter setting up your environment:\n\n1. Explore the [Tool Categories](#tool-categories-overview) to understand available operations\n2. Review the [Architecture Overview](#architecture-overview) for system design\n3. Set up your preferred [Storage Configuration](#configuration)\n4. Run the standalone [Dependency Graph Tool](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md) to visualize project structure\n5. Consult the project's issues for feature requests or bug reports\n\n---\n\n<a id='project-structure'></a>\n\n## Project Structure\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Development Guide](#development-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/index.ts)\n- [src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [tools/create-dependency-graph/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n</details>\n\n# Project Structure\n\n## Overview\n\nThe memory-mcp project implements a Model Context Protocol (MCP) server that provides a knowledge graph-based memory system for AI agents. The repository exposes over 200 tools across 58 categories, enabling persistent memory management with features including entity/relation CRUD, semantic search, bitemporal validity, and causal reasoning.\n\n## Repository Layout\n\n```\nmemory-mcp/\n├── src/                          # Main TypeScript source code\n│   ├── index.ts                  # Entry point and exports\n│   └── server/\n│       ├── MCPServer.ts          # Core MCP server implementation\n│       ├── toolDefinitions.ts    # Tool schemas (input/output specifications)\n│       └── toolHandlers.ts      # Tool implementation handlers\n├── tools/                        # Standalone utility tools\n│   ├── create-dependency-graph/ # TypeScript dependency analysis\n│   ├── compress-for-context/    # LLM context window compression\n│   ├── chunking-for-files/      # Large file splitting utilities\n│   └── migrate-from-jsonl-to-sqlite/ # Storage format migration\n├── dist/                         # Build output (npm published)\n├── docs/architecture/            # Generated documentation\n├── memory.jsonl                  # JSONL storage (project root)\n├── memory.db                     # SQLite storage (optional)\n├── package.json                  # npm package configuration\n└── CLAUDE.md                     # Developer documentation\n```\n\n## Core Architecture\n\n### Layered Architecture\n\nThe project follows a layered architecture where memory-mcp acts as an MCP interface wrapper around the core `@danielsimonjr/memoryjs` library.\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (this repo)\"\n        A[src/index.ts] --> B[src/server/MCPServer.ts]\n        B --> C[src/server/toolDefs.ts]\n        B --> D[src/server/toolHandlers.ts]\n    end\n    \n    subgraph \"@danielsimonjr/memoryjs (npm dependency)\"\n        E[ManagerContext] --> F[EntityManager]\n        E --> G[RelationManager]\n        E --> H[SearchManager]\n        E --> I[ObservationManager]\n        E --> J[TagManager]\n        E --> K[CompressionManager]\n        E --> L[GraphStorage]\n        E --> M[SQLiteStorage]\n    end\n    \n    D --> E\n    C --> E\n```\n\n资料来源：[CLAUDE.md:layered-architecture]()\n\n### Accessor Hierarchy\n\nThe `ManagerContext` provides lazy-initialized accessors for all subsystems:\n\n| Accessor | Purpose |\n|----------|---------|\n| `ctx.entityManager` | Graph node CRUD operations |\n| `ctx.relationManager` | Directed edge management |\n| `ctx.observationManager` | Facts attached to entities |\n| `ctx.searchManager` | Basic, ranked, boolean, fuzzy search |\n| `ctx.tagManager` | Tag CRUD and bulk operations |\n| `ctx.hierarchyManager` | Parent-child tree structures |\n| `ctx.analyticsManager` | Graph statistics and validation |\n| `ctx.compressionManager` | Duplicate detection and merging |\n| `ctx.archiveManager` | Historical data archival |\n| `ctx.ioManager` | Import/export operations |\n| `ctx.graphTraversal` | BFS/DFS path finding |\n| `ctx.semanticSearch` | Embedding similarity search |\n| `ctx.rankedSearch` | TF-IDF ranking |\n| `ctx.storage` | Direct GraphStorage access |\n\n资料来源：[CLAUDE.md:accessors]()\n\n## Source Code Organization\n\n### Entry Point (`src/index.ts`)\n\nThe main entry point handles:\n- Package exports and re-exports\n- Backward compatibility aliases (exports `ManagerContext` as `KnowledgeGraphManager`)\n- Core type re-exports\n\n### MCP Server (`src/server/MCPServer.ts`)\n\nThe `MCPServer` class is responsible for:\n- Initializing the ManagerContext with storage configuration\n- Tool dispatch and request handling\n- Error formatting and response generation\n\nKey aspects:\n- **Error handling**: `handleToolCall` catches exceptions from handlers and returns them as MCP-formatted error responses (checks `isError` field in responses)\n- **Storage initialization**: Supports both JSONL and SQLite storage backends\n- **Tool registration**: Dynamically registers tools from definitions\n\n资料来源：[CLAUDE.md:entry-points](), [CLAUDE.md:error-handling]()\n\n### Tool Definitions (`src/server/toolDefinitions.ts`)\n\nThe tool definitions file contains JSON Schema specifications for all 213 tools. Tools are organized into categories:\n\n| Category | Count | Description |\n|----------|-------|-------------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities |\n| Search | 7 | Basic, ranked, boolean, fuzzy search |\n| Intelligent Search | 3 | Hybrid multi-layer search |\n| Semantic Search | 3 | Embedding-based similarity |\n| Saved Searches | 5 | Stored query execution |\n| Tag Management | 6 | Tag CRUD and bulk operations |\n| Tag Aliases | 5 | Tag synonym management |\n| Hierarchy | 9 | Tree structures and traversal |\n| Graph Algorithms | 4 | Path finding, centrality |\n| Analytics | 2 | Stats and validation |\n| Compression | 4 | Duplicate detection, merge |\n| Import/Export | 2+ | Multiple format support |\n\n资料来源：[CLAUDE.md:tool-categories](), [src/server/toolDefinitions.ts]()\n\n### Tool Handlers (`src/server/toolHandlers.ts`)\n\nTool handlers implement the actual logic for each tool. Each handler:\n1. Validates input arguments using Zod schemas\n2. Accesses appropriate ManagerContext accessors\n3. Returns formatted responses\n\nExample handler pattern:\n```typescript\ntool_name: async (ctx, args) => {\n  // Input validation\n  const param = validateWithSchema(args.param, z.string(), 'Invalid param');\n  \n  // Business logic via ManagerContext\n  const result = await getSomeManager(ctx).someOperation(param);\n  \n  // Response formatting\n  return formatToolResponse(result);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts]()\n\n## Standalone Tools\n\nThe `tools/` directory contains independent utilities, each with its own `package.json` and compilable to Windows executables via `pkg`:\n\n### create-dependency-graph\n\nAnalyzes TypeScript source files and generates dependency documentation.\n\n| Output | Description |\n|--------|-------------|\n| `docs/architecture/DEPENDENCY_GRAPH.md` | Human-readable Markdown documentation |\n| `docs/architecture/dependency-graph.json` | Machine-readable JSON structure |\n\nFeatures:\n- Scans all TypeScript files in `src/`\n- Parses imports and exports\n- Categorizes files into logical modules\n- Detects circular dependencies\n- Generates statistics\n\nUsage:\n```bash\nnpm run docs:deps\n# or\nnpx tsx tools/create-dependency-graph.ts\n```\n\n资料来源：[tools/create-dependency-graph/README.md]()\n\n### compress-for-context\n\nCTON (Context Token Optimization Notation) compression for reducing LLM context window usage.\n\n| Option | Description |\n|--------|-------------|\n| `-o, --output <file>` | Output file path |\n| `-f, --format <fmt>` | Force format: json, yaml, markdown, csv, etc. |\n| `-l, --level <lvl>` | Compression level: light, medium, aggressive |\n| `-b, --batch` | Batch mode for multiple files |\n| `-d, --decompress` | Restore compressed file |\n\n### chunking-for-files\n\nSplits large files into editable sections for context-limited editing.\n\nCommands:\n- `chunker split <file>` - Split file into chunks\n- `chunker merge <manifest.json>` - Merge chunks back\n- `chunker status <manifest.json>` - Show chunk status\n\n### migrate-from-jsonl-to-sqlite\n\nConverts between JSONL and SQLite storage formats using `better-sqlite3`.\n\n```bash\nmigrate-from-jsonl-to-sqlite --from <source> --to <target> [--verbose]\n```\n\n## Storage System\n\nData files reside in the **project root** (not `dist/`):\n\n| Storage Type | File | Environment Variable |\n|--------------|------|---------------------|\n| JSONL (default) | `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl` | `MEMORY_STORAGE_TYPE=jsonl` |\n| SQLite | `memory.db` | `MEMORY_STORAGE_TYPE=sqlite` |\n\nThe `memory.db` and `*.jsonl` files are gitignored—they are created/modified at runtime but not tracked by version control.\n\n资料来源：[CLAUDE.md:storage]()\n\n## Build and Publication\n\n### Build Output\n\n| Artifact | Description |\n|----------|-------------|\n| `dist/index.js` | Main build output |\n| `mcp-server-memory` | CLI binary (package.json `bin` field) |\n\nThe TypeScript target is ES2022 with Node16 module resolution. The `prepare` script auto-runs `npm run build` on `npm install`, ensuring `dist/` is always rebuilt.\n\n### Publishing to npm\n\n```bash\n# Token with \"bypass 2FA\" required\nnpm config set //registry.npmjs.org/:_authToken=$(cat ~/.npm_token)\nnpm publish --access public\n```\n\nThe `prepare` script handles builds automatically, so separate `npm run build` is unnecessary before publishing.\n\n资料来源：[CLAUDE.md:publishing-to-npm]()\n\n## Development Guidelines\n\n### Code Style\n\n| Guideline | Standard |\n|-----------|----------|\n| Language | TypeScript best practices |\n| Indentation | 2 spaces |\n| Documentation | JSDoc comments for public methods |\n| Function design | Small, focused functions |\n| Naming | Meaningful variable names |\n\n### Testing Requirements\n\nWhen adding features:\n- Test with empty graphs and large graphs\n- Include edge cases\n- Verify backward compatibility\n- Ensure export formats are valid\n\n### Documentation Checklist\n\n| File | When to Update |\n|------|----------------|\n| `README.md` | New tools/functionality |\n| `CHANGELOG.md` | Version changes |\n| `WORKFLOW.md` | Development process changes |\n\n## File Naming Conventions\n\n| Pattern | Example | Purpose |\n|---------|---------|---------|\n| `*.ts` | `MCPServer.ts`, `toolHandlers.ts` | TypeScript source files |\n| `*.md` | `DEPENDENCY_GRAPH.md` | Generated documentation |\n| `*.json` | `dependency-graph.json` | Machine-readable data |\n| `*.compact` | output.compact | Compressed files |\n\n## Summary\n\nThe memory-mcp project is structured as a thin MCP wrapper around the `@danielsimonjr/memoryjs` library. The core source in `src/` contains only 5 TypeScript files, while the `tools/` directory provides standalone utilities for dependency analysis, context compression, file chunking, and storage migration. The architecture prioritizes backward compatibility, lazy initialization of managers, and clean separation between tool definitions, handlers, and the underlying knowledge graph implementation.\n\n---\n\n<a id='architecture-overview'></a>\n\n## Architecture Overview\n\n### 相关页面\n\n相关主题：[Storage Backends](#storage-backends), [Entity-Relation-Observation Model](#entity-model)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/index.ts)\n- [src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)\n- [src/server/toolDefs.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefs.ts)\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [docs/architecture/ARCHITECTURE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/docs/architecture/ARCHITECTURE.md)\n</details>\n\n# Architecture Overview\n\nThe memory-mcp project implements a Model Context Protocol (MCP) server that provides a persistent knowledge graph for AI agents. The system enables structured memory management with 213 tools across 58 categories, supporting entity management, relationships, observations, search, tagging, hierarchy traversal, analytics, and compression capabilities.\n\n## High-Level Architecture\n\nThe project follows a layered architecture that separates concerns between the MCP protocol interface, business logic, and storage implementation. The core knowledge graph functionality is delegated to the `@danielsimonjr/memoryjs` library (currently v2.1.0+), while memory-mcp serves as the protocol adapter and tool layer.\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (This Repository)\"\n        A[\"src/index.ts<br/>Entry Point\"] --> B[\"MCPServer.ts<br/>Protocol Handler\"]\n        B --> C[\"toolDefs.ts<br/>Tool Definitions\"]\n        B --> D[\"toolHandlers.ts<br/>Tool Handlers\"]\n        C --> D\n    end\n    \n    subgraph \"@danielsimonjr/memoryjs (npm Dependency)\"\n        E[\"ManagerContext<br/>Lazy Initialization\"]\n        E --> F[\"EntityManager\"]\n        E --> G[\"RelationManager\"]\n        E --> H[\"ObservationManager\"]\n        E --> I[\"SearchManager\"]\n        E --> J[\"TagManager\"]\n        E --> K[\"HierarchyManager\"]\n        E --> L[\"AnalyticsManager\"]\n        E --> M[\"CompressionManager\"]\n        E --> N[\"IOManager\"]\n    end\n    \n    D --> E\n    \n    O[\"GraphStorage/SQLiteStorage\"] --> E\n    \n    style A fill:#e1f5fe\n    style E fill:#fff3e0\n```\n\n资料来源：[CLAUDE.md:Layered Architecture]()\n\n## Core Components\n\n### Entry Point (src/index.ts)\n\nThe `src/index.ts` file serves as the primary entry point for the application. It exports the `ManagerContext` under an alias `KnowledgeGraphManager` for backward compatibility, along with all core types needed by consumers of the library.\n\nThe exports enable external consumers to:\n- Import the main context manager class\n- Access type definitions for entities, relations, observations, and search operations\n- Use the manager without knowledge of internal implementation details\n\n资料来源：[src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/index.ts)\n\n### MCPServer (src/server/MCPServer.ts)\n\nThe `MCPServer` class implements the Model Context Protocol server interface. It handles:\n\n- Protocol message parsing and routing\n- Tool registration and discovery\n- Request/response lifecycle management\n- Error handling and validation\n\nThe server initializes lazy-loaded managers through `ManagerContext`, ensuring resources are only allocated when actually needed.\n\n资料来源：[src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)\n\n### ManagerContext (memoryjs)\n\nThe `ManagerContext` provides access to all core managers through a unified interface. It implements lazy initialization to optimize startup time and resource usage.\n\n| Manager | Purpose |\n|---------|---------|\n| `entityManager` | Core CRUD operations for graph nodes |\n| `relationManager` | Directed edges between entities |\n| `observationManager` | Facts attached to entities with normalization |\n| `searchManager` | Basic, ranked, boolean, fuzzy, and auto-select search |\n| `tagManager` | Tag operations, bulk operations, importance scores |\n| `hierarchyManager` | Parent-child trees, subtree traversal |\n| `analyticsManager` | Graph statistics and integrity validation |\n| `compressionManager` | Duplicate detection, merge, auto-compress, archive |\n| `archiveManager` | Long-term storage management |\n| `ioManager` | Import/export operations |\n| `graphTraversal` | Graph algorithm utilities |\n| `semanticSearch` | Embedding-based similarity search |\n| `rankedSearch` | TF-IDF weighted search |\n| `storage` | Direct GraphStorage access for advanced use cases |\n\n资料来源：[CLAUDE.md:Accessors]()\n\n## Tool System Architecture\n\n### Tool Definitions (src/server/toolDefs.ts)\n\nTool definitions describe the interface contract for each capability. Each definition includes:\n\n- **name**: Unique identifier for the tool\n- **description**: Human-readable explanation of functionality\n- **inputSchema**: JSON Schema describing required and optional parameters\n\n### Tool Handlers (src/server/toolHandlers.ts)\n\nTool handlers implement the business logic for each tool. They receive the `ManagerContext` and validated arguments, then execute the appropriate manager operations.\n\nExample handler pattern:\n```typescript\ncreate_entity: async (ctx, args) => {\n  const name = validateWithSchema(args.name, z.string().min(1), 'Invalid name');\n  const entity = await ctx.entityManager.createEntity({ name, ... });\n  return formatToolResponse(entity);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:tool pattern]()\n\n### Tool Categories\n\nThe system organizes its 213 tools into 58 categories:\n\n| Category | Count | Key Purpose |\n|----------|-------|-------------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities, with normalization |\n| Search | 7 | Basic, ranked, boolean, fuzzy, auto-select |\n| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |\n| Semantic Search | 3 | Embedding similarity via OpenAI or local models |\n| Saved Searches | 5 | Store and re-execute frequent queries |\n| Tag Management | 6 | Tags, bulk ops, importance scores |\n| Tag Aliases | 5 | Tag synonym/alias management |\n| Hierarchy | 9 | Parent-child trees, subtree traversal |\n| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |\n| Analytics | 2 | Graph stats and integrity validation |\n| Compression | 4 | Duplicate detection, merge, auto-compress, archive |\n| Import/Export | 2 | 7 export formats |\n\n资料来源：[CLAUDE.md:Tool Categories]()\n\n## Storage Layer\n\nThe storage layer supports two backends controlled by the `MEMORY_STORAGE_TYPE` environment variable.\n\n### JSONL Storage (Default)\n\nData files are stored in the project root directory:\n\n| File | Purpose |\n|------|---------|\n| `memory.jsonl` | Main knowledge graph data |\n| `memory-saved-searches.jsonl` | Saved search definitions |\n| `memory-tag-aliases.jsonl` | Tag synonym mappings |\n\n### SQLite Storage\n\nWhen `MEMORY_STORAGE_TYPE=sqlite`, the system uses:\n- `memory.db` - Single-file relational database\n\nThe SQLite backend provides better performance for large datasets and supports advanced query capabilities through the storage layer.\n\n资料来源：[CLAUDE.md:Storage]()\n\n## Entry Points\n\n| Entry Point | Description |\n|-------------|-------------|\n| `dist/index.js` | Built output for npm distribution |\n| `mcp-server-memory` | CLI binary defined in package.json `bin` field |\n| `src/index.ts` | Source entry point |\n\n资料来源：[CLAUDE.md:Entry Points]()\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant ToolHandler\n    participant ManagerContext\n    participant Manager\n    participant Storage\n    \n    Client->>MCPServer: MCP Request\n    MCPServer->>ToolHandler: Route to handler\n    ToolHandler->>ManagerContext: Access manager\n    ManagerContext->>Manager: Lazy initialization\n    Manager->>Storage: Read/Write operations\n    Storage-->>Manager: Data\n    Manager-->>ManagerContext: Result\n    ManagerContext-->>ToolHandler: Structured response\n    ToolHandler-->>MCPServer: Formatted response\n    MCPServer-->>Client: MCP Response\n```\n\n## Standalone Tools\n\nThe `tools/` directory contains standalone utilities with their own `package.json` files, buildable to Windows executables via pkg:\n\n| Tool | Purpose |\n|------|---------|\n| `chunking-for-files` | Split/merge large files for context-limited editing |\n| `compress-for-context` | CTON compression for LLM context windows |\n| `create-dependency-graph` | Generate TypeScript project dependency graphs |\n| `migrate-from-jsonl-to-sqlite` | Convert between JSONL and SQLite formats |\n\n资料来源：[CLAUDE.md:Standalone Tools]()\n\n## Version History\n\nThe architecture has evolved through multiple phases:\n\n| Phase | Version | Key Changes |\n|-------|---------|-------------|\n| Phase 13 | Initial | 5 TypeScript source files, memoryjs v2.1.0+ |\n| Phase 15 | v12.2.0 | 23 tools for memoryjs v1.14+ features (bitemporal, OCC, RBAC) |\n| Phase 16 | v12.3.0 | 53 tools for memoryjs v2.1.0 (exclusions, ADR, context, heuristics) |\n\n资料来源：[CLAUDE.md:Phase History]()\n\n## npm Package Information\n\n- **Package**: `@danielsimonjr/memory-mcp`\n- **Core Dependency**: `@danielsimonjr/memoryjs` (version specified in package.json)\n\n资料来源：[CLAUDE.md:npm Information]()\n\n---\n\n<a id='storage-backends'></a>\n\n## Storage Backends\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Entity-Relation-Observation Model](#entity-model)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts)\n- [tools/migrate-from-jsonl-to-sqlite/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/migrate-from-jsonl-to-sqlite/README.md)\n- [tools/migrate-from-jsonl-to-sqlite/package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/migrate-from-jsonl-to-sqlite/package.json)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [SECURITY.md](https://github.com/danielsimonjr/memory-mcp/blob/main/SECURITY.md)\n</details>\n\n# Storage Backends\n\nThe Memory MCP server implements a dual-storage backend architecture that supports both **JSONL (JSON Lines)** and **SQLite** formats for persisting knowledge graph data. This flexible design allows users to choose the most appropriate storage mechanism based on dataset size, performance requirements, and debugging preferences.\n\n## Architecture Overview\n\nThe storage layer handles all persistence operations for entities, relations, and associated metadata within the knowledge graph. The architecture separates the storage format from the core application logic, enabling seamless migration between formats without losing data integrity.\n\n```mermaid\ngraph TD\n    A[Memory MCP Server] --> B[Storage Abstraction Layer]\n    B --> C[JSONL Backend]\n    B --> D[SQLite Backend]\n    C --> E[memory.jsonl]\n    D --> F[memory.db]\n    D --> G[FTS5 Index]\n    \n    style A fill:#e1f5fe\n    style B fill:#fff3e0\n    style E fill:#f3e5f5\n    style F fill:#e8f5e9\n    style G fill:#e8f5e9\n```\n\n## Data Models\n\n### KnowledgeGraph Structure\n\nThe knowledge graph comprises two primary collections that together represent the complete state of the memory system.\n\n| Collection | Type | Description |\n|------------|------|-------------|\n| `entities` | Entity[] | Individual memory items with observations and metadata |\n| `relations` | Relation[] | Connections between entities defining semantic relationships |\n\n### Entity Model\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `name` | string | Yes | Unique identifier for the entity |\n| `entityType` | string | Yes | Classification category (e.g., \"person\", \"concept\", \"task\") |\n| `observations` | string[] | Yes | Array of recorded facts or data points |\n| `createdAt` | string | No | ISO timestamp of entity creation |\n| `lastModified` | string | No | ISO timestamp of last modification |\n| `tags` | string[] | No | Optional categorization labels |\n| `importance` | number | No | Priority score (null if unspecified) |\n| `parentId` | string | No | Hierarchical parent reference |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:50-58]()\n\n### Relation Model\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| `from` | string | Yes | Source entity name or ID |\n| `to` | string | Yes | Target entity name or ID |\n| `relationType` | string | Yes | Semantic relationship type (e.g., \"related_to\", \"part_of\") |\n| `createdAt` | string | No | ISO timestamp of relation creation |\n| `lastModified` | string | No | ISO timestamp of last modification |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:60-66]()\n\n## Supported Storage Formats\n\n### JSONL Format\n\nThe **JSONL (JSON Lines)** backend stores each entity and relation as a separate JSON object on its own line within plain text files. This format provides human-readable data and simple version control compatibility.\n\n**File Locations (Project Root):**\n\n| File | Purpose |\n|------|---------|\n| `memory.jsonl` | Primary knowledge graph storage |\n| `memory-saved-searches.jsonl` | Stored search configurations |\n| `memory-tag-aliases.jsonl` | Tag normalization mappings |\n\n资料来源：[CLAUDE.md:2-9]()\n\n**Characteristics:**\n\n- Default storage format when no configuration is provided\n- Each line contains a valid JSON object\n- Easy to inspect, edit, and debug\n- Direct compatibility with text editors and version control systems\n- Recommended for datasets under 1,000 entities\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/README.md:45-55]()\n\n### SQLite Format\n\nThe **SQLite** backend provides a relational database optimized for larger datasets and concurrent access patterns. It offers ACID transaction support and full-text search capabilities through FTS5.\n\n**File Location (Project Root):**\n\n| File | Purpose |\n|------|---------|\n| `memory.db` | Primary SQLite database |\n\n资料来源：[CLAUDE.md:6]()\n\n**SQLite Backend Features:**\n\n| Feature | Description |\n|---------|-------------|\n| FTS5 Index | Automatic full-text search indexing for fast entity lookups |\n| WAL Mode | Write-Ahead Logging for improved concurrent read/write performance |\n| Atomic Transactions | Ensures data integrity during write operations |\n| Native Performance | Uses better-sqlite3 for 3-10x faster operations compared to WASM alternatives |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:14-15]()\n\n## Environment Configuration\n\nStorage behavior is controlled through environment variables that must be set before server initialization.\n\n### Configuration Variables\n\n| Variable | Values | Default | Description |\n|----------|--------|---------|-------------|\n| `MEMORY_STORAGE_TYPE` | `jsonl`, `sqlite` | `jsonl` | Determines which storage backend to use |\n| `MEMORY_FILE_PATH` | Valid file path | `memory.jsonl` (cwd) | Absolute or relative path to primary storage file |\n\n资料来源：[CLAUDE.md:24-28]()\n\n### Configuration Examples\n\n**JSONL (Default):**\n```bash\n# No environment variables needed - defaults to JSONL\n```\n\n**SQLite:**\n```json\n{\n  \"mcpServers\": {\n    \"memory\": {\n      \"command\": \"node\",\n      \"args\": [\"/path/to/memory-mcp/src/memory/dist/index.js\"],\n      \"env\": {\n        \"MEMORY_STORAGE_TYPE\": \"sqlite\",\n        \"MEMORY_FILE_PATH\": \"/path/to/memory.db\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/README.md:70-79]()\n\n## Migration Between Formats\n\nThe `migrate-from-jsonl-to-sqlite` tool provides bidirectional conversion between JSONL and SQLite storage formats. This enables users to start with simple JSONL storage and migrate to SQLite as their dataset grows.\n\n### Supported File Extensions\n\n| Format | Extensions | Detection Logic |\n|--------|------------|-----------------|\n| JSONL | `.jsonl`, `.json` | Extension-based detection |\n| SQLite | `.db`, `.sqlite`, `.sqlite3` | Extension-based detection |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:97-103]()\n\n### Migration Tool Usage\n\n```bash\n# JSONL to SQLite migration\nmigrate-from-jsonl-to-sqlite --from memory.jsonl --to memory.db\n\n# SQLite to JSONL migration\nmigrate-from-jsonl-to-sqlite --from memory.db --to memory.jsonl\n\n# Using positional arguments\nmigrate-from-jsonl-to-sqlite memory.jsonl memory.db\n\n# Verbose output for troubleshooting\nmigrate-from-jsonl-to-sqlite -f memory.jsonl -t memory.db -v\n```\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts:1-30]()\n\n### Migration Options\n\n| Argument | Short | Description |\n|----------|-------|-------------|\n| `--from` | `-f` | Source file path (JSONL or SQLite) |\n| `--to` | `-t` | Target file path (JSONL or SQLite) |\n| `--verbose` | `-v` | Show detailed progress information |\n| `--help` | `-h` | Display help message |\n\n### Migration Workflow\n\n```mermaid\ngraph TD\n    A[Start Migration] --> B{Detect Source Format}\n    B -->|JSONL| C[loadFromJsonl]\n    B -->|SQLite| D[loadFromSqlite]\n    C --> E[Parse Knowledge Graph]\n    D --> E\n    E --> F{Validate Timestamps}\n    F -->|Missing createdAt| G[Set to migration time + warn]\n    F -->|Missing lastModified| H[Set to migration time + warn]\n    G --> I\n    H --> I[Write to Target Format]\n    I -->|JSONL| J[writeToJsonl]\n    I -->|SQLite| K[Initialize FTS5 + WAL]\n    J --> L[Migration Complete]\n    K --> L\n```\n\n### Migration Notes and Limitations\n\n| Aspect | Behavior |\n|--------|----------|\n| **Target Creation** | Target file is created if it doesn't exist |\n| **Existing Targets** | Target file will be overwritten if it exists |\n| **Data Integrity** | Atomic transactions ensure no data loss during migration |\n| **Timestamp Handling** | Missing `createdAt` or `lastModified` fields are populated with migration timestamp and a warning is displayed |\n| **Saved Searches** | NOT migrated (stored in separate `memory-saved-searches.jsonl` file) |\n| **Tag Aliases** | NOT migrated (stored in separate `memory-tag-aliases.jsonl` file) |\n| **Large Datasets** | Recommended for graphs with 10,000+ entities |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/README.md:20-25]()\n\n## Format Selection Guide\n\nChoose the appropriate storage backend based on your specific use case and dataset characteristics.\n\n| Criteria | JSONL | SQLite |\n|----------|-------|--------|\n| Dataset Size | < 1,000 entities | 10,000+ entities |\n| Transaction Needs | Simple append operations | ACID transactions required |\n| Data Inspection | Human-readable preferred | Structured queries needed |\n| Concurrent Access | Single process | Multiple readers/writers |\n| Debugging | Direct file inspection | Requires SQLite tools |\n| Performance | Sufficient for small datasets | Optimized for large graphs |\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/README.md:45-55]()\n\n## Security Considerations\n\nWhen configuring storage backends, consider the following security implications documented in the project's security guidelines.\n\n### File Permissions\n\nThe storage files contain all knowledge graph data and should be protected with appropriate file system permissions:\n\n```json\n{\n  \"mcpServers\": {\n    \"memory\": {\n      \"command\": \"node\",\n      \"args\": [\"/path/to/memory-mcp/src/memory/dist/index.js\"],\n      \"env\": {\n        \"MEMORY_FILE_PATH\": \"/secure/path/memory.jsonl\"\n      }\n    }\n  }\n}\n```\n\n资料来源：[SECURITY.md:8-18]()\n\n### Data Sensitivity\n\n| Format | Export Considerations |\n|--------|----------------------|\n| JSONL/JSON | Full entity data visible in plain text |\n| SQLite | Database contents require database tools to inspect |\n| CSV/GraphML Exports | Full data included; filter parameters can limit exported data |\n\n资料来源：[SECURITY.md:19-26]()\n\n## Tool Dependencies\n\nThe SQLite backend and migration tool rely on the `better-sqlite3` package for native performance:\n\n```json\n{\n  \"name\": \"migrate-from-jsonl-to-sqlite\",\n  \"version\": \"1.1.0\",\n  \"dependencies\": {\n    \"better-sqlite3\": \"^11.7.0\"\n  },\n  \"devDependencies\": {\n    \"@types/better-sqlite3\": \"^7.6.12\"\n  }\n}\n```\n\n资料来源：[tools/migrate-from-jsonl-to-sqlite/package.json:1-12]()\n\nThe package is configured with `yao-pkg/pkg` for building standalone executables targeting `node22-win-x64`.\n\n## Related Documentation\n\n| Document | Description |\n|----------|-------------|\n| [CLAUDE.md](CLAUDE.md) | Project architecture and development guidelines |\n| [tools/migrate-from-jsonl-to-sqlite/README.md](tools/migrate-from-jsonl-to-sqlite/README.md) | Detailed migration tool documentation |\n| [SECURITY.md](SECURITY.md) | Security considerations for data storage |\n\n---\n\n<a id='entity-model'></a>\n\n## Entity-Relation-Observation Model\n\n### 相关页面\n\n相关主题：[Search Capabilities](#search-capabilities), [Temporal and Advanced Features](#temporal-features)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [src/index.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/index.ts)\n- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n</details>\n\n# Entity-Relation-Observation Model\n\nThe Entity-Relation-Observation (ERO) Model is the core data architecture powering the Enhanced Memory MCP server. It implements a temporal knowledge graph where **entities** represent nodes in a graph, **relations** represent directed edges between entities, and **observations** attach factual metadata to entities.\n\n## Architecture Overview\n\nThe ERO Model is built on the layered architecture of memoryjs (v^2.1.0), where the `ManagerContext` provides lazy-initialized access to specialized managers:\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (MCP Server Layer)\"\n        MCPS[MCPServer]\n        TH[ToolHandlers]\n        TD[ToolDefinitions]\n    end\n    \n    subgraph \"memoryjs (Core Library Layer)\"\n        MC[ManagerContext]\n        EM[EntityManager]\n        RM[RelationManager]\n        OM[ObservationManager]\n        SM[SearchManager]\n    end\n    \n    MCPS --> TH\n    TH --> TD\n    TH --> MC\n    MC --> EM\n    MC --> RM\n    MC --> OM\n    MC --> SM\n    \n    subgraph \"Storage Layer\"\n        GS[GraphStorage]\n        SS[SQLiteStorage]\n        JL[JSONLStorage]\n    end\n    \n    MC --> GS\n    GS --> SS\n    GS --> JL\n```\n\n资料来源：[CLAUDE.md:layered-architecture](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Core Components\n\n### Entity Manager\n\nEntities are the primary nodes in the knowledge graph. The EntityManager provides core CRUD operations:\n\n| Operation | Tool Name | Description |\n|-----------|-----------|-------------|\n| Create | `create_entity` | Add a new entity to the graph |\n| Read | `get_entity` | Retrieve entity by name or ref |\n| Update | `update_entity` | Modify entity properties |\n| Delete | `delete_entities` | Remove entity from graph |\n| List | `list_entities` | Get entities with optional filters |\n\n资料来源：[toolDefinitions.ts:entity-tools](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n\n**Entity Properties:**\n- `name` (required): Unique identifier\n- `memoryType`: Classification type (default: `semantic`)\n- `confidence`: Trust score (0.0 - 1.0, default: 0.8)\n- `tags`: Array of associated tags\n- `observations`: Attached factual metadata\n- `createdAt` / `updatedAt`: Temporal timestamps\n- `accessCount`: Usage tracking\n- `confirmationCount`: Verification count\n\n### Relation Manager\n\nRelations are directed edges connecting entities with typed relationships. The RelationManager handles:\n\n```mermaid\ngraph LR\n    E1[Entity A] -->|\"created_by\"| R[Relation]\n    R -->|\"part_of\"| E2[Entity B]\n    E1 -->|\"depends_on\"| R2[Relation]\n    R2 -->|\"implements\"| E3[Entity C]\n```\n\n| Operation | Tool Name | Description |\n|-----------|-----------|-------------|\n| Create | `create_relations` | Batch create directed edges |\n| Delete | `delete_relations` | Remove relations by criteria |\n| Invalidate | `invalidate_relation` | Bitemporal validity - end a relation |\n| Chain | `get_entity_chain` | Traverse relation paths between entities |\n\n资料来源：[toolHandlers.ts:relation-handlers](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n**Relation Schema:**\n```typescript\ninterface Relation {\n  from: string;      // Source entity name/ref\n  relationType: string; // Relationship type (e.g., \"depends_on\", \"part_of\")\n  to: string;        // Target entity name/ref\n  ended?: string;    // Bitemporal end timestamp (undefined = active)\n}\n```\n\n### Observation Manager\n\nObservations are factual statements attached to entities, providing evidence and context:\n\n| Property | Description |\n|----------|-------------|\n| `content` | The factual statement |\n| `normalized` | Canonical form for comparison |\n| `source` | Origin of the observation |\n| `confirmed` | Verification status |\n| `attachedAt` | Timestamp when attached |\n\n资料来源：[CLAUDE.md:observation](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n**Key Features:**\n- Content normalization for deduplication\n- Source tracking for provenance\n- Confirmation counting for consensus-based truth\n\n## Tool Categories\n\nThe ERO Model exposes 213 tools across 58 categories:\n\n| Category | Count | Purpose |\n|----------|-------|---------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities |\n| Search | 7 | Query graph data |\n| Intelligent Search | 3 | Advanced query processing |\n| Semantic Search | 3 | Embedding-based retrieval |\n| Tag Management | 6 | Entity categorization |\n| Hierarchy | 9 | Parent-child tree structures |\n| Graph Algorithms | 4 | Path finding, centrality |\n| Analytics | 2 | Graph statistics |\n| Compression | 4 | Deduplication, archiving |\n\n资料来源：[CLAUDE.md:tool-categories](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPS as MCPServer\n    participant TH as ToolHandlers\n    participant MC as ManagerContext\n    participant Storage as GraphStorage\n\n    Client->>MCPS: create_entity({ name, tags, observations })\n    MCPS->>TH: Route to create_entity handler\n    TH->>MC: ctx.entityManager.createEntity()\n    MC->>Storage: saveGraph(graph)\n    Storage-->>MC: Success\n    MC-->>TH: Entity result\n    TH-->>MCPS: Formatted response\n    MCPS-->>Client: { content: [...] }\n```\n\n## Storage Layer\n\nThe ERO Model supports two storage backends:\n\n### JSONL Storage (Default)\n- **File**: `memory.jsonl` (project root)\n- **Format**: One JSON object per line\n- **Additional files**: `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl`\n\n### SQLite Storage\n- **File**: `memory.db` (project root)\n- **Enable**: Set `MEMORY_STORAGE_TYPE=sqlite`\n- **Benefits**: Queryable, relational operations\n\n资料来源：[CLAUDE.md:storage](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Bitemporal Validity\n\nRelations support bitemporal validity for tracking historical state:\n\n```mermaid\ngraph TD\n    A[Entity A] -->|created: 2024-01-01| R1[Active Relation]\n    A -->|ended: 2024-02-15| R2[Historical Relation]\n    \n    subgraph \"Timeline\"\n        T1[Jan 2024]\n        T2[Feb 2024]\n        T3[Current]\n    end\n    \n    R1 --> T3\n    R2 --> T2\n```\n\nThe `invalidate_relation` tool terminates a relation at a specified timestamp:\n```typescript\ninvalidate_relation(from, relationType, to, ended?)\n```\n\n资料来源：[toolHandlers.ts:invalidate-relation](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n## Hierarchy Integration\n\nEntities can form hierarchical trees through the HierarchyManager:\n\n| Tool | Purpose |\n|------|---------|\n| `set_entity_parent` | Assign parent entity |\n| `get_children` | Direct descendants |\n| `get_parent` | Direct ancestor |\n| `get_ancestors` | Full ancestry path |\n| `get_descendants` | All descendants (recursive) |\n| `get_subtree` | Subtree structure |\n\n资料来源：[toolHandlers.ts:hierarchy-handlers](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n## Search Capabilities\n\nThe ERO Model provides layered search:\n\n```mermaid\ngraph TD\n    Q[Query] --> BS[Basic Search]\n    Q --> RS[Ranked Search]\n    Q --> FS[Fuzzy Search]\n    Q --> SS[Semantic Search]\n    \n    BS -->|TF-IDF| R1[Results]\n    RS -->|Ranked| R2[Results]\n    FS -->|Edit Distance| R3[Results]\n    SS -->|Embeddings| R4[Results]\n    \n    subgraph \"Intelligent Search\"\n        QA[Query Analysis]\n        QR[Query Reflection]\n    end\n    \n    Q --> QA\n    QA --> QR\n    QR --> R5[Intelligent Results]\n```\n\n**Search Types:**\n1. **Basic**: Exact and substring matching\n2. **Ranked (TF-IDF)**: Term frequency-inverse document frequency\n3. **Fuzzy**: Edit distance tolerance\n4. **Semantic**: Embedding similarity (OpenAI or local models)\n5. **Intelligent**: Multi-layer hybrid with query analysis\n\n资料来源：[CLAUDE.md:search](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Environment Configuration\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `MEMORY_FILE_PATH` | Storage file path | `memory.jsonl` |\n| `MEMORY_STORAGE_TYPE` | Backend type | `jsonl` |\n| `MEMORY_EMBEDDING_PROVIDER` | Embedding service | `none` |\n| `MEMORY_OPENAI_API_KEY` | API key for OpenAI | — |\n| `MEMORY_EMBEDDING_MODEL` | Model name | `text-embedding-3-small` |\n| `MEMORY_AUTO_INDEX_EMBEDDINGS` | Auto-index on create | `false` |\n\n资料来源：[CLAUDE.md:env-vars](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## API Entry Points\n\n| Endpoint | Description |\n|----------|-------------|\n| `dist/index.js` | Build output entry |\n| `src/index.ts` | Source entry (exports ManagerContext as KnowledgeGraphManager) |\n| `mcp-server-memory` | CLI binary |\n\n资料来源：[package.json:exports](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n\n## Adding Custom Tools\n\nTo extend the ERO Model with new functionality:\n\n1. **Define Schema** in `toolDefinitions.ts`:\n```typescript\n{\n  name: 'new_tool',\n  description: 'Tool description',\n  inputSchema: {\n    type: 'object',\n    properties: { /* parameters */ },\n    required: ['param1']\n  }\n}\n```\n\n2. **Implement Handler** in `toolHandlers.ts`:\n```typescript\nnew_tool: async (ctx, args) => {\n  // Validate arguments\n  // Call manager methods\n  // Return formatted response\n}\n```\n\n3. **Add Tests** in `tests/e2e/tools/`\n\n资料来源：[CLAUDE.md:adding-tools](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n---\n\n<a id='tool-reference'></a>\n\n## Tool Reference\n\n### 相关页面\n\n相关主题：[Search Capabilities](#search-capabilities), [Temporal and Advanced Features](#temporal-features), [Collaboration and Security](#collaboration-security)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)\n- [src/server/MCPServer.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/MCPServer.ts)\n</details>\n\n# Tool Reference\n\n## Overview\n\nThe Tool Reference documents the 213 MCP tools exposed by memory-mcp, organized across 58 categories. These tools provide a comprehensive interface for managing a persistent knowledge graph that supports entity storage, relationship mapping, semantic search, and temporal reasoning capabilities.\n\nThe tool layer acts as a bridge between MCP clients and the underlying `ManagerContext` system, which provides access to specialized managers for entities, relations, observations, search, tags, hierarchies, analytics, compression, and I/O operations. 资料来源：[CLAUDE.md:1-5]()\n\n## Architecture\n\n### Layered Design\n\n```mermaid\ngraph TD\n    A[MCP Client] --> B[MCPServer]\n    B --> C[Tool Definitions]\n    B --> D[Tool Handlers]\n    C --> E[Schema Validation]\n    D --> F[ManagerContext]\n    F --> G[memoryjs Library]\n    F --> H[GraphStorage]\n    G --> I[SQLite/JSONL]\n    \n    subgraph Managers\n        F --> J[EntityManager]\n        F --> K[RelationManager]\n        F --> L[SearchManager]\n        F --> M[ObservationManager]\n        F --> N[TagManager]\n        F --> O[HierarchyManager]\n        F --> P[AnalyticsManager]\n    end\n```\n\nThe architecture follows a layered approach where tool definitions declare schemas using JSON Schema format, handlers implement business logic by calling manager methods, and the `ManagerContext` provides lazy-initialized access to specialized subsystems. 资料来源：[CLAUDE.md:8-12]()\n\n### Tool Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCPServer\n    participant Handler\n    participant Manager\n    participant Storage\n    \n    Client->>MCPServer: Tool Call Request\n    MCPServer->>Handler: Dispatch with args\n    Handler->>Handler: Validate with Zod schema\n    Handler->>Manager: Call manager method\n    Manager->>Storage: Read/Write data\n    Storage-->>Manager: Result\n    Manager-->>Handler: Response\n    Handler->>Handler: Format response\n    Handler-->>MCPServer: ToolResponse\n    MCPServer-->>Client: MCP-formatted result\n```\n\nError handling in dispatch catches exceptions from handlers and returns them as MCP-formatted error responses rather than throwing. The MCP response `isError` field indicates failures. 资料来源：[CLAUDE.md:85-87]()\n\n## Tool Categories\n\nThe tools are organized into 58 categories spanning core graph operations to advanced features like bitemporal validity and causal reasoning.\n\n| Category | Count | Key Purpose |\n|----------|-------|-------------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities, with normalization |\n| Search | 7 | Basic, ranked (TF-IDF), boolean, fuzzy, auto-select |\n| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |\n| Semantic Search | 3 | Embedding similarity via OpenAI or local models |\n| Saved Searches | 5 | Store and re-execute frequent queries |\n| Tag Management | 6 | Tags, bulk ops, importance scores |\n| Tag Aliases | 5 | Tag synonym/alias management |\n| Hierarchy | 9 | Parent-child trees, subtree traversal |\n| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |\n| Analytics | 2 | Graph stats and integrity validation |\n| Compression | 4 | Duplicate detection, merge, auto-compress, archive |\n| Import/Export | 2 | 7 export formats |\n\n资料来源：[CLAUDE.md:30-44]()\n\n## Tool Definition Schema\n\nEach tool is defined with a JSON Schema that specifies input parameters. The schema follows a consistent pattern:\n\n```typescript\n{\n  name: 'tool_name',\n  description: 'Human-readable description of tool purpose',\n  inputSchema: {\n    type: 'object',\n    properties: {\n      paramName: { \n        type: 'string', \n        description: 'Parameter description',\n        enum: ['option1', 'option2'] // optional for constrained values\n      },\n    },\n    required: ['paramName'], // mandatory parameters\n    additionalProperties: false,\n  },\n}\n```\n\n资料来源：[src/server/toolDefinitions.ts:1-20]()\n\n### Example: Artifact Tool Definition\n\n```typescript\n{\n  name: 'create_artifact',\n  description: 'Create an artifact entity (tool output, code snippet, API response, etc.) with a stable auto-generated ref',\n  inputSchema: {\n    type: 'object',\n    properties: {\n      content: { type: 'string', description: 'Artifact content stored as an entity observation' },\n      toolName: { type: 'string', description: 'Name of the tool or source that produced this artifact' },\n      artifactType: {\n        type: 'string',\n        enum: ['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input'],\n        description: 'Category of artifact for structured filtering',\n      },\n      description: { type: 'string', description: 'Optional human-readable description' },\n      sessionId: { type: 'string', description: 'Optional session context for grouping related artifacts' },\n    },\n    required: ['content', 'toolName', 'artifactType'],\n    additionalProperties: false,\n  },\n}\n```\n\n资料来源：[src/server/toolDefinitions.ts:90-115]()\n\n## Handler Implementation Pattern\n\nTool handlers follow a consistent implementation pattern across all 213 tools:\n\n```typescript\ntool_name: async (ctx, args) => {\n  // 1. Validate required arguments\n  const param = validateWithSchema(args.param, z.string().min(1), 'Invalid param');\n  \n  // 2. Build filter/options objects\n  const filter: FilterType = {};\n  if (args.optionalParam !== undefined) {\n    filter.optionalParam = validateWithSchema(args.optionalParam, z.string(), 'Invalid optionalParam');\n  }\n  \n  // 3. Call manager method\n  const result = await getManager(ctx).method(filter);\n  \n  // 4. Format and return response\n  return formatToolResponse(result);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:1-30]()\n\n### Validation with Zod\n\nHandlers use Zod schemas for runtime validation:\n\n| Zod Function | Usage |\n|--------------|-------|\n| `z.string().min(1)` | Non-empty string |\n| `z.number().int().min(1).max(1000)` | Bounded integer |\n| `z.enum(['option1', 'option2'])` | Constrained string |\n| `z.boolean()` | Boolean flag |\n| `z.string().regex(/pattern/)` | Pattern-matched string |\n| `z.record(z.string(), z.unknown())` | Dictionary object |\n\n```typescript\nconst ref = validateWithSchema(args.ref, z.string().min(1), 'Invalid ref');\nconst limit = validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit');\nconst artifactType = validateWithSchema(\n  args.artifactType,\n  z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n  'Invalid artifactType'\n);\n```\n\n资料来源：[src/server/toolHandlers.ts:5-25]()\n\n## Artifact Tools\n\nArtifact tools manage tool outputs, code snippets, API responses, and other generated content with stable references.\n\n### create_artifact\n\nCreates an artifact entity with a stable auto-generated reference.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `content` | string | Yes | Artifact content stored as an entity observation |\n| `toolName` | string | Yes | Name of the tool or source that produced this artifact |\n| `artifactType` | enum | Yes | Category: `tool_output`, `code_snippet`, `api_response`, `search_result`, `file_content`, `user_input` |\n| `description` | string | No | Human-readable description |\n| `sessionId` | string | No | Session context for grouping related artifacts |\n\n```typescript\ncreate_artifact: async (ctx, args) => {\n  const content = validateWithSchema(args.content, z.string().min(1), 'Invalid content');\n  const toolName = validateWithSchema(args.toolName, z.string().min(1), 'Invalid toolName');\n  const artifactType = validateWithSchema(\n    args.artifactType,\n    z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n    'Invalid artifactType'\n  );\n  const description = args.description !== undefined\n    ? validateWithSchema(args.description, z.string(), 'Invalid description')\n    : undefined;\n  const sessionId = args.sessionId !== undefined\n    ? validateWithSchema(args.sessionId, z.string(), 'Invalid sessionId')\n    : undefined;\n  const artifact = await getArtifactManager(ctx).createArtifact({\n    content, toolName, artifactType, description, sessionId,\n  });\n  return formatToolResponse(artifact);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:290-315]()\n\n### get_artifact\n\nRetrieves an artifact entity by its stable ref or entity name.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `ref` | string | Yes | Stable ref or entity name (e.g. \"bash-2026-03-24-a3f2\") |\n\n```typescript\nget_artifact: async (ctx, args) => {\n  const ref = validateWithSchema(args.ref, z.string().min(1), 'Invalid ref');\n  const artifact = await getArtifactManager(ctx).getArtifact(ref);\n  if (!artifact) {\n    return formatTextResponse(`Artifact \"${ref}\" not found`);\n  }\n  return formatToolResponse(artifact);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:318-328]()\n\n### list_artifacts\n\nLists artifacts with optional filtering by tool name, type, or time.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `toolName` | string | No | Filter by originating tool |\n| `artifactType` | enum | No | Filter by artifact category |\n| `since` | string | No | ISO 8601 timestamp for time-based filtering |\n\n```typescript\nlist_artifacts: async (ctx, args) => {\n  const filter: ArtifactFilter = {};\n  if (args.toolName !== undefined) {\n    filter.toolName = validateWithSchema(args.toolName, z.string(), 'Invalid toolName');\n  }\n  if (args.artifactType !== undefined) {\n    filter.artifactType = validateWithSchema(\n      args.artifactType,\n      z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n      'Invalid artifactType'\n    );\n  }\n  if (args.since !== undefined) {\n    const sinceStr = validateWithSchema(args.since, z.string().regex(/^\\d{4}-\\d{2}-\\d{2}(T[\\d:.Z+-]+)?$/, 'since must be an ISO 8601 date string'), 'Invalid since');\n    const sinceDate = new Date(sinceStr);\n    if (isNaN(sinceDate.getTime())) {\n      throw new Error(`Invalid since date: \"${sinceStr}\" is not a valid date`);\n    }\n    filter.since = sinceDate;\n  }\n  const artifacts = await getArtifactManager(ctx).listArtifacts(Object.keys(filter).length > 0 ? filter : undefined);\n  return formatToolResponse({ artifacts, count: artifacts.length });\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:330-360]()\n\n## Decay and Salience Tools\n\nThese tools manage memory importance over time using time-based decay algorithms.\n\n### run_decay_cycle\n\nRuns a single pass of time-based importance decay across all agent memories.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| (none) | - | - | No parameters required |\n\nReturns the count of decayed and forgotten memories. 资料来源：[src/server/toolDefinitions.ts:180-195]()\n\n### get_decayed_memories\n\nLists memories whose importance has fallen below a threshold due to time-based decay.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `threshold` | number | No | Importance threshold (default: 0.1) |\n\nUnlike `get_stale_entities` which uses freshness timestamps, this tool uses decay engine importance calculations. 资料来源：[src/server/toolDefinitions.ts:197-208]()\n\n### forget_weak_memories\n\nBulk-deletes memories that fell below a decay threshold.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `threshold` | number | No | Importance threshold below which to forget |\n| `maxCount` | number | No | Maximum number of memories to forget |\n| `dryRun` | boolean | No | If true, report what would be forgotten without deleting |\n\nUnlike `forget_memory` (content match) or `archive_entities` (criteria-based move), this uses decay-based importance scoring. 资料来源：[src/server/toolDefinitions.ts:210-222]()\n\n## Governance and Audit Tools\n\n### audit_query\n\nQueries the audit log for operations matching specified criteria.\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `operation` | enum | No | Filter by: `create`, `update`, `delete`, `merge`, `archive` |\n| `agentId` | string | No | Filter by agent identifier |\n| `entityName` | string | No | Filter by entity name |\n| `since` | string | No | Start time (ISO 8601) |\n| `until` | string | No | End time (ISO 8601) |\n| `limit` | number | No | Maximum entries to return (default: 50, max: 1000) |\n\n```typescript\naudit_query: async (ctx, args) => {\n  const filter: AuditFilter = {};\n  if (args.operation !== undefined) {\n    filter.operation = validateWithSchema(\n      args.operation,\n      z.enum(['create', 'update', 'delete', 'merge', 'archive']),\n      'Invalid operation'\n    ) as AuditFilter['operation'];\n  }\n  if (args.agentId !== undefined) {\n    filter.agentId = validateWithSchema(args.agentId, z.string(), 'Invalid agentId');\n  }\n  if (args.entityName !== undefined) {\n    filter.entityName = validateWithSchema(args.entityName, z.string(), 'Invalid entityName');\n  }\n  // AuditFilter uses fromTime/toTime (not since/until)\n  if (args.since !== undefined) {\n    filter.fromTime = validateWithSchema(args.since, z.string(), 'Invalid since');\n  }\n  if (args.until !== undefined) {\n    filter.toTime = validateWithSchema(args.until, z.string(), 'Invalid until');\n  }\n  const limit = args.limit !== undefined\n    ? validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit')\n    : 50;\n  const al = getAuditLog(ctx);\n  let entries = await al.query(filter);\n  entries = entries.slice(0, limit);\n  return formatToolResponse({ entries, count: entries.length });\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:400-440]()\n\n## Adding New Tools\n\nThe development workflow for adding a new tool follows a three-step process:\n\n```mermaid\ngraph LR\n    A[1. Add schema to toolDefinitions.ts] --> B[2. Add handler to toolHandlers.ts]\n    B --> C[3. Add e2e test in tests/e2e/tools/]\n```\n\n1. **Add schema to `toolDefinitions.ts`** — Define the tool name, description, and input schema in the appropriate category section\n2. **Add handler to `toolHandlers.ts`** — Register handler in the `TOOL_HANDLERS` registry with the pattern: validate args → call manager method → return formatted response\n3. **Add e2e test** — Create test coverage in `tests/e2e/tools/` 资料来源：[CONTRIBUTING.md:55-62]()\n\n### Handler Pattern Template\n\n```typescript\n// ==================== CATEGORY_NAME ====================\ntool_name: async (ctx, args) => {\n  // Validate required arguments\n  const required = validateWithSchema(args.required, z.string().min(1), 'Invalid required');\n  \n  // Build options object with optional parameters\n  const options: OptionsType = {};\n  if (args.optional !== undefined) {\n    options.optional = validateWithSchema(args.optional, z.string(), 'Invalid optional');\n  }\n  \n  // Call manager method\n  const result = await getManager(ctx).method(options);\n  \n  // Return formatted response\n  return formatToolResponse(result);\n},\n```\n\nIf the response can be large, wrap the handler result with `withCompression()`. 资料来源：[CONTRIBUTING.md:58-60]()\n\n## Environment Configuration\n\nTools honor the following environment variables:\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `MEMORY_FILE_PATH` | Path to storage file | `memory.jsonl` (cwd) |\n| `MEMORY_STORAGE_TYPE` | `jsonl` or `sqlite` | `jsonl` |\n| `MEMORY_EMBEDDING_PROVIDER` | `openai`, `local`, or `none` | `none` |\n| `MEMORY_OPENAI_API_KEY` | Required if provider is `openai` | — |\n| `MEMORY_EMBEDDING_MODEL` | Embedding model name | `text-embedding-3-small` / `Xenova/all-MiniLM-L6-v2` |\n| `MEMORY_AUTO_INDEX_EMBEDDINGS` | Auto-index on entity creation | `false` |\n\n资料来源：[CLAUDE.md:66-73]()\n\n## ManagerContext Accessors\n\nHandlers access underlying functionality through the ManagerContext:\n\n| Accessor | Purpose |\n|----------|---------|\n| `ctx.entityManager` | Core entity CRUD operations |\n| `ctx.relationManager` | Relationship management |\n| `ctx.observationManager` | Fact attachment to entities |\n| `ctx.searchManager` | Full-text and ranked search |\n| `ctx.tagManager` | Tag CRUD and bulk operations |\n| `ctx.hierarchyManager` | Tree structures and traversal |\n| `ctx.analyticsManager` | Graph statistics |\n| `ctx.compressionManager` | Deduplication and archiving |\n| `ctx.archiveManager` | Historical data management |\n| `ctx.ioManager` | Import/export operations |\n| `ctx.graphTraversal` | Path finding algorithms |\n| `ctx.semanticSearch` | Embedding-based similarity |\n| `ctx.rankedSearch` | TF-IDF ranking |\n| `ctx.storage` | Direct GraphStorage access |\n\n资料来源：[CLAUDE.md:13-26]()\n\n## Storage Backend\n\nTools persist data to the **project root** (not `dist/`):\n\n| Format | Files |\n|--------|-------|\n| JSONL | `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl` |\n| SQLite | `memory.db` (set `MEMORY_STORAGE_TYPE=sqlite`) |\n\nThe `prepare` script runs `npm run build` on install, so `dist/` is rebuilt automatically. 资料来源：[CLAUDE.md:48-55]()\n\n## Response Formatting\n\nHandlers return responses using two formatting functions:\n\n| Function | Usage |\n|----------|-------|\n| `formatToolResponse(data)` | Structured data response (objects, arrays) |\n| `formatTextResponse(text)` | Simple text response (errors, confirmations) |\n\n```typescript\n// Success with data\nreturn formatToolResponse(artifact);\n\n// Not found / error message\nreturn formatTextResponse(`Artifact \"${ref}\" not found`);\n\n// List results\nreturn formatToolResponse({ artifacts, count: artifacts.length });\n```\n\n资料来源：[src/server/toolHandlers.ts:318-328]()\n\n## TypeScript Configuration\n\nTools are built with the following TypeScript configuration:\n\n- **Target**: ES2022\n- **Module resolution**: Node16\n- **Build output**: `dist/index.js`\n- **Source entry**: `src/index.ts` 资料来源：[CLAUDE.md:88-90]()\n\nBackward compatibility is maintained by re-exporting `ManagerContext` as `KnowledgeGraphManager` alias, plus core types. 资料来源：[CLAUDE.md:27-29]()\n\n---\n\n<a id='search-capabilities'></a>\n\n## Search Capabilities\n\n### 相关页面\n\n相关主题：[Entity-Relation-Observation Model](#entity-model), [Temporal and Advanced Features](#temporal-features)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n</details>\n\n# Search Capabilities\n\n## Overview\n\nThe memory-mcp repository provides a comprehensive multi-layered search system with 13 search tools across 6 categories. These capabilities enable users to query the knowledge graph using various matching strategies, from simple text matching to advanced semantic similarity using embeddings.\n\n资料来源：[CLAUDE.md:18]()\n\n## Architecture\n\nThe search system is built on a layered architecture that provides progressive enhancement from basic keyword matching to intelligent semantic understanding.\n\n```mermaid\ngraph TD\n    A[Search Query] --> B[Search Category]\n    A --> C[Intelligent Search]\n    A --> D[Semantic Search]\n    \n    B --> B1[Basic Search]\n    B --> B2[Ranked Search TF-IDF]\n    B --> B3[Boolean Search]\n    B --> B4[Fuzzy Search]\n    B --> B5[Auto-Select]\n    \n    C --> C1[Hybrid Multi-Layer]\n    C --> C2[Query Analysis]\n    C --> C3[Reflection-Based]\n    \n    D --> D1[OpenAI Embeddings]\n    D --> D2[Local Model Embeddings]\n    \n    style A fill:#e1f5fe\n    style B fill:#fff3e0\n    style C fill:#e8f5e9\n    style D fill:#f3e5f5\n```\n\n## Search Tool Categories\n\n| Category | Tool Count | Primary Use Case |\n|----------|------------|------------------|\n| Search | 7 | Core text-based query operations |\n| Intelligent Search | 3 | Advanced query analysis and multi-layer approaches |\n| Semantic Search | 3 | Embedding-based similarity matching |\n| Saved Searches | 5 | Store and reuse frequent queries |\n\n资料来源：[CLAUDE.md:18-22]()\n\n## Basic Search Operations\n\n### Core Search Handler\n\nThe primary search functionality is implemented in `toolHandlers.ts` and supports multiple query types:\n\n```typescript\nsearch: async (ctx, args) => {\n  const query = validateWithSchema(args.query, SearchQuerySchema, 'Invalid search query');\n  const limit = args.limit !== undefined\n    ? validateWithSchema(args.limit, z.number().int().min(1).max(100), 'Invalid limit')\n    : undefined;\n  const graph = await ctx.storage.loadGraph();\n  const results = await ctx.searchManager.search(graph, query, limit);\n  return formatToolResponse({ query, results, count: results.length });\n}\n```\n\n资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n### Search Tool Definition\n\nThe MCP tool definition specifies the input schema for the search interface:\n\n```typescript\n{\n  name: 'semantic_search',\n  description: 'Search for entities using semantic similarity. Requires embedding provider to be configured via MEMORY_EMBEDDING_PROVIDER.',\n  inputSchema: {\n    type: 'object',\n    properties: {\n      query: { type: 'string', description: 'Natural language search query' },\n      limit: { type: 'number', description: 'Maximum number of results (default: 10, max: 100)' },\n      minSimilarity: {\n        type: 'number',\n        description: 'Minimum similarity score threshold (0.0-1.0, default: 0)',\n      },\n    },\n    required: ['query'],\n    additionalProperties: false,\n  },\n}\n```\n\n资料来源：[src/server/toolDefinitions.ts:1-30]()\n\n## Semantic Search\n\nSemantic search provides embedding-based similarity matching for natural language queries.\n\n### Configuration Requirements\n\nSemantic search requires an embedding provider to be configured via the `MEMORY_EMBEDDING_PROVIDER` environment variable:\n\n| Provider | Description |\n|----------|-------------|\n| `openai` | Use OpenAI embedding models |\n| `local` | Use locally deployed embedding models |\n\n### Handler Implementation\n\nThe semantic search handler validates configuration and executes embedding-based queries:\n\n```typescript\nsemantic_search: async (ctx, args) => {\n  const semanticSearch = ctx.semanticSearch;\n  if (!semanticSearch) {\n    return formatTextResponse(\n      'Semantic search is not available. Set MEMORY_EMBEDDING_PROVIDER environment variable to \"openai\" or \"local\".'\n    );\n  }\n\n  const query = validateWithSchema(args.query, SearchQuerySchema, 'Invalid search query');\n  const limit = args.limit !== undefined\n    ? validateWithSchema(args.limit, z.number().int().min(1).max(100), 'Invalid limit (1-100)')\n    : undefined;\n  const minSimilarity = args.minSimilarity !== undefined\n    ? validateWithSchema(args.minSimilarity, z.number().min(0).max(1), 'Invalid minSimilarity (0-1)')\n    : undefined;\n\n  const graph = await ctx.storage.loadGraph();\n  const results = await semanticSearch.search(graph, query, limit, minSimilarity);\n\n  return formatToolResponse({\n    query,\n    results: results.map(r => ({\n      entity: r.entity,\n      similarity: r.similarity,\n    })),\n    count: results.length,\n  });\n}\n```\n\n资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n### Similar Entity Discovery\n\nThe `find_similar_entities` tool extends semantic search to discover entities similar to a given reference entity:\n\n```typescript\nfind_similar_entities: async (ctx, args) => {\n  const semanticSearch = ctx.semanticSearch;\n  if (!semanticSearch) {\n    return formatTextResponse(\n      'Semantic search is not available. Set MEMORY_EMBEDDING_PROVIDER environment variable...'\n    );\n  }\n  // Implementation continues...\n}\n```\n\n## Search Manager Architecture\n\nThe search functionality is provided through the `ManagerContext` which exposes the `searchManager` and `semanticSearch` accessors:\n\n```typescript\n// Available accessors in ManagerContext\nctx.entityManager\nctx.relationManager\nctx.observationManager\nctx.searchManager        // Basic search operations\nctx.tagManager\nctx.hierarchyManager\nctx.analyticsManager\nctx.compressionManager\nctx.archiveManager\nctx.ioManager\nctx.graphTraversal\nctx.semanticSearch       // Embedding-based search\nctx.rankedSearch\nctx.storage              // Direct GraphStorage access\n```\n\n资料来源：[CLAUDE.md:10-13]()\n\n## Search Parameters\n\n### Input Validation Schema\n\nAll search operations use Zod schemas for input validation to ensure type safety:\n\n| Parameter | Type | Constraints | Default |\n|-----------|------|-------------|---------|\n| query | string | min(1) | required |\n| limit | number | int, min(1), max(100) | undefined |\n| minSimilarity | number | min(0), max(1) | undefined |\n\n### Validation Pattern\n\nThe tool handlers use a consistent validation pattern:\n\n```typescript\nconst validateWithSchema = (value, schema, errorMessage) => {\n  const result = schema.safeParse(value);\n  if (!result.success) {\n    throw new Error(`${errorMessage}: ${result.error.message}`);\n  }\n  return result.data;\n};\n```\n\n## Search Result Format\n\nResults are formatted consistently across all search operations:\n\n```typescript\nreturn formatToolResponse({\n  query,\n  results: results.map(r => ({\n    entity: r.entity,\n    similarity: r.similarity,  // Only for semantic search\n  })),\n  count: results.length,\n});\n```\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Required | Values | Purpose |\n|----------|----------|--------|---------|\n| `MEMORY_EMBEDDING_PROVIDER` | For semantic search | `openai`, `local` | Select embedding backend |\n| `MEMORY_STORAGE_TYPE` | No | `jsonl`, `sqlite` | Storage format for graph data |\n\n### Storage Integration\n\nSearch operations load the graph from storage before executing queries:\n\n```typescript\nconst graph = await ctx.storage.loadGraph();\n```\n\nThe storage layer supports both JSONL and SQLite backends for persistent graph storage.\n\n资料来源：[CLAUDE.md:38-42]()\n\n## Workflow Diagram\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant MCPServer\n    participant SearchManager\n    participant Storage\n    participant SemanticSearch\n\n    User->>MCPServer: search query\n    MCPServer->>MCPServer: Validate input schema\n    MCPServer->>Storage: loadGraph()\n    Storage-->>MCPServer: graph data\n    alt Basic Search\n        MCPServer->>SearchManager: search(graph, query, limit)\n        SearchManager-->>MCPServer: text match results\n    else Semantic Search\n        MCPServer->>SemanticSearch: search(graph, query, limit, minSimilarity)\n        SemanticSearch-->>MCPServer: similarity results\n    end\n    MCPServer-->>User: formatted response\n```\n\n## Related Documentation\n\n- [Query Language Guide](docs/guides/QUERY_LANGUAGE.md) - Syntax and operators for advanced queries\n- [Compression Guide](docs/guides/COMPRESSION.md) - Search optimization through deduplication\n\n---\n\n<a id='temporal-features'></a>\n\n## Temporal and Advanced Features\n\n### 相关页面\n\n相关主题：[Entity-Relation-Observation Model](#entity-model), [Tool Reference](#tool-reference)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n- [tools/create-dependency-graph/README.md](https://github.com/danielsimonjr/memory-mcp/blob/main/tools/create-dependency-graph/README.md)\n</details>\n\n# Temporal and Advanced Features\n\nThis page documents the temporal, governance, and advanced cognitive features available in the memory-mcp system. These features extend beyond basic entity and relation management to provide sophisticated memory lifecycle management, access control, and intelligent decay mechanisms.\n\n## Overview\n\nThe memory-mcp system implements advanced features introduced in two major phases:\n\n- **Phase 15 (v12.2.0)**: Added 23 tools surfacing memoryjs v1.14+ features including bitemporal validity, OCC (Optimistic Concurrency Control), RBAC (Role-Based Access Control), procedural memory, active retrieval, causal reasoning, and world model capabilities.\n- **Phase 16 (v12.3.0)**: Added 53 tools surfacing memoryjs v2.1.0 features including decision rationale, ADR markdown dual-write, structured project context, heuristic guidelines, tool affordance observation pipeline, observation deduplication, and spell correction.\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Architecture\n\nThe advanced features are built upon the layered architecture where memory-mcp acts as the MCP server layer while the core graph logic resides in the `@danielsimonjr/memoryjs` package.\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (MCP Server Layer)\"\n        A[toolHandlers.ts] --> B[ManagerContext Accessors]\n        C[toolDefinitions.ts] --> B\n    end\n    \n    subgraph \"@danielsimonjr/memoryjs (Core Library)\"\n        B --> D[EntityManager]\n        B --> E[RelationManager]\n        B --> F[ObservationManager]\n        B --> G[SearchManager]\n        B --> H[CompressionManager]\n        B --> I[ArchiveManager]\n        B --> J[GraphTraversal]\n        B --> K[SemanticSearch]\n    end\n    \n    subgraph \"Temporal Features\"\n        L[Bitemporal Validity]\n        M[OCC - Optimistic Concurrency Control]\n        N[Decay Engine]\n    end\n    \n    subgraph \"Advanced Features\"\n        O[RBAC Governance]\n        P[Audit Logging]\n        Q[Artifact Management]\n        R[Procedural Memory]\n    end\n    \n    D --> L\n    E --> M\n    F --> N\n    G --> O\n    H --> P\n    I --> Q\n    J --> R\n```\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Governance and Access Control\n\n### Role-Based Access Control (RBAC)\n\nThe system implements RBAC through governance policy settings that control what operations agents can perform on memory entities.\n\n#### Governance Policy Tool\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `allowCreate` | boolean | Permission to create new entities |\n| `allowUpdate` | boolean | Permission to update existing entities |\n| `allowDelete` | boolean | Permission to delete entities |\n\n**Handler Implementation:**\n\n```typescript\ngovernance_policy_set: async (ctx, args) => {\n  const allowCreate = validateWithSchema(args.allowCreate, z.boolean(), 'Invalid allowCreate');\n  const allowUpdate = validateWithSchema(args.allowUpdate, z.boolean(), 'Invalid allowUpdate');\n  const allowDelete = validateWithSchema(args.allowDelete, z.boolean(), 'Invalid allowDelete');\n  \n  const { setGovernancePolicy } = await import('@danielsimonjr/memoryjs');\n  await setGovernancePolicy(ctx.storage, {\n    canCreate: allowCreate ? undefined : () => false,\n    canUpdate: allowUpdate ? undefined : () => false,\n    canDelete: allowDelete ? undefined : () => false,\n  });\n  return formatTextResponse(`Governance policy set: canCreate=${allowCreate}, canUpdate=${allowUpdate}, canDelete=${allowDelete}`);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:1-50](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n### Audit Logging\n\nThe audit system tracks all operations performed on the knowledge graph for compliance and debugging purposes.\n\n#### Audit Query Parameters\n\n| Parameter | Type | Description | Default |\n|-----------|------|-------------|---------|\n| `operation` | enum | create, update, delete, merge, archive | — |\n| `agentId` | string | Filter by agent identifier | — |\n| `entityName` | string | Filter by entity name | — |\n| `since` | string | Start time (maps to fromTime) | — |\n| `until` | string | End time (maps to toTime) | — |\n| `limit` | number | Maximum entries to return | 50 |\n\n**Handler Implementation:**\n\n```typescript\naudit_query: async (ctx, args) => {\n  const filter: AuditFilter = {};\n  if (args.operation !== undefined) {\n    filter.operation = validateWithSchema(args.operation, z.enum(['create', 'update', 'delete', 'merge', 'archive']), 'Invalid operation');\n  }\n  if (args.agentId !== undefined) {\n    filter.agentId = validateWithSchema(args.agentId, z.string(), 'Invalid agentId');\n  }\n  if (args.entityName !== undefined) {\n    filter.entityName = validateWithSchema(args.entityName, z.string(), 'Invalid entityName');\n  }\n  if (args.since !== undefined) {\n    filter.fromTime = validateWithSchema(args.since, z.string(), 'Invalid since');\n  }\n  if (args.until !== undefined) {\n    filter.toTime = validateWithSchema(args.until, z.string(), 'Invalid until');\n  }\n  const limit = args.limit !== undefined\n    ? validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit')\n    : 50;\n  const al = getAuditLog(ctx);\n  let entries = await al.query(filter);\n  entries = entries.slice(0, limit);\n  // ...\n}\n```\n\n资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n## Temporal Validity and Bitemporal Data\n\n### Bitemporal Validity\n\nBitemporal validity tracks two dimensions of time:\n\n1. **Valid Time**: When facts were true in the real world\n2. **Transaction Time**: When facts were recorded in the system\n\nThis enables accurate historical queries and audit trails that reflect the state of knowledge at any point in time.\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n### Optimistic Concurrency Control (OCC)\n\nOCC prevents conflicting updates by checking whether the data has changed since it was last read, ensuring data consistency without requiring locks.\n\n## Memory Decay and Salience\n\nThe decay engine implements time-based importance scoring that automatically reduces the importance of memories over time.\n\n### Decay Cycle Tool\n\nThe `run_decay_cycle` tool executes a single pass of time-based importance decay across all agent memories.\n\n```typescript\n{\n  name: 'run_decay_cycle',\n  description: 'Run a single pass of time-based importance decay across all agent memories. Returns count of decayed and forgotten memories.',\n  inputSchema: {\n    type: 'object',\n    properties: {},\n    additionalProperties: false,\n  },\n}\n```\n\n资料来源：[src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n\n### Decay-Based Memory Queries\n\n| Tool | Purpose | Key Parameters |\n|------|---------|----------------|\n| `get_decayed_memories` | List memories below decay threshold | `threshold` (default: 0.1) |\n| `forget_weak_memories` | Bulk-delete memories below threshold | `threshold`, `maxCount`, `dryRun` |\n\n**Difference from other deletion mechanisms:**\n\n- `forget_memory`: Uses content matching\n- `archive_entities`: Uses criteria-based move to archive\n- `forget_weak_memories`: Uses decay-based importance scoring\n\n```typescript\n{\n  name: 'get_decayed_memories',\n  description: 'List memories whose importance has fallen below a threshold due to time-based decay. Unlike get_stale_entities (which uses freshness timestamps), this uses decay engine importance calculations.',\n  inputSchema: {\n    type: 'object',\n    properties: {\n      threshold: { type: 'number', description: 'Importance threshold (default: 0.1)' },\n    },\n    additionalProperties: false,\n  },\n}\n```\n\n资料来源：[src/server/toolDefinitions.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefinitions.ts)\n\n## Artifact Management\n\nArtifacts capture structured outputs from tool executions for later retrieval and analysis.\n\n### Artifact Types\n\n| Type | Description |\n|------|-------------|\n| `tool_output` | Results from tool invocations |\n| `code_snippet` | Generated or analyzed code |\n| `api_response` | External API responses |\n| `search_result` | Search query results |\n| `file_content` | File read contents |\n| `user_input` | User-provided prompts |\n\n### Artifact Tools\n\n```typescript\ncreate_artifact: async (ctx, args) => {\n  const content = validateWithSchema(args.content, z.string().min(1), 'Invalid content');\n  const toolName = validateWithSchema(args.toolName, z.string().min(1), 'Invalid toolName');\n  const artifactType = validateWithSchema(\n    args.artifactType,\n    z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n    'Invalid artifactType'\n  );\n  const description = args.description !== undefined\n    ? validateWithSchema(args.description, z.string(), 'Invalid description')\n    : undefined;\n  const sessionId = args.sessionId !== undefined\n    ? validateWithSchema(args.sessionId, z.string(), 'Invalid sessionId')\n    : undefined;\n  const artifact = await getArtifactManager(ctx).createArtifact({\n    content, toolName, artifactType, description, sessionId,\n  });\n  return formatToolResponse(artifact);\n},\n\nget_artifact: async (ctx, args) => {\n  const ref = validateWithSchema(args.ref, z.string().min(1), 'Invalid ref');\n  const artifact = await getArtifactManager(ctx).getArtifact(ref);\n  if (!artifact) {\n    return formatTextResponse(`Artifact \"${ref}\" not found`);\n  }\n  return formatToolResponse(artifact);\n},\n\nlist_artifacts: async (ctx, args) => {\n  const filter: ArtifactFilter = {};\n  if (args.toolName !== undefined) {\n    filter.toolName = validateWithSchema(args.toolName, z.string(), 'Invalid toolName');\n  }\n  // ...\n}\n```\n\n资料来源：[src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n\n## Phase 16 Advanced Features (v12.3.0)\n\n### Decision Rationale and ADR Dual-Write\n\nThe system supports dual-writing decision rationale in both structured format and Architecture Decision Records (ADR) markdown format.\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n### Tool Affordance and Observation Pipeline\n\n| Component | Description |\n|-----------|-------------|\n| `ToolCallObserver` | Pipeline for observing and analyzing tool calls |\n| Tool Affordance | Metadata describing available tool capabilities |\n| Observation Dedup | Prevents duplicate observations in the system |\n| Spell Correction | 3 tools for automatic typo correction in queries |\n\n### Structured Project Context\n\n12 tools providing structured access to project metadata and context for better decision-making.\n\n### Heuristic Guidelines\n\n10 tools implementing rule-based guidance for memory management and retrieval decisions.\n\n## Tool Categories Summary\n\nThe system organizes its 213 tools across 58 categories, with the advanced features distributed across:\n\n| Category | Feature Type |\n|----------|--------------|\n| Governance | RBAC, audit logging |\n| Compression | Duplicate detection, merge, auto-compress |\n| Analytics | Graph stats, integrity validation |\n| Decay & Salience | Time-based importance decay |\n| Import/Export | Multi-format data handling |\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Storage Considerations\n\nAdvanced features persist data in the same storage backends as core entities:\n\n| Storage Type | File Location | Configuration |\n|--------------|---------------|---------------|\n| JSONL | `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl` | Default |\n| SQLite | `memory.db` | Set `MEMORY_STORAGE_TYPE=sqlite` |\n\nData files reside in the project root (not `dist/`), and are gitignored to prevent accidental commits.\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Manager Context Accessors\n\nAdvanced features access the core library through the `ManagerContext`:\n\n| Accessor | Purpose |\n|----------|---------|\n| `ctx.analyticsManager` | Graph statistics and validation |\n| `ctx.compressionManager` | Duplicate detection and merging |\n| `ctx.archiveManager` | Long-term memory archival |\n| `ctx.ioManager` | Import/export operations |\n| `ctx.graphTraversal` | Advanced graph navigation |\n| `ctx.semanticSearch` | Embedding-based search |\n| `ctx.rankedSearch` | TF-IDF based search |\n| `ctx.storage` | Direct GraphStorage access |\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n## Testing Coverage\n\nAdvanced features are covered by the test suite with the following coverage metrics:\n\n| Metric | Coverage |\n|--------|----------|\n| Statements | 80.7% |\n| Lines | 81.4% |\n| Functions | 79.5% |\n| Branches | 68.3% |\n\nTest files are organized in `tests/e2e/tools/` with one file per tool group including governance, freshness, and entropy categories.\n\n资料来源：[CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n\n---\n\n<a id='collaboration-security'></a>\n\n## Collaboration and Security\n\n### 相关页面\n\n相关主题：[Tool Reference](#tool-reference), [Temporal and Advanced Features](#temporal-features)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/server/toolHandlers.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolHandlers.ts)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)\n- [src/server/toolDefs.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/src/server/toolDefs.ts)\n- [docs/architecture/API.md](https://github.com/danielsimonjr/memory-mcp/blob/main/docs/architecture/API.md)\n- [docs/architecture/TEST_COVERAGE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/docs/architecture/TEST_COVERAGE.md)\n</details>\n\n# Collaboration and Security\n\nThe memory-mcp system provides a comprehensive suite of collaboration and security features designed to enable multi-agent workflows while maintaining data integrity, access control, and auditability. These features are built on the underlying memoryjs library (v1.14+) and exposed through 213 MCP tools across 58 categories.\n\n## Overview\n\nCollaboration and Security in memory-mcp encompasses four primary domains:\n\n| Domain | Purpose | Key Components |\n|--------|---------|----------------|\n| **Governance** | Access control policies | RBAC, CRUD permissions |\n| **Audit** | Activity tracking | Operation logs, agent attribution |\n| **Artifacts** | Collaboration artifacts | Tool outputs, code snippets, session data |\n| **Data Integrity** | Export security | PII redaction, format validation |\n\n资料来源：[CLAUDE.md:14-16]()\n\n## Architecture\n\n```graph TD\n    subgraph \"MCP Client Layer\"\n        A[AI Agent 1] \n        B[AI Agent 2]\n        C[Human User]\n    end\n    \n    subgraph \"memory-mcp Server\"\n        D[MCP Protocol Handler]\n        E[Tool Router]\n        F[Governance Layer]\n    end\n    \n    subgraph \"memoryjs Core\"\n        G[EntityManager]\n        H[RelationManager]\n        I[AuditManager]\n        J[ArtifactManager]\n    end\n    \n    subgraph \"Storage\"\n        K[(JSONL/SQLite)]\n    end\n    \n    A --> D\n    B --> D\n    C --> D\n    D --> E\n    E --> F\n    F --> G\n    F --> H\n    E --> I\n    E --> J\n    G --> K\n    H --> K\n    I --> K\n    J --> K\n```\n\n## Governance and Access Control\n\n### Role-Based Access Control (RBAC)\n\nmemory-mcp implements RBAC through the memoryjs library, providing granular control over entity and relation operations. 资料来源：[CLAUDE.md:16]()\n\n### Governance Policy Management\n\nThe `governance_set_policy` tool enables administrators to configure CRUD permissions for the knowledge graph:\n\n```typescript\ngovernance_set_policy: async (ctx, args) => {\n    const { \n        allowCreate = true, \n        allowUpdate = true, \n        allowDelete = true \n    } = args;\n    \n    const governance = getGovernance(ctx);\n    await governance.setPolicy({\n        canCreate: allowCreate ? undefined : () => false,\n        canUpdate: allowUpdate ? undefined : () => false,\n        canDelete: allowDelete ? undefined : () => false,\n    });\n    return formatTextResponse(\n        `Governance policy set: canCreate=${allowCreate}, canUpdate=${allowUpdate}, canDelete=${allowDelete}`\n    );\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:1-20]()\n\n### Governance Tool Definition\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `allowCreate` | boolean | No | Enable entity creation (default: true) |\n| `allowUpdate` | boolean | No | Enable entity updates (default: true) |\n| `allowDelete` | boolean | No | Enable entity deletion (default: true) |\n\nWhen a permission flag is `false`, the governance layer installs a deny function that blocks the operation.\n\n## Audit System\n\n### Audit Log Architecture\n\nThe audit system tracks all graph mutations with full attribution:\n\n```graph TD\n    A[Graph Operation] --> B{AuditManager}\n    B --> C[Create Entry]\n    B --> D[Update Entry]\n    B --> E[Delete Entry]\n    B --> F[Merge Entry]\n    B --> G[Archive Entry]\n    \n    C --> H[AuditStore]\n    D --> H\n    E --> H\n    F --> H\n    G --> H\n```\n\n### Audit Query Handler\n\nThe `audit_query` tool provides filtered access to audit entries:\n\n```typescript\naudit_query: async (ctx, args) => {\n    const filter: AuditFilter = {};\n    if (args.operation !== undefined) {\n        filter.operation = validateWithSchema(\n            args.operation,\n            z.enum(['create', 'update', 'delete', 'merge', 'archive']),\n            'Invalid operation'\n        );\n    }\n    if (args.agentId !== undefined) {\n        filter.agentId = validateWithSchema(args.agentId, z.string(), 'Invalid agentId');\n    }\n    if (args.entityName !== undefined) {\n        filter.entityName = validateWithSchema(args.entityName, z.string(), 'Invalid entityName');\n    }\n    if (args.since !== undefined) {\n        filter.fromTime = validateWithSchema(args.since, z.string(), 'Invalid since');\n    }\n    if (args.until !== undefined) {\n        filter.toTime = validateWithSchema(args.until, z.string(), 'Invalid until');\n    }\n    const limit = args.limit !== undefined\n        ? validateWithSchema(args.limit, z.number().int().min(1).max(1000), 'Invalid limit')\n        : 50;\n    const al = getAuditLog(ctx);\n    let entries = await al.query(filter);\n    entries = entries.slice(0, limit);\n    // ...\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:22-57]()\n\n### Audit Query Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `operation` | enum | No | Filter by: `create`, `update`, `delete`, `merge`, `archive` |\n| `agentId` | string | No | Filter by responsible agent |\n| `entityName` | string | No | Filter by affected entity |\n| `since` | string | No | Start time (ISO 8601) |\n| `until` | string | No | End time (ISO 8601) |\n| `limit` | number | No | Max results (1-1000, default: 50) |\n\n### Supported Audit Operations\n\nThe audit system records the complete lifecycle of graph entities:\n\n| Operation | Description |\n|-----------|-------------|\n| `create` | New entity or relation creation |\n| `update` | Modification of existing entities |\n| `delete` | Permanent removal from graph |\n| `merge` | Entity consolidation operations |\n| `archive` | Soft deletion with retention |\n\n## Artifact Management\n\n### Purpose\n\nArtifacts enable collaboration by persisting tool outputs, code snippets, API responses, and user inputs across sessions. This supports multi-agent workflows where one agent's output becomes another agent's context.\n\n### Artifact Types\n\n| Type | Use Case |\n|------|----------|\n| `tool_output` | Raw outputs from MCP tool invocations |\n| `code_snippet` | Generated or referenced code |\n| `api_response` | External API responses |\n| `search_result` | Search query results |\n| `file_content` | File contents for reference |\n| `user_input` | User-provided content |\n\n资料来源：[src/server/toolHandlers.ts:59-75]()\n\n### Artifact CRUD Operations\n\n#### Create Artifact\n\n```typescript\ncreate_artifact: async (ctx, args) => {\n    const content = validateWithSchema(args.content, z.string().min(1), 'Invalid content');\n    const toolName = validateWithSchema(args.toolName, z.string().min(1), 'Invalid toolName');\n    const artifactType = validateWithSchema(\n        args.artifactType,\n        z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n        'Invalid artifactType'\n    );\n    const description = args.description !== undefined\n        ? validateWithSchema(args.description, z.string(), 'Invalid description')\n        : undefined;\n    const sessionId = args.sessionId !== undefined\n        ? validateWithSchema(args.sessionId, z.string(), 'Invalid sessionId')\n        : undefined;\n    const artifact = await getArtifactManager(ctx).createArtifact({\n        content, toolName, artifactType, description, sessionId,\n    });\n    return formatToolResponse(artifact);\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:59-80]()\n\n#### List Artifacts with Filtering\n\n```typescript\nlist_artifacts: async (ctx, args) => {\n    const filter: ArtifactFilter = {};\n    if (args.toolName !== undefined) {\n        filter.toolName = validateWithSchema(args.toolName, z.string(), 'Invalid toolName');\n    }\n    if (args.artifactType !== undefined) {\n        filter.artifactType = validateWithSchema(\n            args.artifactType,\n            z.enum(['tool_output', 'code_snippet', 'api_response', 'search_result', 'file_content', 'user_input']),\n            'Invalid artifactType'\n        );\n    }\n    if (args.since !== undefined) {\n        const sinceStr = validateWithSchema(args.since, z.string().regex(/^\\d{4}-\\d{2}-\\d{2}(T[\\d:.Z+-]+)?$/, 'since must be an ISO 8601 date string'), 'Invalid since');\n        const sinceDate = new Date(sinceStr);\n        if (isNaN(sinceDate.getTime())) {\n            throw new Error(`Invalid since date: \"${sinceStr}\" is not a valid date`);\n        }\n        filter.since = sinceDate;\n    }\n    const artifacts = await getArtifactManager(ctx).listArtifacts(\n        Object.keys(filter).length > 0 ? filter : undefined\n    );\n    return formatToolResponse({ artifacts, count: artifacts.length });\n}\n```\n\n资料来源：[src/server/toolHandlers.ts:95-125]()\n\n### Artifact Filter Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `toolName` | string | No | Filter by originating tool |\n| `artifactType` | enum | No | Filter by artifact type |\n| `since` | string | No | ISO 8601 date for time-based filtering |\n\n## Data Integrity and Export Security\n\n### PII Redaction\n\nWhen exporting graph data, memory-mcp supports automatic PII redaction to prevent sensitive information leakage:\n\n```graph TD\n    A[Export Request] --> B{Export Format}\n    B -->|XML| C[memoryjs η.5.4]\n    B -->|JSON-LD| C\n    C --> D{redactPii: true}\n    D -->|Yes| E[Redaction Engine]\n    D -->|No| F[Raw Export]\n    E --> F\n    F --> G[Exported File]\n```\n\n资料来源：[CLAUDE.md:34-35]()\n\n### Export Configuration\n\n| Option | Type | Description | Version |\n|--------|------|-------------|---------|\n| `redactPii` | boolean | Enable PII redaction on export | memoryjs η.6.3+ |\n| Export formats | enum | `xml`, `json-ld` | memoryjs η.5.4+ |\n\n### Compression for Context\n\nThe standalone `compress-for-context` tool provides CTON (Compact Textual Object Notation) compression for managing context windows during multi-agent collaboration:\n\n```bash\n# Single file compression\nnode compress-for-context.js data.json\n\n# Aggressive compression for maximum context savings\nnode compress-for-context.js README.md -l aggressive\n\n# Batch processing\nnode compress-for-context.js -b -p \"*.json\" ./src\n```\n\n资料来源：[tools/compress-for-context/compress-for-context.ts:1-25]()\n\n## Security Architecture\n\n```graph TD\n    subgraph \"Security Layers\"\n        A[Authentication]\n        B[Authorization]\n        C[Audit Logging]\n        D[Data Encryption]\n    end\n    \n    subgraph \"Access Control Points\"\n        E[governance_set_policy]\n        F[RBAC via memoryjs]\n        G[Operation Validation]\n    end\n    \n    subgraph \"Audit Trail\"\n        H[Operation Tracking]\n        I[Agent Attribution]\n        J[Time-based Queries]\n    end\n    \n    A --> B\n    B --> C\n    C --> D\n    E --> F\n    F --> G\n    G --> H\n    H --> I\n    I --> J\n```\n\n## Environment Variables for Security\n\n| Variable | Description | Default | Security Impact |\n|----------|-------------|---------|-----------------|\n| `MEMORY_FILE_PATH` | Storage file location | `memory.jsonl` | Data isolation |\n| `MEMORY_STORAGE_TYPE` | Storage backend | `jsonl` | Persistence security |\n| `MEMORY_EMBEDDING_PROVIDER` | Embedding service | `none` | External data exposure |\n| `MEMORY_OPENAI_API_KEY` | API authentication | — | External service auth |\n\n资料来源：[CLAUDE.md:58-64]()\n\n## Testing Coverage\n\nThe collaboration and security features are validated through the test suite:\n\n| Test Category | Location | Coverage Focus |\n|---------------|----------|----------------|\n| Integration | `tests/integration/` | MCP server lifecycle, security hooks |\n| E2E | `tests/e2e/tools/` | Per-tool handler validation |\n| Governance | `tests/e2e/tools/governance.test.ts` | Policy enforcement |\n| Audit | `tests/e2e/tools/audit.test.ts` | Log integrity |\n| Artifacts | `tests/e2e/tools/artifact.test.ts` | CRUD operations |\n\n资料来源：[CLAUDE.md:46-50](), [docs/architecture/TEST_COVERAGE.md]()\n\n## Best Practices for Multi-Agent Collaboration\n\n1. **Configure Governance Early**: Set appropriate `allowCreate`, `allowUpdate`, and `allowDelete` policies before enabling multi-agent access.\n\n2. **Enable Audit Logging**: Use `audit_query` with appropriate filters to monitor agent activity and detect anomalies.\n\n3. **Use Artifacts for Context**: Store intermediate results as artifacts with descriptive `sessionId` values to enable context sharing.\n\n4. **Enable PII Redaction**: Set `redactPii: true` when exporting data containing sensitive information.\n\n5. **Rotate Storage Files**: Implement periodic rotation of `memory.jsonl` or `memory.db` with archival to maintain audit history.\n\n## Pull Request Security Requirements\n\nWhen contributing security-related changes:\n\n1. **Title**: Clear, descriptive summary of the security impact\n2. **Description**: Document what changed, why, and potential security implications\n3. **Tests**: Include test results demonstrating security controls\n4. **Documentation**: Update relevant security documentation\n5. **Backward Compatibility**: Confirm no breaking security changes\n\n资料来源：[CONTRIBUTING.md:37-44]()\n\n---\n\n<a id='development-guide'></a>\n\n## Development Guide\n\n### 相关页面\n\n相关主题：[Getting Started](#getting-started)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n- [tsconfig.json](https://github.com/danielsimonjr/memory-mcp/blob/main/tsconfig.json)\n- [vitest.config.ts](https://github.com/danielsimonjr/memory-mcp/blob/main/vitest.config.ts)\n- [CONTRIBUTING.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CONTRIBUTING.md)\n- [CLAUDE.md](https://github.com/danielsimonjr/memory-mcp/blob/main/CLAUDE.md)\n</details>\n\n# Development Guide\n\nThis guide provides comprehensive information for developers contributing to the memory-mcp project. It covers project setup, architecture, coding standards, testing practices, and the development workflow.\n\n## Project Overview\n\nmemory-mcp is a Model Context Protocol (MCP) server that provides memory and knowledge graph capabilities. The server exposes 213 tools across 58 categories for managing entities, relations, observations, searches, tags, hierarchies, and analytics.\n\n**npm Package:** `@danielsimonjr/memory-mcp`\n**Core Dependency:** `@danielsimonjr/memoryjs` (currently `^2.1.0`)\n\n资料来源：[CLAUDE.md:1]()\n\n## Architecture Overview\n\n### Layered Architecture\n\nThe project follows a layered architecture where memory-mcp serves as the MCP interface layer on top of the memoryjs core library.\n\n```mermaid\ngraph TD\n    subgraph \"memory-mcp (this repo)\"\n        A[\"src/index.ts\"] --> B[\"src/server/MCPServer.ts\"]\n        B --> C[\"src/server/toolDefs.ts\"]\n        B --> D[\"src/server/toolHandlers.ts\"]\n        C --> E[\"Tool Definitions\"]\n        D --> F[\"Tool Handlers\"]\n    end\n    \n    subgraph \"@danielsimonjr/memoryjs (npm dependency)\"\n        G[\"ManagerContext\"]\n        G --> H[\"EntityManager\"]\n        G --> I[\"RelationManager\"]\n        G --> J[\"ObservationManager\"]\n        G --> K[\"SearchManager\"]\n        G --> L[\"TagManager\"]\n        G --> M[\"HierarchyManager\"]\n        G --> N[\"AnalyticsManager\"]\n        G --> O[\"GraphStorage/SQLiteStorage\"]\n    end\n    \n    F -->|imports| G\n```\n\n资料来源：[CLAUDE.md:15-25]()\n\n### Key Source Files\n\n| File | Purpose |\n|------|---------|\n| `src/index.ts` | Entry point, re-exports `ManagerContext` as `KnowledgeGraphManager` |\n| `src/server/MCPServer.ts` | MCP server implementation |\n| `src/server/toolDefs.ts` | JSON schema definitions for all 213 tools |\n| `src/server/toolHandlers.ts` | Implementation handlers for each tool |\n\n资料来源：[CLAUDE.md:28-31]()\n\n## Project Setup\n\n### Prerequisites\n\n- Node.js (compatible with ES2022)\n- npm\n\n### Installation\n\n```bash\ncd c:/mcp-servers/memory-mcp\nnpm install\n```\n\nThe `prepare` script automatically runs `npm run build` on install, so the `dist/` directory is rebuilt automatically.\n\n资料来源：[CLAUDE.md:54]()\n\n### TypeScript Configuration\n\nThe project uses ES2022 target with Node16 module resolution:\n\n```json\n{\n  \"compilerOptions\": {\n    \"target\": \"ES2022\",\n    \"module\": \"Node16\",\n    \"moduleResolution\": \"Node16\",\n    \"outDir\": \"./dist\",\n    \"rootDir\": \"./src\"\n  },\n  \"include\": [\"src/**/*\"]\n}\n```\n\n资料来源：[tsconfig.json](https://github.com/danielsimonjr/memory-mcp/blob/main/tsconfig.json)\n\n### Build Scripts\n\n| Script | Purpose |\n|--------|---------|\n| `npm run build` | Compile TypeScript to `dist/` |\n| `npm run typecheck` | Run TypeScript type checking |\n| `npm run test` | Run all tests |\n| `npm run test:unit` | Run unit tests only |\n| `npm run test:e2e` | Run end-to-end tests |\n| `npm run docs:deps` | Generate dependency graph documentation |\n\n资料来源：[package.json](https://github.com/danielsimonjr/memory-mcp/blob/main/package.json)\n\n## Environment Configuration\n\nThe MCP server uses environment variables for configuration:\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `MEMORY_FILE_PATH` | Path to storage file | `memory.jsonl` (cwd) |\n| `MEMORY_STORAGE_TYPE` | `jsonl` or `sqlite` | `jsonl` |\n| `MEMORY_EMBEDDING_PROVIDER` | `openai`, `local`, or `none` | `none` |\n| `MEMORY_OPENAI_API_KEY` | Required if provider is `openai` | — |\n| `MEMORY_EMBEDDING_MODEL` | Embedding model name | `text-embedding-3-small` / `Xenova/all-MiniLM-L6-v2` |\n| `MEMORY_AUTO_INDEX_EMBEDDINGS` | Auto-index on entity creation | `false` |\n\n资料来源：[CLAUDE.md:60-67]()\n\n### Storage\n\nData files live in the **project root** (not `dist/`):\n- **JSONL**: `memory.jsonl`, `memory-saved-searches.jsonl`, `memory-tag-aliases.jsonl`\n- **SQLite**: `memory.db` (set `MEMORY_STORAGE_TYPE=sqlite`)\n\n资料来源：[CLAUDE.md:37-42]()\n\n## Code Style Guidelines\n\n### TypeScript Best Practices\n\n- Follow TypeScript best practices\n- Use meaningful variable names\n- Add JSDoc comments for public methods\n- Keep functions focused and small\n- Maintain consistent indentation (2 spaces)\n\n资料来源：[CONTRIBUTING.md:21-25]()\n\n### ManagerContext Access Pattern\n\nWhen implementing tool handlers, use the ManagerContext accessors to access various managers:\n\n| Accessor | Purpose |\n|----------|---------|\n| `ctx.entityManager` | Core CRUD for graph nodes |\n| `ctx.relationManager` | Directed edges between entities |\n| `ctx.observationManager` | Facts attached to entities |\n| `ctx.searchManager` | Search operations |\n| `ctx.tagManager` | Tag management |\n| `ctx.hierarchyManager` | Parent-child trees |\n| `ctx.analyticsManager` | Graph stats and validation |\n| `ctx.compressionManager` | Duplicate detection, merge |\n| `ctx.archiveManager` | Archive operations |\n| `ctx.ioManager` | Import/Export operations |\n| `ctx.graphTraversal` | BFS/DFS path finding |\n| `ctx.semanticSearch` | Embedding similarity search |\n| `ctx.rankedSearch` | TF-IDF ranked search |\n| `ctx.storage` | Direct GraphStorage access |\n\n资料来源：[CLAUDE.md:53-55]()\n\n## Testing Guidelines\n\n### Test Structure\n\nThe project has 26 test files with 665 tests, achieving approximately 81% statement coverage.\n\n| Tier | Location | Purpose |\n|------|----------|---------|\n| Unit | `tests/unit/` | Isolated module tests (e.g., response compressor) |\n| Integration | `tests/integration/` | MCP server lifecycle tests |\n| E2E | `tests/e2e/tools/` | Per-category tool tests |\n| Root | `tests/` | Core graph operations and storage path handling |\n\n资料来源：[CLAUDE.md:71-80]()\n\n### Test Coverage\n\nCoverage verification is done via `coverage/coverage-summary.json`:\n\n| Metric | Coverage |\n|--------|----------|\n| Statements | 80.7% |\n| Lines | 81.4% |\n| Functions | 79.5% |\n| Branches | 68.3% |\n\n资料来源：[CLAUDE.md:71-72]()\n\n### Vitest Configuration\n\nTests use Vitest with custom reporting. Configuration file: `vitest.config.ts`. Coverage targets `src/**/*.ts` (excludes index barrel files).\n\n资料来源：[CLAUDE.md:81-82]()\n\n### Testing Best Practices\n\n- Test new features thoroughly\n- Include edge cases\n- Test backward compatibility\n- Verify export formats are valid\n- Test with empty graphs and large graphs\n\n资料来源：[CONTRIBUTING.md:14-18]()\n\n### Testing Notes\n\n- **Storage files**: JSONL and SQLite files created during tests are in the project root but excluded in `.gitignore` — they won't appear in `git status`.\n- **Error handling in dispatch**: `handleToolCall` catches exceptions from handlers and returns them as MCP-formatted error responses. Check MCP response `isError` field when debugging.\n\n资料来源：[CLAUDE.md:84-87]()\n\n## Adding a New Tool\n\n### Step-by-Step Process\n\n```mermaid\ngraph LR\n    A[\"1. Add schema to<br/>toolDefinitions.ts\"] --> B[\"2. Add handler to<br/>toolHandlers.ts\"]\n    B --> C[\"3. Add e2e test in<br/>tests/e2e/tools/\"]\n    C --> D[\"4. Update documentation\"]\n```\n\n### Tool Handler Pattern\n\nHandlers follow this pattern:\n\n1. **Validate arguments** with schema validation\n2. **Call manager method** via appropriate accessor\n3. **Return formatted response**\n\n```typescript\nconst TOOL_HANDLERS = {\n  tool_name: async (ctx, args) => {\n    // 1. Validate arguments\n    const param = validateWithSchema(args.param, z.string().min(1), 'Invalid param');\n    \n    // 2. Call manager method\n    const result = await getManager(ctx).method(param);\n    \n    // 3. Return formatted response\n    return formatToolResponse(result);\n  },\n};\n```\n\nIf the response can be large, wrap with `withCompression()`.\n\n资料来源：[CLAUDE.md:47-52]()\n\n### Tool Categories Overview\n\nThe project exposes 213 tools across 58 categories:\n\n| Category | Count | Key Purpose |\n|----------|-------|-------------|\n| Entity | 4 | Core CRUD for graph nodes |\n| Relation | 2 | Directed edges between entities |\n| Observation | 3 | Facts attached to entities, with normalization |\n| Search | 7 | Basic, ranked (TF-IDF), boolean, fuzzy, auto-select |\n| Intelligent Search | 3 | Hybrid multi-layer, query analysis, reflection-based |\n| Semantic Search | 3 | Embedding similarity via OpenAI or local models |\n| Saved Searches | 5 | Store and re-execute frequent queries |\n| Tag Management | 6 | Tags, bulk ops, importance scores |\n| Tag Aliases | 5 | Tag synonym/alias management |\n| Hierarchy | 9 | Parent-child trees, subtree traversal |\n| Graph Algorithms | 4 | BFS/DFS path finding, centrality, connected components |\n| Analytics | 2 | Graph stats and integrity validation |\n| Compression | 4 | Duplicate detection, merge, auto-compress, archive |\n| Import/Export | 2 | 7 export formats (xml, json-ld, etc.) |\n\n资料来源：[CLAUDE.md:33-46]()\n\n## Documentation Guidelines\n\nWhen adding features, update the following documentation:\n\n| File | Purpose |\n|------|---------|\n| `README.md` | Update with new tools/functionality |\n| `CHANGELOG.md` | Document changes |\n| `WORKFLOW.md` | Update if development process changes |\n| Usage examples | Include practical examples |\n\n资料来源：[CONTRIBUTING.md:30-34]()\n\n## Pull Request Process\n\n### PR Checklist\n\n| Step | Requirement |\n|------|-------------|\n| **Title** | Clear, descriptive summary |\n| **Description** | What changed, why it changed, how to test it |\n| **Tests** | Include test results |\n| **Documentation** | Update relevant docs |\n| **Backward Compatibility** | Confirm no breaking changes |\n\n资料来源：[CONTRIBUTING.md:36-45]()\n\n### PR Workflow\n\n```bash\n# 1. Create feature branch\ngit checkout -b feature/your-feature-name\n\n# 2. Make changes and commit\ncd c:/mcp-servers/memory-mcp\ngit add .\ngit commit -m \"Description of your changes\"\n\n# 3. Push and create PR\ngit push origin feature/your-feature-name\n# Create PR on GitHub\n```\n\n资料来源：[CONTRIBUTING.md:1-8]()\n\n## Standalone Tools\n\nThe `tools/` directory contains standalone utilities, each with its own `package.json` and buildable to Windows exes via pkg:\n\n| Tool | Purpose |\n|------|---------|\n| `chunking-for-files` | Split/merge large files for context-limited editing |\n| `compress-for-context` | CTON compression for LLM context windows |\n| `create-dependency-graph` | Generate TypeScript project dependency graphs |\n| `migrate-from-jsonl-to-sqlite` | Convert between JSONL and SQLite formats |\n\n资料来源：[CLAUDE.md:44-51]()\n\n## Publishing to npm\n\n```bash\n# Token with \"bypass 2FA\" required — classic tokens are revoked\nnpm config set //registry.npmjs.org/:_authToken=$(cat c:\\mcp-servers\\npm_key.txt)\nnpm publish --access public\n```\n\n**Important Notes:**\n- The `prepare` script auto-builds, so separate `npm run build` is not needed before publish\n- Always bump version in `package.json` before publishing\n- Verify tarball contents before publishing\n\n资料来源：[CLAUDE.md:52-58]()\n\n### Verify Tarball Contents\n\n```bash\nnpm pack --dry-run 2>&1 | grep -E \"jsonl|\\.db|total files|package size\"\n```\n\n资料来源：[CLAUDE.md:59]()\n\n## Reporting Issues\n\n| Type | Action |\n|------|--------|\n| **Bug Reports** | Open an issue with detailed reproduction steps |\n| **Feature Requests** | Open an issue describing the use case |\n| **Questions** | Check existing issues or open a new one |\n\nThis project follows the [Model Context Protocol community guidelines](https://modelcontextprotocol.io/community/communication).\n\n资料来源：[CONTRIBUTING.md:60-65]()\n\n## License\n\nBy contributing, you agree that your contributions will be licensed under the MIT License.\n\n资料来源：[CONTRIBUTING.md:68-70]()\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: danielsimonjr/memory-mcp\n\nSummary: Found 6 potential pitfall items; 0 are high/blocking. Highest priority: capability - 能力判断依赖假设.\n\n## 1. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | README/documentation is current enough for a first validation pass.\n\n## 2. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | last_activity_observed missing\n\n## 3. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium\n\n## 4. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium\n\n## 5. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | issue_or_pr_quality=unknown\n\n## 6. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | release_recency=unknown\n\n<!-- canonical_name: danielsimonjr/memory-mcp; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "Human Manual"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log\n\nProject: danielsimonjr/memory-mcp\n\nSummary: Found 6 potential pitfall items; 0 are high/blocking. Highest priority: capability - 能力判断依赖假设.\n\n## 1. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- Evidence: capability.assumptions | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | README/documentation is current enough for a first validation pass.\n\n## 2. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | last_activity_observed missing\n\n## 3. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- Evidence: downstream_validation.risk_items | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium\n\n## 4. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- Evidence: risks.scoring_risks | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | no_demo; severity=medium\n\n## 5. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | issue_or_pr_quality=unknown\n\n## 6. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- Evidence: evidence.maintainer_signals | github_repo:1093926095 | https://github.com/danielsimonjr/memory-mcp | release_recency=unknown\n",
      "summary": "Identity, installation, configuration, runtime, and safety pitfalls before user trial.",
      "title": "Pitfall Log"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# memory-mcp - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for danielsimonjr/memory-mcp.\n\nProject:\n- Name: memory-mcp\n- Repository: https://github.com/danielsimonjr/memory-mcp\n- Summary: Enhanced Model Context Protocol memory server with timestamps, tags, importance, search, and export capabilities\n- Host target: mcp_host\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Enhanced Model Context Protocol memory server with timestamps, tags, importance, search, and export capabilities\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Enhanced Model Context Protocol memory server with timestamps, tags, importance, search, and export capabilities\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. getting-started: Getting Started. Produce one small intermediate artifact and wait for confirmation.\n2. architecture-overview: Architecture Overview. Produce one small intermediate artifact and wait for confirmation.\n3. storage-backends: Storage Backends. Produce one small intermediate artifact and wait for confirmation.\n4. entity-model: Entity-Relation-Observation Model. Produce one small intermediate artifact and wait for confirmation.\n5. tool-reference: Tool Reference. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/danielsimonjr/memory-mcp\n- https://github.com/danielsimonjr/memory-mcp#readme\n- README.md\n- package.json\n- src/index.ts\n- src/server/MCPServer.ts\n- docs/architecture/ARCHITECTURE.md\n- docs/architecture/COMPONENTS.md\n- docs/architecture/dependency-graph.json\n- tools/migrate-from-jsonl-to-sqlite/migrate-from-jsonl-to-sqlite.ts\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start\n\nProject: danielsimonjr/memory-mcp\n\n## Official Entry Points\n\n### Node.js / npm · 官方安装入口\n\n```bash\nnpm install -g @danielsimonjr/memory-mcp\n```\n\nSource：https://github.com/danielsimonjr/memory-mcp#readme\n\n## Sources\n\n- repo: https://github.com/danielsimonjr/memory-mcp\n- docs: https://github.com/danielsimonjr/memory-mcp#readme\n",
      "summary": "Entry points extracted from official README or installation documentation.",
      "title": "Quick Start"
    }
  },
  "validation_id": "dval_34874bd3c6f3464c8fd118ee38eb5781"
}
