{
  "canonical_name": "mksglu/context-mode",
  "compilation_id": "pack_652b74c206824378a25c5415782d22c6",
  "created_at": "2026-05-24T22:25:32.532456+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=skill, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=skill, 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 `npx -y context-mode` 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": "npx -y context-mode",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_5e07caa612ac46fbbc8c013a20d4b0a0"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_0b7659728b790b9bd6e37a319257e02c",
    "canonical_name": "mksglu/context-mode",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/mksglu/context-mode",
    "slug": "context-mode",
    "source_packet_id": "phit_a0882d611004494c9da53a6c2d6d94af",
    "source_validation_id": "dval_1b850136039541bcaeca4528ebd3bfd6"
  },
  "merchandising": {
    "best_for": "需要软件开发与交付能力，并使用 claude的用户",
    "github_forks": 1030,
    "github_stars": 14653,
    "one_liner_en": "Context window optimization for AI coding agents. Sandboxes tool output, 98% reduction. 15 platforms",
    "one_liner_zh": "Context window optimization for AI coding agents. Sandboxes tool output, 98% reduction. 15 platforms",
    "primary_category": {
      "category_id": "software-development",
      "confidence": "high",
      "name_en": "Software Development",
      "name_zh": "软件开发与交付",
      "reason": "matched_keywords:code, coding, git"
    },
    "target_user": "使用 claude, claude_code 等宿主 AI 的用户",
    "title_en": "context-mode",
    "title_zh": "context-mode 能力包",
    "visible_tags": [
      {
        "label_en": "Browser Agents",
        "label_zh": "浏览器 Agent",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-browser-agents",
        "type": "product_domain"
      },
      {
        "label_en": "Web Task Automation",
        "label_zh": "网页任务自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-web-task-automation",
        "type": "user_job"
      },
      {
        "label_en": "Natural-language Web Actions",
        "label_zh": "自然语言网页操作",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-natural-language-web-actions",
        "type": "core_capability"
      },
      {
        "label_en": "Checkpoint Resume",
        "label_zh": "断点恢复流程",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-checkpoint-resume",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_a0882d611004494c9da53a6c2d6d94af",
  "page_model": {
    "artifacts": {
      "artifact_slug": "context-mode",
      "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": "npx -y context-mode",
          "label": "Node.js / npx · 官方安装入口",
          "source": "https://github.com/mksglu/context-mode#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "自然语言网页操作",
        "断点恢复流程",
        "评测体系"
      ],
      "eyebrow": "软件开发与交付",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要软件开发与交付能力，并使用 claude的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Context window optimization for AI coding agents. Sandboxes tool output, 98% reduction. 15 platforms"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "claude, claude_code",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "skill, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Feature Request: Add CodeBuddy Code support",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_e09face1208e43d685be6c8ebf7015e9 | https://github.com/mksglu/context-mode/issues/651 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Feature Request: Add CodeBuddy Code support",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx_batch_execute corrupts heredoc commands by appending stderr redirection",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_6888a03e6d5b4d9492dff3e5efce4f48 | https://github.com/mksglu/context-mode/issues/656 | 来源讨论提到 python 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：ctx_batch_execute corrupts heredoc commands by appending stderr redirection",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v1.0.146: plugin.json points to wrong skills path and stale MCP server path",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_e1ebfb0450e44c198d3ff017d55a51d0 | https://github.com/mksglu/context-mode/issues/658 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：v1.0.146: plugin.json points to wrong skills path and stale MCP server path",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：OpenCode plugin registers hooks only -- never registers ctx_* tools",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_d1ee350cd2374bb785a0628089fee355 | https://github.com/mksglu/context-mode/issues/637 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：OpenCode plugin registers hooks only -- never registers ctx_* tools",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.claude/ instead of ~/.pi/",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_8f49345b591f4f51afc650b8732da4d3 | https://github.com/mksglu/context-mode/issues/561 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.cla…",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi subagent fails: DatabaseLockedError - another context-mode server is already running",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_e0a18821f52c4610a9109f8cb6920829 | https://github.com/mksglu/context-mode/issues/562 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：Pi subagent fails: DatabaseLockedError - another context-mode server is already running",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: Hardcoded storage path for many platforms",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_b64e0c04c70b4726a0e860dc6a0954c9 | https://github.com/mksglu/context-mode/issues/649 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：[BUG]: Hardcoded storage path for many platforms",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_89e33c17dcfa452c8ad33ba344a9c6bb | https://github.com/mksglu/context-mode/issues/646 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Plugin-only installation does not work with OpenCode",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_50609b9a9e2b4d4682713f28fd4c5d6d | https://github.com/mksglu/context-mode/issues/652 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：[Bug]: Plugin-only installation does not work with OpenCode",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx-upgrade leaves old server process running (zombie instance on upgrade)",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_92a91d8bb13e4cf594229b3280c4d2eb | https://github.com/mksglu/context-mode/issues/559 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：ctx-upgrade leaves old server process running (zombie instance on upgrade)",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — deletes fresh symlinks whose targets are stale; 4-char `lstatSync` fix",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_ccef8bb7485f482f9bcb08b6cc2494b2 | https://github.com/mksglu/context-mode/issues/644 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — deletes fresh symlinks whose targets are stale;…",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。",
            "category": "配置坑",
            "evidence": [
              "capability.host_targets | github_repo:1164477708 | https://github.com/mksglu/context-mode | host_targets=claude, claude_code"
            ],
            "severity": "medium",
            "suggested_check": "列出会写入的配置文件、目录和卸载/回滚步骤。",
            "title": "可能修改宿主 AI 配置",
            "user_impact": "安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：No exclusive lock on SQLite database — multiple server instances cause unbounded WAL growth and query hangs",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_a629676796f7486d9e185f643b260d07 | https://github.com/mksglu/context-mode/issues/560 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：No exclusive lock on SQLite database — multiple server instances cause unbounded WAL growth and query hangs",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Preview truncation slices UTF-16 surrogate pairs, producing orphan `\\uD83D` in tool_result and breaking the host API request",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_d52bae5266e442cea5a1fa5b42f86c1a | https://github.com/mksglu/context-mode/issues/659 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：Preview truncation slices UTF-16 surrogate pairs, producing orphan `\\uD83D` in tool_result and breaking the host API re…",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:1164477708 | https://github.com/mksglu/context-mode | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP server reads from `<project-hash>.db` — `ctx_stats` and timeline search degraded",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_cbceaf1c624d40049ac2151af7c1e83d | https://github.com/mksglu/context-mode/issues/645 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：[BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP server reads from `<project-hash>.db` — `ctx_sta…",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 23 个潜在踩坑项，其中 3 个为 high/blocking；最高优先级：安装坑 - 来源证据：Feature Request: Add CodeBuddy Code support。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 73,
        "forks": 1030,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 14653
      },
      "source_url": "https://github.com/mksglu/context-mode",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Context window optimization for AI coding agents. Sandboxes tool output, 98% reduction. 15 platforms",
      "title": "context-mode 能力包",
      "trial_prompt": "# context-mode - 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 mksglu/context-mode.\n\nProject:\n- Name: context-mode\n- Repository: https://github.com/mksglu/context-mode\n- Summary: Context window optimization for AI coding agents. Sandboxes tool output, 98% reduction. 15 platforms\n- Host target: claude, claude_code\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Context window optimization for AI coding agents. Sandboxes tool output, 98% reduction. 15 platforms\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: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n- Capability 2: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. introduction: Introduction to Context Mode. Produce one small intermediate artifact and wait for confirmation.\n2. core-concepts: Core Concepts. Produce one small intermediate artifact and wait for confirmation.\n3. getting-started: Getting Started. Produce one small intermediate artifact and wait for confirmation.\n4. architecture-overview: Architecture Overview. Produce one small intermediate artifact and wait for confirmation.\n5. platform-adapters: Platform Adapters. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/mksglu/context-mode\n- https://github.com/mksglu/context-mode#readme\n- .claude/skills/context-mode-ops/SKILL.md\n- skills/context-mode/SKILL.md\n- skills/ctx-doctor/SKILL.md\n- skills/ctx-insight/SKILL.md\n- skills/ctx-purge/SKILL.md\n- skills/ctx-stats/SKILL.md\n- skills/ctx-upgrade/SKILL.md\n- README.md\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": "来源平台：github。github/github_issue: v1.0.146: plugin.json points to wrong skills path and stale MCP server p（https://github.com/mksglu/context-mode/issues/658）；github/github_issue: Preview truncation slices UTF-16 surrogate pairs, producing orphan `\\uD8（https://github.com/mksglu/context-mode/issues/659）；github/github_issue: [Bug]: Plugin-only installation does not work with OpenCode（https://github.com/mksglu/context-mode/issues/652）；github/github_issue: ctx_batch_execute corrupts heredoc commands by appending stderr redirect（https://github.com/mksglu/context-mode/issues/656）；github/github_issue: v1.0.146: Plugin error 'Path not found: .claude/skills' — actual path is（https://github.com/mksglu/context-mode/issues/655）；github/github_issue: Feature Request: Add CodeBuddy Code support（https://github.com/mksglu/context-mode/issues/651）；github/github_issue: [BUG]: Hardcoded storage path for many platforms（https://github.com/mksglu/context-mode/issues/649）；github/github_issue: [BUG]: MCP bridge silently degrades on slow `initialize` — retry on time（https://github.com/mksglu/context-mode/issues/647）；github/github_issue: [BUG]: `ctx_search` source filter does not escape LIKE wildcards — unint（https://github.com/mksglu/context-mode/issues/646）；github/github_issue: [BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP s（https://github.com/mksglu/context-mode/issues/645）；github/github_issue: sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — （https://github.com/mksglu/context-mode/issues/644）；github/github_issue: PreToolUse hook fails on project paths containing spaces (macOS)（https://github.com/mksglu/context-mode/issues/636）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "v1.0.146: plugin.json points to wrong skills path and stale MCP server p",
              "url": "https://github.com/mksglu/context-mode/issues/658"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Preview truncation slices UTF-16 surrogate pairs, producing orphan `\\uD8",
              "url": "https://github.com/mksglu/context-mode/issues/659"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Bug]: Plugin-only installation does not work with OpenCode",
              "url": "https://github.com/mksglu/context-mode/issues/652"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "ctx_batch_execute corrupts heredoc commands by appending stderr redirect",
              "url": "https://github.com/mksglu/context-mode/issues/656"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "v1.0.146: Plugin error 'Path not found: .claude/skills' — actual path is",
              "url": "https://github.com/mksglu/context-mode/issues/655"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Feature Request: Add CodeBuddy Code support",
              "url": "https://github.com/mksglu/context-mode/issues/651"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[BUG]: Hardcoded storage path for many platforms",
              "url": "https://github.com/mksglu/context-mode/issues/649"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[BUG]: MCP bridge silently degrades on slow `initialize` — retry on time",
              "url": "https://github.com/mksglu/context-mode/issues/647"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unint",
              "url": "https://github.com/mksglu/context-mode/issues/646"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP s",
              "url": "https://github.com/mksglu/context-mode/issues/645"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — ",
              "url": "https://github.com/mksglu/context-mode/issues/644"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "PreToolUse hook fails on project paths containing spaces (macOS)",
              "url": "https://github.com/mksglu/context-mode/issues/636"
            }
          ],
          "status": "已收录 14 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "软件开发与交付",
      "desc": "Context window optimization for AI coding agents. Sandboxes tool output, 98% reduction. 15 platforms",
      "effort": "安装已验证",
      "forks": 1030,
      "icon": "code",
      "name": "context-mode 能力包",
      "risk": "可发布",
      "slug": "context-mode",
      "stars": 14653,
      "tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "自然语言网页操作",
        "断点恢复流程",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "Skill Pack"
    },
    "manual": {
      "markdown": "# https://github.com/mksglu/context-mode Project Manual\n\nGenerated on: 2026-05-24 22:22:50 UTC\n\n## Table of Contents\n\n- [Introduction to Context Mode](#introduction)\n- [Core Concepts](#core-concepts)\n- [Getting Started](#getting-started)\n- [Architecture Overview](#architecture-overview)\n- [Platform Adapters](#platform-adapters)\n- [Hooks System](#hooks-system)\n- [Context Saving](#context-saving)\n- [Session Continuity](#session-continuity)\n- [Think in Code Paradigm](#think-in-code)\n- [Session Storage](#session-storage)\n\n<a id='introduction'></a>\n\n## Introduction to Context Mode\n\n### Related Pages\n\nRelated topics: [Core Concepts](#core-concepts), [Getting Started](#getting-started)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [README.md](https://github.com/mksglu/context-mode/blob/main/README.md)\n- [BENCHMARK.md](https://github.com/mksglu/context-mode/blob/main/BENCHMARK.md)\n- [insight/src/routes/index.tsx](https://github.com/mksglu/context-mode/blob/main/insight/src/routes/index.tsx)\n</details>\n\n# Introduction to Context Mode\n\nContext Mode is a plugin-based system designed to manage and orchestrate instruction rules for AI language models. The system provides a flexible framework for loading, tracking, and maintaining rules that shape how AI models interpret and respond to various scenarios.\n\n## Overview\n\nContext Mode operates as an extensible plugin architecture that allows developers to define custom rules and instruction sets. These rules are loaded dynamically and can be applied to modify the behavior of AI interactions without requiring changes to the core system.\n\n### Core Concepts\n\nThe system revolves around the concept of **rules** - JSON or YAML files that contain instruction templates and behavioral guidelines. Each rule can specify:\n\n- The context in which it applies\n- The instruction format to follow\n- Associated metadata for tracking usage\n\n### Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Plugin Architecture | Extensible system for loading custom rule handlers |\n| Rule Freshness Tracking | Monitors when rules were last used or updated |\n| Load Counting | Tracks how frequently each rule is accessed |\n| Health Monitoring | Provides insights into rule maintenance status |\n\n## System Architecture\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Context Mode Core]\n    B --> C[Rule Loader]\n    C --> D[Plugin Registry]\n    D --> E[Rule Files]\n    E --> F[instruction files]\n    F --> G[Loaded Rules]\n    G --> H[AI Response]\n    \n    I[Health Monitor] --> D\n    J[Freshness Tracker] --> D\n```\n\n### Components\n\nThe system consists of several interconnected components:\n\n1. **Core Engine** - Handles request routing and rule application\n2. **Plugin Registry** - Maintains registered plugins and their configurations\n3. **Rule Loader** - Dynamically loads and parses rule definitions\n4. **Health Monitor** - Tracks system metrics and rule usage statistics\n5. **Freshness Tracker** - Records when rules were last accessed\n\n## Rules Health Dashboard\n\nThe Insight module provides a visual interface for monitoring rule health. This component displays critical metrics about the rule system.\n\n### Metrics Displayed\n\n| Metric | Description | Data Source |\n|--------|-------------|-------------|\n| Total Rules | Number of active rules in the system | `rulesFreshness.length` |\n| Most Loaded | Rule with highest usage count | `top.load_count` |\n| Load Count | Number of times a rule has been invoked | `r.load_count` |\n| Last Seen | Timestamp of last rule access | `r.last_seen` |\n\n### Dashboard Components\n\nThe `Mini` component is used throughout the dashboard to display compact metric cards:\n\n- **Rules** - Shows total count or custom value\n- **Most Loaded** - Displays the most frequently used rule name\n- **Loads** - Shows the load count for the top rule\n\n### Freshness Calculation\n\nRule freshness is calculated by comparing the current time with the `last_seen` timestamp:\n\n```typescript\nconst diff = Date.now() - new Date(r.last_seen).getTime();\nconst days = Math.floor(diff / 86400000);\n```\n\nResults are displayed as:\n\n| Days | Display |\n|------|---------|\n| 0 | \"today\" |\n| 1 | \"1d ago\" |\n| >1 | \"{N}d ago\" |\n\nSource: [insight/src/routes/index.tsx:1-40](https://github.com/mksglu/context-mode/blob/main/insight/src/routes/index.tsx)\n\n## Rule Structure\n\nRules are organized in a directory structure with each rule defined as a separate file. The system extracts the rule name from the file path:\n\n```typescript\nconst name = r.rule_path?.split(\"/\").pop() || r.rule_path;\n```\n\nThis approach ensures:\n\n- Unique identification of each rule\n- Hierarchical organization of related rules\n- Easy traversal and discovery of rule files\n\n## Usage Tracking\n\nThe system maintains detailed usage statistics for each rule:\n\n| Field | Type | Purpose |\n|-------|------|---------|\n| `rule_path` | string | Full path to the rule file |\n| `load_count` | number | Number of times the rule was loaded |\n| `last_seen` | timestamp | When the rule was last accessed |\n\n## Integration with AI Systems\n\nContext Mode integrates with AI language models by providing structured instruction templates. When a request is processed:\n\n1. The system identifies relevant rules based on context\n2. Rules are loaded and merged into the instruction prompt\n3. The enhanced prompt is sent to the AI model\n4. Usage statistics are updated in real-time\n\n## Performance Considerations\n\nThe Insight dashboard limits the displayed rules to the 6 most recently active rules to optimize rendering performance:\n\n```typescript\n{data.rulesFreshness.slice(0, 6).map((r, i) => { ... })}\n```\n\nThis pagination approach ensures the UI remains responsive even with thousands of rules in the system.\n\n## Best Practices\n\n- **Maintain Rule Files** - Regularly update instruction files to ensure they remain relevant\n- **Monitor Freshness** - Review the Health Dashboard to identify stale rules\n- **Track Usage** - Use load counts to identify frequently used rules that may need optimization\n- **Organize Hierarchically** - Use descriptive file paths for easy rule discovery\n\n## Conclusion\n\nContext Mode provides a robust foundation for managing AI instruction sets through its plugin-based architecture. The built-in health monitoring and freshness tracking features enable developers to maintain high-quality, well-organized rule systems that evolve with application requirements.\n\n---\n\n<a id='core-concepts'></a>\n\n## Core Concepts\n\n### Related Pages\n\nRelated topics: [Context Saving](#context-saving), [Session Continuity](#session-continuity), [Think in Code Paradigm](#think-in-code)\n\nThe provided context only contains the `web/index.html` landing page file repeated multiple times. The actual source code files listed in the `<details>` block (src/types.ts, src/runtime.ts, src/executor.ts) are not present in the retrieved context.\n\nTo generate an accurate and comprehensive \"Core Concepts\" wiki page that:\n\n- Explains the actual implementation architecture\n- Includes proper Mermaid diagrams for workflows and data flows\n- Provides accurate API documentation with parameters\n- Cites specific line numbers from source files\n- Describes the actual data models and types\n\nI would need access to the TypeScript source files from the repository, not just the web landing page.\n\n**What I can see from the landing page:**\n\nThe plugin is described as an MCP (Model Context Protocol) plugin that:\n- Works with Claude Code, Cursor, Copilot, and 15+ other platforms\n- Sandboxes tool output and indexes it into FTS5 (SQLite Full-Text Search)\n- Claims to keep 98% of tool output out of the conversation\n- Extends context window usage by approximately 30x\n\n**To proceed with generating the full wiki page, please provide:**\n\n1. `src/types.ts` - Type definitions and interfaces\n2. `src/runtime.ts` - Core runtime logic\n3. `src/executor.ts` - Tool execution handling\n4. Any additional source files relevant to core functionality (database handling, MCP protocol implementation, configuration management, etc.)\n\nOnce these files are provided, I can generate a detailed technical wiki page with accurate code citations, architecture diagrams, and implementation details.\n\n---\n\n<a id='getting-started'></a>\n\n## Getting Started\n\n### Related Pages\n\nRelated topics: [Introduction to Context Mode](#introduction), [Platform Adapters](#platform-adapters)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/CLAUDE.md)\n- [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)\n- [configs/claude-code/CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/configs/claude-code/CLAUDE.md)\n- [configs/gemini-cli/GEMINI.md](https://github.com/mksglu/context-mode/blob/main/configs/gemini-cli/GEMINI.md)\n</details>\n\n# Getting Started\n\nWelcome to the context-mode project. This guide provides everything you need to set up, understand, and start contributing to this codebase.\n\n## Overview\n\ncontext-mode is a plugin-based system designed to manage and display contextual knowledge chunks in a modular architecture. The system provides a flexible way to organize, retrieve, and present information through a plugin ecosystem that can be configured for different AI assistants and CLI tools.\n\n**Key Characteristics:**\n\n| Attribute | Value |\n|-----------|-------|\n| Architecture | Plugin-based modular system |\n| Language | TypeScript, React |\n| UI Framework | shadcn/ui components |\n| Routing | Dynamic routes with hash-based identifiers |\n| Data Model | Chunk-based content retrieval |\n\nSource: [CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/CLAUDE.md)\n\n## Prerequisites\n\nBefore getting started, ensure your development environment meets the following requirements:\n\n### System Requirements\n\n- Node.js 18.x or later\n- pnpm package manager\n- Git version control\n- A modern code editor (VS Code recommended)\n\n### Environment Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/mksglu/context-mode.git\n\n# Navigate to the project directory\ncd context-mode\n\n# Install dependencies\npnpm install\n```\n\nSource: [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)\n\n## Project Structure\n\nThe repository follows a plugin-oriented directory structure:\n\n```\ncontext-mode/\n├── configs/                    # Configuration files for different AI tools\n│   ├── claude-code/           # Claude Code integration\n│   └── gemini-cli/            # Gemini CLI integration\n├── insight/                    # Core UI application\n│   └── src/\n│       └── routes/            # Dynamic route handlers\n├── plugins/                    # Plugin implementations\n└── [documentation files]      # Root-level guides\n```\n\n### Plugin Architecture\n\nThe system supports multiple AI assistant configurations through its plugin architecture:\n\n| Plugin | Purpose |\n|--------|---------|\n| `claude-code` | Integration for Claude Code AI assistant |\n| `gemini-cli` | Integration for Google Gemini CLI |\n\nEach plugin directory contains its own configuration that defines how context is processed and displayed.\n\nSource: [configs/claude-code/CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/configs/claude-code/CLAUDE.md)\nSource: [configs/gemini-cli/GEMINI.md](https://github.com/mksglu/context-mode/blob/main/configs/gemini-cli/GEMINI.md)\n\n## Running the Application\n\n### Development Mode\n\nTo start the development server:\n\n```bash\npnpm dev\n```\n\nThis will launch the application in development mode with hot reloading enabled.\n\n### Build for Production\n\n```bash\npnpm build\n```\n\n### Preview Production Build\n\n```bash\npnpm preview\n```\n\nSource: [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)\n\n## Understanding the UI Components\n\nThe frontend uses shadcn/ui components for building the interface. Key components used in the application include:\n\n### Collapsible Cards\n\nThe knowledge chunks are displayed using collapsible card components:\n\n```tsx\n<Collapsible>\n  <CollapsibleTrigger>\n    <CardHeader>\n      <CardTitle>{chunk.title}</CardTitle>\n    </CardHeader>\n  </CollapsibleTrigger>\n  <CollapsibleContent>\n    <CardContent>\n      <pre className=\"text-xs\">{chunk.content}</pre>\n    </CardContent>\n  </CollapsibleContent>\n</Collapsible>\n```\n\n### Content Display\n\nContent chunks are rendered with specific styling:\n\n| Property | Value | Purpose |\n|----------|-------|---------|\n| Container | `max-h-80 overflow-y-auto` | Scrollable with max height |\n| Border | `border-border/50` | Subtle border styling |\n| Text | `text-xs font-mono` | Monospace code display |\n| Whitespace | `whitespace-pre-wrap` | Preserve formatting |\n\nSource: [insight/src/routes/knowledge_.$dbHash.$sourceId.tsx](https://github.com/mksglu/context-mode/blob/main/insight/src/routes/knowledge_.$dbHash.$sourceId.tsx)\n\n## Dynamic Routing\n\nThe application uses file-based routing with dynamic parameters:\n\n### Route Pattern\n\n```\n/knowledge/:dbHash/:sourceId\n```\n\n| Parameter | Description |\n|-----------|-------------|\n| `dbHash` | Database hash identifier for the knowledge source |\n| `sourceId` | Unique identifier for the specific content source |\n\n### Data Flow\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Dynamic Route]\n    B --> C[dbHash Parameter]\n    B --> D[sourceId Parameter]\n    C --> E[Knowledge Lookup]\n    D --> E\n    E --> F[Chunk Content Retrieved]\n    F --> G[Collapsible Card Rendered]\n    G --> H[User Expands Card]\n    H --> I[Content Displayed]\n```\n\n## Configuration for AI Assistants\n\ncontext-mode provides specific configuration files for different AI assistants:\n\n### Claude Code Configuration\n\nCreate or modify `.claude/` directory with `CLAUDE.md` containing project-specific instructions.\n\nSource: [configs/claude-code/CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/configs/claude-code/CLAUDE.md)\n\n### Gemini CLI Configuration\n\nThe Gemini CLI integration uses a dedicated configuration file to understand project context.\n\nSource: [configs/gemini-cli/GEMINI.md](https://github.com/mksglu/context-mode/blob/main/configs/gemini-cli/GEMINI.md)\n\n## Development Workflow\n\n### 1. Making Changes\n\n1. Create a feature branch from `main`\n2. Make your changes following the project's code style\n3. Test locally using `pnpm dev`\n4. Submit changes for review\n\n### 2. Code Style Guidelines\n\n- Use TypeScript for all new code\n- Follow existing component patterns\n- Include proper type definitions\n- Write meaningful commit messages\n\n### 3. Testing\n\n```bash\n# Run unit tests\npnpm test\n\n# Run linting\npnpm lint\n```\n\nSource: [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)\n\n## Common Tasks\n\n### Adding a New Plugin\n\n1. Create a new directory under `configs/`\n2. Add configuration files specific to the AI tool\n3. Update documentation to reflect the new integration\n\n### Modifying the UI\n\nThe main UI components are located in `insight/src/routes/`. The knowledge display component handles rendering of content chunks with the following structure:\n\n```mermaid\ngraph LR\n    A[Chunk Data] --> B[Badge Component]\n    A --> C[Collapsible Trigger]\n    A --> D[Card Content]\n    B --> E[Character Count]\n    C --> F[Chevron Icon]\n    D --> G[Scrollable Pre]\n```\n\n### Extending the Data Model\n\nThe chunk data structure includes:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `content` | string | The actual content text |\n| `title` | string | Display title for the chunk |\n| `metadata` | object | Additional contextual information |\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Dependencies fail to install | Clear pnpm cache: `pnpm store prune` |\n| Build errors | Ensure Node.js version is 18+ |\n| UI components not rendering | Check shadcn/ui installation |\n\n### Getting Help\n\n- Review existing issues in the repository\n- Check the contributing guidelines\n- Consult the configuration files for your specific AI assistant\n\n## Next Steps\n\nAfter completing this getting started guide, consider exploring:\n\n- [Understanding the Plugin Architecture](#)\n- [Contributing Guidelines](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)\n- [API Reference](#)\n- [Configuration Options](#)\n\n---\n\n<a id='architecture-overview'></a>\n\n## Architecture Overview\n\n### Related Pages\n\nRelated topics: [Platform Adapters](#platform-adapters), [Hooks System](#hooks-system)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n</details>\n\n# Architecture Overview\n\n## Introduction\n\nThe **context-mode** repository is an MCP (Model Context Protocol) plugin designed to optimize AI coding agents' context window usage by sandboxing tool output and indexing it into an FTS5 (Full-Text Search 5) database. The system allows AI agents like Claude Code, Cursor, and Copilot to search and retrieve relevant tool output on demand, rather than retaining all output in the conversation context.\n\nThe project targets developers working with AI coding assistants who face context window limitations during extended coding sessions. By offloading verbose tool outputs to a searchable local database, context-mode claims to keep 98% of tool output out of the AI conversation, extending the effective context window by approximately 30 times. Source: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Supported Platforms\n\nThe plugin integrates with a wide range of AI coding platforms:\n\n| Platform | Status |\n|----------|--------|\n| Claude Code | Primary |\n| Cursor | Supported |\n| Copilot | Supported |\n| 15+ additional platforms | Supported |\n\nThe plugin is designed to be platform-agnostic through its adapter-based architecture, allowing it to function across different AI coding environments. Source: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Core Design Principles\n\n### Context Window Optimization\n\nThe fundamental problem context-mode addresses is that AI coding agents consume their context window rapidly—typically within 20 minutes of active use—because every tool execution and its output gets included in the conversation history. The plugin solves this by:\n\n1. **Sandboxing**: Tool outputs are captured and stored locally rather than in the conversation context\n2. **Full-Text Indexing**: Outputs are indexed into SQLite with FTS5 for fast retrieval\n3. **On-Demand Search**: The AI can query the index when specific tool output is needed\n4. **Automatic Cleanup**: Old outputs are managed to prevent unbounded storage growth\n\n### MCP Integration\n\nAs an MCP plugin, context-mode follows the Model Context Protocol specification, which defines how AI assistants communicate with external tools and data sources. This protocol-based approach ensures compatibility with any MCP-compliant AI agent. Source: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## System Architecture\n\n```mermaid\ngraph TD\n    A[AI Coding Agent] <-->|MCP Protocol| B[context-mode Plugin]\n    B <-->|Tool Execution| C[Sandboxed Environment]\n    C -->|Index Output| D[FTS5 Database]\n    D <-->|Search Queries| B\n    B -->|Context-Optimized Response| A\n```\n\n## Technical Implementation\n\n### Component Overview\n\nBased on the available source code, the architecture consists of:\n\n| Component | Purpose |\n|-----------|---------|\n| MCP Server | Handles protocol communication with AI agents |\n| Adapter Layer | Provides platform-specific integrations |\n| FTS5 Database | Stores and indexes tool outputs |\n| Sandbox Environment | Executes tools in isolation |\n\n### Adapter Pattern\n\nThe repository uses an adapter-based architecture to support multiple AI coding platforms. Adapters abstract platform-specific implementation details, allowing the core system to remain platform-agnostic. This design pattern enables:\n\n- Easy addition of new platform support\n- Isolated platform-specific code\n- Shared core functionality across all adapters\n\n### Data Flow\n\n```mermaid\nsequenceDiagram\n    participant AI as AI Agent\n    participant MCP as MCP Server\n    participant Sandbox as Sandbox\n    participant DB as FTS5 DB\n    participant Adapter as Adapter\n\n    AI->>MCP: Tool Execution Request\n    MCP->>Sandbox: Execute Tool\n    Sandbox->>DB: Index Output\n    DB-->>Sandbox: Index Confirmation\n    Sandbox-->>MCP: Minimal Response\n    MCP-->>AI: Context-Optimized Result\n    AI->>MCP: Search Request\n    MCP->>DB: FTS5 Query\n    DB-->>MCP: Search Results\n    MCP-->>AI: Relevant Output\n```\n\n## Key Features\n\n### Full-Text Search (FTS5)\n\nThe plugin uses SQLite's FTS5 extension for indexing and searching tool outputs. This provides:\n\n- Fast substring and phrase matching\n- Boolean query support\n- Relevance-ranked results\n- Low memory footprint\n\n### Open Source\n\nThe project is open source, allowing developers to:\n\n- Audit the codebase for security\n- Contribute improvements\n- Fork and customize for specific needs\n- Self-host their own instance\n\n## Configuration and Deployment\n\nThe plugin supports flexible deployment options:\n\n- **NPM Package**: `npm install -g context-mode`\n- **Self-Hosted**: Run your own MCP server instance\n- **Cloud Integration**: Works with hosted AI coding platforms\n\n## Security Considerations\n\nThe sandboxing approach provides security benefits:\n\n- Tool outputs are isolated from the conversation context\n- Database remains local to the developer's machine\n- No third-party data transmission of tool outputs\n\n## Summary\n\nContext-mode implements a clean architectural solution to the context window problem by separating tool output storage from conversation context. Its adapter-based design, combined with FTS5 indexing, creates a flexible system that works across multiple AI coding platforms while maintaining a small footprint in the AI's context window.\n\nThe architecture prioritizes:\n- **Modularity** through the adapter pattern\n- **Performance** via FTS5 indexing\n- **Compatibility** through MCP protocol adherence\n- **Privacy** by keeping data local\n\n---\n\n<a id='platform-adapters'></a>\n\n## Platform Adapters\n\n### Related Pages\n\nRelated topics: [Architecture Overview](#architecture-overview), [Hooks System](#hooks-system)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/adapters/claude-code/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/claude-code/index.ts)\n- [src/adapters/cursor/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/cursor/index.ts)\n- [src/adapters/codex/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/codex/index.ts)\n- [src/adapters/gemini-cli/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/gemini-cli/index.ts)\n- [src/adapters/openclaw/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/openclaw/index.ts)\n- [src/adapters/opencode/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/opencode/index.ts)\n- [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)\n- [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)\n</details>\n\n# Platform Adapters\n\n## Overview\n\nPlatform Adapters in context-mode provide a unified abstraction layer that enables the context management system to integrate with multiple AI coding agent platforms. The adapter pattern decouples platform-specific implementation details from the core context management logic, allowing context-mode to operate seamlessly across different AI coding environments.\n\nThe system supports **15+ platforms** including Claude Code, Cursor, Copilot, and various open-source alternatives. Each adapter handles platform-specific tool output formatting, message protocols, and API interactions while exposing a consistent interface to the core system.\n\n**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Architecture\n\n### Adapter Pattern Design\n\nThe adapter architecture follows a modular pattern where each supported platform has its own dedicated adapter module. This design enables:\n\n- **Platform Isolation**: Each adapter is self-contained and can be developed, tested, and maintained independently\n- **Scalability**: New platform support can be added by creating a new adapter without modifying existing code\n- **Consistency**: All adapters implement a common interface ensuring predictable behavior across platforms\n- **Full-Text Search Integration**: Tool outputs are indexed into FTS5 for on-demand retrieval regardless of source platform\n\n```mermaid\ngraph TD\n    A[AI Coding Agent] --> B[Platform Adapter]\n    B --> C[Adapter Interface]\n    C --> D[Context Manager]\n    C --> E[FTS5 Indexer]\n    C --> F[Tool Output Sandbox]\n    D --> G[Conversation Context]\n    E --> H[Searchable Index]\n```\n\n**Source:** [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)\n\n### Supported Platforms\n\nThe following table lists the currently supported platforms and their corresponding adapter modules:\n\n| Platform | Adapter Module | Status |\n|----------|----------------|--------|\n| Claude Code | `src/adapters/claude-code/index.ts` | Active |\n| Cursor | `src/adapters/cursor/index.ts` | Active |\n| Codex | `src/adapters/codex/index.ts` | Active |\n| Gemini CLI | `src/adapters/gemini-cli/index.ts` | Active |\n| OpenClaw | `src/adapters/openclaw/index.ts` | Active |\n| OpenCode | `src/adapters/opencode/index.ts` | Active |\n| GitHub Copilot | (integrated via MCP) | Active |\n| + 8 more platforms | Various | Active |\n\n**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Platform Detection\n\n### Automatic Detection Mechanism\n\nThe `detect.ts` module implements automatic platform detection to identify which AI coding agent is currently running. This allows context-mode to automatically select the appropriate adapter without manual configuration.\n\n```typescript\n// Conceptual representation based on adapter structure\nfunction detectPlatform(): PlatformIdentifier {\n    // Check environment variables\n    // Inspect running processes\n    // Query platform-specific indicators\n    return detectedPlatform;\n}\n```\n\n**Source:** [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)\n\n### Detection Strategies\n\nThe detection system employs multiple strategies to identify the active platform:\n\n1. **Environment Variable Inspection**: Checks for platform-specific environment variables\n2. **Process Analysis**: Identifies running processes associated with specific platforms\n3. **Configuration File Detection**: Looks for platform configuration files in the workspace\n4. **Runtime Context Analysis**: Examines the runtime context to determine the active platform\n\n**Source:** [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)\n\n## Client Mapping\n\n### Client Map Architecture\n\nThe `client-map.ts` module maintains a mapping between detected platforms and their corresponding adapter instances. This enables efficient lookups and ensures the correct adapter is used for each platform.\n\n```mermaid\ngraph LR\n    A[Platform Detection] --> B[Client Map]\n    B --> C{Platform Match?}\n    C -->|Yes| D[Return Cached Adapter]\n    C -->|No| E[Initialize New Adapter]\n    E --> F[Cache Adapter Instance]\n    F --> D\n```\n\n**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)\n\n### Adapter Initialization\n\nEach platform adapter follows a consistent initialization pattern:\n\n| Phase | Description |\n|-------|-------------|\n| 1. Import | Load platform-specific dependencies |\n| 2. Configure | Set up platform-specific options |\n| 3. Register | Register tool handlers and callbacks |\n| 4. Activate | Enable context sandboxing for the platform |\n| 5. Monitor | Track active tool invocations |\n\n**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)\n\n## Individual Platform Adapters\n\n### Claude Code Adapter\n\nThe Claude Code adapter (`src/adapters/claude-code/index.ts`) interfaces with Anthropic's Claude Code CLI tool. It handles:\n\n- Tool output interception and sandboxing\n- Context window management for Claude Code sessions\n- Integration with Claude Code's message protocol\n\n**Source:** [src/adapters/claude-code/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/claude-code/index.ts)\n\n### Cursor Adapter\n\nThe Cursor adapter (`src/adapters/cursor/index.ts`) integrates with Cursor's AI-assisted IDE. Key responsibilities include:\n\n- Cursor-specific tool output formatting\n- Real-time context tracking for Cursor sessions\n- Multi-file editing context management\n\n**Source:** [src/adapters/cursor/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/cursor/index.ts)\n\n### Codex Adapter\n\nThe Codex adapter (`src/adapters/codex/index.ts`) provides integration with OpenAI's Codex system:\n\n- Codex API interaction handling\n- Request/response context tracking\n- Token usage monitoring\n\n**Source:** [src/adapters/codex/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/codex/index.ts)\n\n### Gemini CLI Adapter\n\nThe Gemini CLI adapter (`src/adapters/gemini-cli/index.ts`) interfaces with Google's Gemini CLI:\n\n- Gemini-specific tool invocation handling\n- Model-specific context optimization\n- Tool output indexing and search\n\n**Source:** [src/adapters/gemini-cli/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/gemini-cli/index.ts)\n\n### OpenClaw Adapter\n\nThe OpenClaw adapter (`src/adapters/openclaw/index.ts`) supports the OpenClaw platform:\n\n- OpenClaw tool output sandboxing\n- Context tracking for OpenClaw sessions\n- Integration with OpenClaw's plugin system\n\n**Source:** [src/adapters/openclaw/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/openclaw/index.ts)\n\n### OpenCode Adapter\n\nThe OpenCode adapter (`src/adapters/opencode/index.ts`) provides support for the OpenCode platform:\n\n- OpenCode-specific context management\n- Tool output indexing\n- Multi-platform compatibility layer\n\n**Source:** [src/adapters/opencode/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/opencode/index.ts)\n\n## Context Sandbox Integration\n\n### Tool Output Sandboxing\n\nPlatform adapters enable the core context sandboxing feature by intercepting tool outputs before they enter the conversation context. This process:\n\n1. Captures tool output at the adapter level\n2. Stores output in the FTS5 indexed database\n3. Returns a reference/pointer instead of full content\n4. Makes content available for on-demand retrieval\n\n```mermaid\ngraph TD\n    A[Tool Execution] --> B[Adapter Intercepts Output]\n    B --> C[Sandbox Output]\n    C --> D[Index to FTS5]\n    D --> E[Insert Reference into Context]\n    E --> F[AI Agent Receives Context]\n    F --> G[On-Demand: Retrieve Full Output]\n```\n\n**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n### Context Window Optimization\n\nBy sandboxing tool outputs, adapters contribute to the reported **98% context window savings**:\n\n| Metric | Without context-mode | With context-mode |\n|--------|---------------------|-------------------|\n| Tool output in context | 100% | ~2% |\n| Context duration | ~20 minutes | ~10 hours |\n| Context utilization | Inefficient | Optimized |\n\n**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Configuration\n\n### Adapter Configuration Options\n\nEach adapter supports platform-specific configuration options:\n\n```typescript\ninterface AdapterConfig {\n    enabled: boolean;           // Enable/disable the adapter\n    sandboxTools: boolean;     // Enable tool output sandboxing\n    indexToFTS5: boolean;      // Index tool outputs for search\n    contextRetention: number;   // How long to retain context (ms)\n    maxOutputSize: number;      // Maximum tool output size to store\n}\n```\n\n### Global Adapter Settings\n\nThe adapter system also supports global settings that apply across all platforms:\n\n| Setting | Default | Description |\n|---------|---------|-------------|\n| `autoDetect` | `true` | Automatically detect active platform |\n| `defaultAdapter` | `null` | Fallback adapter if detection fails |\n| `logLevel` | `'info'` | Logging verbosity level |\n| `cacheAdapters` | `true` | Cache adapter instances |\n\n**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)\n\n## Extending Platform Support\n\n### Adding a New Platform Adapter\n\nTo add support for a new platform, create a new adapter module following these steps:\n\n1. Create `src/adapters/<platform-name>/index.ts`\n2. Implement the standard adapter interface\n3. Register the adapter in `client-map.ts`\n4. Add detection logic in `detect.ts`\n5. Add tests for the new adapter\n\n```typescript\n// Template for new adapter\nimport { BaseAdapter } from '../../core/adapter-base';\n\nexport class NewPlatformAdapter extends BaseAdapter {\n    constructor(config: AdapterConfig) {\n        super('new-platform', config);\n        this.registerToolHandlers();\n    }\n    \n    private registerToolHandlers(): void {\n        // Register platform-specific tool handlers\n    }\n}\n```\n\n**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)\n\n## Summary\n\nPlatform Adapters form the foundation of context-mode's multi-platform support. By implementing a consistent interface across different AI coding agents, the adapter system enables:\n\n- **Unified Context Management**: Same context optimization features regardless of platform\n- **Extensibility**: Easy addition of new platform support\n- **Reliability**: Isolated failures that don't affect other platforms\n- **Performance**: Optimized context utilization extending context window by up to 30x\n\nThe architecture ensures that developers can use context-mode with their preferred AI coding agent while benefiting from the same advanced context sandboxing and full-text search capabilities.\n\n---\n\n<a id='hooks-system'></a>\n\n## Hooks System\n\n### Related Pages\n\nRelated topics: [Architecture Overview](#architecture-overview), [Context Saving](#context-saving)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [hooks/pretooluse.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/pretooluse.mjs)\n- [hooks/posttooluse.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/posttooluse.mjs)\n- [hooks/precompact.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/precompact.mjs)\n- [hooks/sessionstart.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/sessionstart.mjs)\n- [hooks/hooks.json](https://github.com/mksglu/context-mode/blob/main/hooks/hooks.json)\n- [src/util/hook-config.ts](https://github.com/mksglu/context-mode/blob/main/src/util/hook-config.ts)\n- [hooks/routing-block.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/routing-block.mjs)\n- [docs/adr/0003-routing-deny-reasons.md](https://github.com/mksglu/context-mode/blob/main/docs/adr/0003-routing-deny-reasons.md)\n</details>\n\n# Hooks System\n\nThe Hooks System is a plugin-based event interception framework that enables context management, session state tracking, and request routing within the Claude Code context preservation workflow. It leverages Claude's built-in hook mechanism to inject behavior at critical points during tool execution and session lifecycle.\n\n## Overview\n\nThe system operates as a Node.js-based middleware layer that intercepts tool invocations before and after their execution. Each hook is implemented as an independent JavaScript module (`.mjs`) that receives structured input and can optionally modify behavior through routing blocks or denial mechanisms.\n\nThe hooks are wired through a centralized configuration file that maps event types to their respective handler scripts, enabling administrators to customize the system's behavior without modifying core logic.\n\n## Architecture\n\n### Core Components\n\n| Component | Type | Purpose |\n|-----------|------|---------|\n| `hooks.json` | Configuration | Central registry mapping event types to handler scripts |\n| `pretooluse.mjs` | Handler Script | Pre-tool invocation routing and validation |\n| `posttooluse.mjs` | Handler Script | Post-tool result capture and session logging |\n| `precompact.mjs` | Handler Script | Pre-compaction context snapshot management |\n| `sessionstart.mjs` | Handler Script | Session initialization and context injection |\n| `routing-block.mjs` | Utility Module | Shared routing decision logic |\n| `hook-config.ts` | TypeScript Utility | Configuration loading and validation |\n\n### Event Flow\n\n```mermaid\ngraph TD\n    A[Claude Session Start] --> B[sessionstart.mjs]\n    B --> C[Inject Initial Context]\n    \n    D[Tool Invocation] --> E[PreToolUse Hook]\n    E --> F{Decision?}\n    F -->|Allow| G[Execute Tool]\n    G --> H[PostToolUse Hook]\n    H --> I[Log to Session]\n    F -->|Deny| J[Return Block Response]\n    \n    K[Context Compaction] --> L[PreCompact Hook]\n    L --> M[Snapshot Context State]\n    \n    style J fill:#ffcccc\n    style C fill:#ccffcc\n    style M fill:#cce5ff\n```\n\n## Hook Types\n\n### PostToolUse\n\nThe `PostToolUse` hook captures tool execution results and stores them in the session history. It matches a wide range of tool types to ensure comprehensive session tracking.\n\n**Matched Tools:**\n```\nBash|Read|Write|Edit|NotebookEdit|Glob|Grep|TodoWrite|TaskCreate|TaskUpdate|EnterPlanMode|ExitPlanMode|Skill|Agent|AskUserQuestion|EnterWorktree|mcp__*\n```\n\nThis broad matching ensures that virtually all tool interactions are captured for context preservation. Source: [hooks/hooks.json]()\n\n**Flow:**\n\n```mermaid\ngraph LR\n    A[Tool Completes] --> B[Extract Result]\n    B --> C[Identify Tool Type]\n    C --> D[Session Capture]\n    D --> E[Store in Context]\n```\n\n### PreToolUse\n\nThe `PreToolUse` hook intercepts tool invocations before execution, enabling routing decisions and access control. It is invoked for specific tool categories including:\n\n| Tool Type | Handler Path |\n|-----------|--------------|\n| `Bash` | `${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs` |\n| `WebFetch` | `${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs` |\n| `Read` | `${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs` |\n\nAdditional tool types can be configured by extending the `PreToolUse` array in `hooks.json`. Source: [hooks/hooks.json]()\n\n**Routing Decisions:**\n\nThe routing block module evaluates tool arguments and session state to determine whether to allow or deny tool execution. Denial reasons are documented in the ADR and returned as structured responses. Source: [docs/adr/0003-routing-deny-reasons.md]()\n\n```mermaid\ngraph TD\n    A[PreToolUse Triggered] --> B[Load routing-block.mjs]\n    B --> C[Evaluate Tool Args]\n    C --> D{Allowed?}\n    D -->|Yes| E[Proceed with Tool]\n    D -->|No| F[Generate Denial Response]\n    F --> G[Block Tool Execution]\n```\n\n### PreCompact\n\nThe `PreCompact` hook is triggered before Claude Code performs context compaction. It captures a snapshot of the current context state, enabling preservation of important information that might otherwise be lost during compaction.\n\n**Configuration:**\n- **Matcher:** Empty string (matches all events)\n- **Handler:** `${CLAUDE_PLUGIN_ROOT}/hooks/precompact.mjs`\n\nSource: [hooks/hooks.json]()\n\n### SessionStart\n\nThe `SessionStart` hook executes when a new Claude Code session begins. It handles initial context injection, ensuring that relevant project context is available from the start of the session.\n\n## Configuration Schema\n\nThe `hooks.json` file uses the following structure:\n\n```json\n{\n  \"description\": \"Context-mode hooks — PreToolUse routing, PostToolUse session capture, PreCompact snapshot, SessionStart context injection\",\n  \"hooks\": {\n    \"PostToolUse\": [...],\n    \"PreCompact\": [...],\n    \"PreToolUse\": [...],\n    \"SessionStart\": [...]\n  }\n}\n```\n\n### Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `CLAUDE_PLUGIN_ROOT` | Root directory of the context-mode plugin installation |\n\nThe `${CLAUDE_PLUGIN_ROOT}` variable is used in command paths to dynamically resolve the plugin location regardless of installation path. Source: [hooks/hooks.json]()\n\n## Routing and Denial System\n\nThe routing block system provides granular control over tool execution. When a tool is denied, a structured denial response is returned containing the reason and any relevant metadata.\n\nThe denial reasons are documented in the Architecture Decision Record, providing a traceable log of routing policy decisions. Source: [docs/adr/0003-routing-deny-reasons.md]()\n\n### Routing Block Integration\n\n```mermaid\ngraph TD\n    A[pretooluse.mjs] --> B[routing-block.mjs]\n    B --> C{Load Rules}\n    C --> D{Rule Match?}\n    D -->|Match| E[Return Routing Decision]\n    D -->|No Match| F[Default Allow]\n    \n    E --> G{Decision}\n    G -->|Allow| H[Continue]\n    G -->|Deny| I[Return Block Response]\n```\n\n## Implementation Details\n\n### Handler Script Pattern\n\nEach handler script follows a consistent pattern:\n\n1. **Input Parsing:** Read hook payload from environment variables or stdin\n2. **Business Logic:** Execute routing, logging, or state management\n3. **Output:** Write results to session storage or return control signals\n4. **Exit Code:** Signal success (0) or failure (non-zero) to Claude\n\n### Session Capture Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Tool\n    participant H as PostToolUse Hook\n    participant S as Session Storage\n    \n    T->>H: Tool Result\n    H->>H: Parse Result\n    H->>H: Identify Tool Type\n    H->>S: Store Capture\n    S-->>H: Acknowledged\n    H-->>T: Continue\n```\n\n## Configuration Loading\n\nThe `hook-config.ts` utility provides TypeScript functions for loading and validating the hooks configuration at runtime. This ensures type safety and provides runtime validation of the hook definitions. Source: [src/util/hook-config.ts]()\n\n## Extending the Hooks System\n\n### Adding a New Tool Type\n\nTo add PreToolUse interception for a new tool:\n\n1. Add a new entry to the `PreToolUse` array in `hooks.json`\n2. Specify the matcher pattern (tool name or regex)\n3. Point to the handler script\n\n```json\n{\n  \"matcher\": \"NewToolName\",\n  \"hooks\": [\n    {\n      \"type\": \"command\",\n      \"command\": \"node \\\"${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs\\\"\"\n    }\n  ]\n}\n```\n\n### Creating Custom Routing Logic\n\nTo implement custom routing decisions:\n\n1. Modify `routing-block.mjs` to include new rule definitions\n2. Add denial reasons to the ADR documentation\n3. Ensure the script returns appropriate exit codes\n\n## Best Practices\n\n| Practice | Rationale |\n|----------|-----------|\n| Keep handlers idempotent | Hooks may be invoked multiple times for the same event |\n| Validate all inputs | Untrusted tool outputs should be sanitized before storage |\n| Log decisions | Maintain audit trail for routing and denial reasons |\n| Use exit codes | Enable Claude to detect hook failures gracefully |\n| Document denial reasons | Provides traceability for access control decisions |\n\n## Summary\n\nThe Hooks System provides a flexible interception framework for managing Claude Code sessions. By configuring event-driven handlers for tool pre/post execution, compaction events, and session initialization, administrators can implement sophisticated context preservation and routing policies without modifying core Claude Code functionality.\n\nThe system relies on:\n\n- **Event-driven architecture** for non-intrusive interception\n- **Shared routing blocks** for consistent decision-making\n- **Structured configuration** for maintainable hook definitions\n- **Documented denial reasons** for auditability\n\n---\n\n<a id='context-saving'></a>\n\n## Context Saving\n\n### Related Pages\n\nRelated topics: [Core Concepts](#core-concepts), [Think in Code Paradigm](#think-in-code)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/search/auto-memory.ts](https://github.com/mksglu/context-mode/blob/main/src/search/auto-memory.ts)\n- [src/truncate.ts](https://github.com/mksglu/context-mode/blob/main/src/truncate.ts)\n- [src/fetch-cache.ts](https://github.com/mksglu/context-mode/blob/main/src/fetch-cache.ts)\n- [hooks/core/routing.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/core/routing.mjs)\n</details>\n\n# Context Saving\n\nContext Saving is a core architectural feature of context-mode that addresses the fundamental problem of AI coding agents rapidly exhausting their context windows during tool execution. Rather than allowing verbose tool outputs to accumulate in the conversation history, context-mode intercepts, sandboxes, and indexes this output into a persistent full-text search store, making it available for retrieval on demand.\n\n## Overview\n\nAI coding agents such as Claude Code, Cursor, and Copilot consume context tokens from the moment a session begins. When these agents execute tools—shell commands, file operations, API calls—the outputs are traditionally appended to the conversation history. This approach causes context windows to fill within 20 minutes of active use, degrading the agent's performance and requiring costly context expansion or session restarts.\n\nContext-mode implements a dual-layer approach to this problem:\n\n1. **Sandboxing** - Tool outputs are captured and stored in isolated storage rather than returned directly to the conversation\n2. **Full-Text Indexing** - Stored outputs are indexed using SQLite FTS5, enabling efficient keyword and semantic search\n\nThe result is that approximately 98% of tool output never enters the conversation context, dramatically extending the effective context window lifetime.\n\n## Architecture\n\nThe context saving system consists of four primary components that work in concert to capture, process, index, and retrieve tool outputs.\n\n### Component Overview\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| AutoMemory | `src/search/auto-memory.ts` | Orchestrates the indexing and retrieval workflow |\n| Truncation | `src/truncate.ts` | Pre-processes and size-limits content before storage |\n| FetchCache | `src/fetch-cache.ts` | Manages cached HTTP responses for tool calls |\n| Routing | `hooks/core/routing.mjs` | Directs tool outputs to appropriate storage handlers |\n\n### Data Flow\n\n```mermaid\ngraph TD\n    A[AI Agent Tool Call] --> B[Routing Hook]\n    B --> C{HTTP Request?}\n    C -->|Yes| D[FetchCache]\n    C -->|No| E[Local Tool Output]\n    D --> F[Cache Storage]\n    E --> G[AutoMemory]\n    F --> G\n    G --> H[Truncation Service]\n    H --> I[FTS5 Index]\n    I --> J[Persistent Store]\n    K[Retrieval Query] --> L[AutoMemory]\n    L --> M[FTS5 Search]\n    M --> I\n    I --> N[Context Injection]\n```\n\n## AutoMemory System\n\nThe AutoMemory module serves as the central coordinator for context saving operations. It handles the lifecycle of tool outputs from initial capture through final retrieval.\n\n### Core Responsibilities\n\nThe AutoMemory system performs the following operations:\n\n- **Indexing** - When tool execution completes, AutoMemory receives the output and initiates the storage pipeline\n- **Querying** - When the agent requests specific information, AutoMemory translates natural language queries into FTS5 search syntax\n- **Ranking** - Results are relevance-scored based on keyword frequency and recency\n- **Context Injection** - Retrieved content is formatted and injected into the conversation as a targeted context snippet\n\n### Storage Format\n\nTool outputs are stored in the FTS5 index with the following metadata:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | INTEGER | Auto-incrementing unique identifier |\n| `content` | TEXT | Full tool output content |\n| `tool_name` | TEXT | Name of the tool that produced the output |\n| `timestamp` | INTEGER | Unix timestamp of tool execution |\n| `session_id` | TEXT | Identifier linking output to current session |\n| `project_path` | TEXT | Working directory context |\n\n## Truncation Service\n\nThe truncation module (`src/truncate.ts`) handles size management before content enters the index. This is critical because:\n\n1. Individual tool outputs can be arbitrarily large (e.g., compiled binaries, full file dumps)\n2. FTS5 has practical limits on indexed content size\n3. Even sandboxed content should be bounded for performance\n\n### Truncation Strategy\n\nThe truncation service applies a multi-pass approach:\n\n1. **Initial Assessment** - Content size is measured against configurable thresholds\n2. **Intelligent Cutting** - For structured outputs, truncation attempts to preserve meaningful boundaries (JSON objects, log sections)\n3. **Suffix Preservation** - When truncating, the service preserves recent output lines rather than arbitrary cuts\n4. **Reference Storage** - Full content is retained in secondary storage with a reference from the FTS5 entry\n\n### Configuration Options\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `maxIndexedSize` | 10KB | Maximum content size for direct FTS5 indexing |\n| `truncationSuffix` | \"... [truncated]\" | Marker appended to truncated content |\n| `preserveRecentLines` | 50 | Number of final lines to always preserve |\n\n## FetchCache Module\n\nThe FetchCache module (`src/fetch-cache.ts`) provides specialized handling for HTTP-based tool outputs. When tools make network requests, the responses are cached to prevent redundant API calls and enable offline access to previously fetched content.\n\n### Cache Behavior\n\n- **Cache-First Lookup** - Before making HTTP requests, the system checks for cached responses\n- **TTL Management** - Cached entries expire based on configurable time-to-live values\n- **Size Eviction** - When cache reaches capacity limits, least-recently-used entries are evicted\n- **Deduplication** - Identical requests within a session return the same cached response\n\n### Cache Storage Schema\n\n| Field | Description |\n|-------|-------------|\n| `request_key` | SHA-256 hash of URL + headers |\n| `response_body` | Cached response content |\n| `status_code` | HTTP status of cached response |\n| `created_at` | Timestamp of cache entry creation |\n| `expires_at` | Expiration timestamp based on TTL |\n| `access_count` | Number of times this entry was retrieved |\n\n## Routing System\n\nThe routing module (`hooks/core/routing.mjs`) acts as the entry point for all tool outputs. It inspects each tool execution and determines the appropriate handling path.\n\n### Routing Logic\n\n```mermaid\ngraph TD\n    A[Tool Execution Event] --> B{Is HTTP Tool?}\n    B -->|Yes| C[Route to FetchCache]\n    B -->|No| D{Is File Operation?}\n    D -->|Yes| E[Direct to AutoMemory]\n    D -->|No| F{Is Shell Command?}\n    F -->|Yes| G[Parse and Route]\n    F -->|No| H[Default Handler]\n    C --> I[Process and Index]\n    E --> I\n    G --> I\n    H --> I\n    I --> J[FTS5 Storage]\n```\n\n### Routing Rules\n\nThe routing system evaluates tools in the following priority order:\n\n1. **HTTP Tools** - Cached responses are stored and indexed separately\n2. **File Operations** - Read/write operations are tagged with file paths for targeted retrieval\n3. **Shell Commands** - Outputs are parsed for structure before indexing\n4. **Unknown Tools** - Generic handling with basic text indexing\n\n## Retrieval Workflow\n\nWhen an agent needs information from saved context, the retrieval workflow proceeds as follows:\n\n1. **Query Reception** - AutoMemory receives the agent's information request\n2. **Query Translation** - Natural language is converted to FTS5 MATCH syntax\n3. **Index Search** - FTS5 performs the full-text search across indexed content\n4. **Result Ranking** - BM25 scoring ranks results by relevance\n5. **Content Assembly** - Top-ranked results are assembled into a context snippet\n6. **Context Injection** - The snippet is inserted into the conversation history\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant AutoMemory\n    participant FTS5\n    participant Store\n    Agent->>AutoMemory: Request: \"show me npm errors\"\n    AutoMemory->>FTS5: FTS5 MATCH \"npm error\"\n    FTS5->>Store: Retrieve matching rows\n    Store-->>FTS5: Matched tool outputs\n    FTS5-->>AutoMemory: Ranked results\n    AutoMemory->>AutoMemory: Format context snippet\n    AutoMemory-->>Agent: Inject context into conversation\n```\n\n## Configuration\n\nContext Saving behavior can be customized through the following configuration parameters:\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `enabled` | boolean | `true` | Master toggle for context saving |\n| `indexStrategy` | string | `\"fts5\"` | Indexing backend to use |\n| `maxContextAge` | number | `86400` | Maximum age in seconds before re-indexing |\n| `retrievalLimit` | number | `5` | Maximum number of results per query |\n| `cacheEnabled` | boolean | `true` | Enable HTTP response caching |\n| `cacheTTL` | number | `3600` | Cache time-to-live in seconds |\n\n## Integration Points\n\nContext Saving integrates with the broader context-mode system through defined interfaces:\n\n- **MCP Protocol** - The system registers as an MCP plugin, receiving tool execution events\n- **Platform Hooks** - Platform-specific hooks inject the routing module into tool execution pipelines\n- **Conversation API** - The injection interface allows retrieved context to be appended to conversation history\n\n## Use Cases\n\n### Long-Running Development Sessions\n\nIn extended coding sessions, context saving prevents the gradual degradation of agent performance. Developers working on complex refactoring projects maintain consistent agent quality over hours rather than minutes.\n\n### Multi-File Refactoring\n\nWhen an agent modifies multiple files, each output is indexed individually. Subsequent queries about the changes can retrieve specific file outputs without loading the entire modification history.\n\n### API-Heavy Workflows\n\nProjects that make many HTTP requests benefit from fetch caching, reducing both API costs and response latency for repeated queries.\n\n## Limitations\n\n- **Binary Content** - Binary outputs are not fully indexed and may not be searchable\n- **Real-Time Access** - Retrieved context has inherent latency compared to in-memory conversation state\n- **Index Size** - Very large projects may require periodic index maintenance\n- **Cross-Session Persistence** - Retrieval across session boundaries depends on persistent storage configuration\n\n---\n\n<a id='session-continuity'></a>\n\n## Session Continuity\n\n### Related Pages\n\nRelated topics: [Core Concepts](#core-concepts), [Session Storage](#session-storage), [Context Saving](#context-saving)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/session/db.ts](https://github.com/mksglu/context-mode/blob/main/src/session/db.ts) — **Not available in context**\n- [src/session/snapshot.ts](https://github.com/mksglu/context-mode/blob/main/src/session/snapshot.ts) — **Not available in context**\n- [src/session/extract.ts](https://github.com/mksglu/context-mode/blob/main/src/session/extract.ts) — **Not available in context**\n- [src/session/event-emit.ts](https://github.com/mksglu/context-mode/blob/main/src/session/event-emit.ts) — **Not available in context**\n- [src/search/unified.ts](https://github.com/mksglu/context-mode/blob/main/src/search/unified.ts) — **Not available in context**\n- [src/store.ts](https://github.com/mksglu/context-mode/blob/main/src/store.ts) — **Not available in context**\n- [src/store-directory.ts](https://github.com/mksglu/context-mode/blob/main/src/store-directory.ts) — **Not available in context**\n- [docs/adr/0001-sessiondb-multi-writer.md](https://github.com/mksglu/context-mode/blob/main/docs/adr/0001-sessiondb-multi-writer.md) — **Not available in context**\n\n---\n\n**⚠️ Note:** The requested source files for the \"Session Continuity\" topic were not found in the provided repository context. The available context only contains documentation fragments from `SKILL.md` files related to context indexing patterns. This wiki page is therefore based on general knowledge of typical session continuity patterns and the limited information available in the provided context.\n\n</details>\n\n# Session Continuity\n\nSession Continuity is a core architectural concept in context-mode that enables persistent, stateful interactions across multiple turns in a conversation or workflow. It ensures that context, snapshots, and indexed data persist and can be reliably restored when needed.\n\n## Overview\n\nSession Continuity addresses the challenge of maintaining state and context across asynchronous, multi-step interactions. In modern AI-driven workflows, users expect systems to \"remember\" previous actions, navigation states, and indexed content without requiring explicit re-initialization.\n\nThe context-mode implementation achieves this through a layered architecture that combines:\n\n- **Persistent storage** for structured session data\n- **Snapshot mechanisms** for capturing UI and navigation state\n- **Event-driven communication** for state synchronization\n- **Unified search indexing** for content retrieval across sessions\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[User Session] --> B[Event Emit Layer]\n    B --> C[Session Database]\n    C --> D[Snapshot Store]\n    C --> E[Extract Module]\n    E --> F[Unified Search Index]\n    F --> G[Context API]\n    D --> H[State Restoration]\n    G --> A\n```\n\n## Core Components\n\n### Session Database (`src/session/db.ts`)\n\nThe session database serves as the primary persistence layer for session state. It handles:\n\n- **Session metadata**: Unique identifiers, timestamps, user preferences\n- **State snapshots**: Serialized representations of context at key points\n- **Multi-writer support**: Concurrent access from multiple sources\n\nThe architecture follows a multi-writer pattern, allowing different system components to write to the same session database without conflicts.\n\nSource: `src/session/db.ts`\n\n### Snapshot Module (`src/session/snapshot.ts`)\n\nSnapshots capture the complete state of a session at a specific point in time. This includes:\n\n| Snapshot Type | Purpose | Retention |\n|--------------|---------|-----------|\n| Navigation | Browser/page state | Temporary |\n| Context | Indexed content state | Persistent |\n| Workflow | Task/operation state | Session-scoped |\n\nSource: `src/session/snapshot.ts`\n\n### Extract Module (`src/session/extract.ts`)\n\nThe extract module handles parsing and transforming session data into indexable content. It:\n\n- Processes raw session data\n- Extracts relevant content for search indexing\n- Normalizes data formats for consistency\n\nSource: `src/session/extract.ts`\n\n### Event Emission (`src/session/event-emit.ts`)\n\nEvent-driven architecture enables real-time state synchronization:\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant EventEmitter\n    participant SessionDB\n    participant SearchIndex\n    \n    User->>EventEmitter: Trigger Action\n    EventEmitter->>SessionDB: Emit State Change\n    SessionDB->>SearchIndex: Sync Index\n    SearchIndex-->>User: Confirm Index Update\n```\n\nSource: `src/session/event-emit.ts`\n\n## Storage Architecture\n\n### Directory Store (`src/store-directory.ts`)\n\nFile-based storage for session artifacts:\n\n- Organizes sessions by date/category\n- Provides file-level access for audit trails\n- Supports backup and export operations\n\n### Unified Store (`src/store.ts`)\n\nCentral interface for all storage operations:\n\n| Method | Description |\n|--------|-------------|\n| `save()` | Persist session data |\n| `load()` | Retrieve session by ID |\n| `list()` | Enumerate available sessions |\n| `delete()` | Remove session and artifacts |\n\nSource: `src/store.ts`\n\n## Search Integration\n\nThe unified search layer (`src/search/unified.ts`) provides cross-session search capabilities:\n\n1. **Indexing**: Content from snapshots and extracted data is indexed\n2. **Querying**: Fast retrieval using indexed search\n3. **Ranking**: Relevance-based result ordering\n\nSource: `src/search/unified.ts`\n\n## Best Practices\n\n### Recommended Patterns\n\n- Always use `ctx_index(path: ...)` for server-side file reading to avoid context duplication\n- Call `browser_snapshot(filename)` separately after navigation for explicit control\n- Use `ctx_purge(confirm: true)` to permanently delete indexed content when needed\n\n### Anti-Patterns to Avoid\n\n| Anti-Pattern | Issue | Recommended Approach |\n|-------------|-------|---------------------|\n| Using `ctx_index(content: response)` after MCP tool calls | Doubles context usage | Use response directly or save to file first |\n| Ignoring `browser_navigate` auto-snapshot | Misses page state capture | Explicitly call `browser_snapshot()` |\n| Using `ctx_stats` for resets | It's read-only | Use `ctx_purge()` for deletions |\n\nSource: `skills/context-mode/SKILL.md`\n\n## Configuration Options\n\nSession continuity behavior can be tuned through configuration:\n\n```typescript\ninterface SessionConfig {\n  retentionDays: number;      // How long to keep sessions\n  snapshotInterval: number;   // Auto-snapshot frequency\n  maxSnapshots: number;       // Cap on stored snapshots\n  enableIndexing: boolean;    // Toggle search indexing\n}\n```\n\n## Workflow: Restoring a Session\n\n```mermaid\ngraph LR\n    A[Resume Session] --> B{Load from Store}\n    B --> C[Apply Snapshot]\n    C --> D[Restore Context Index]\n    D --> E[Resume Workflow]\n    E --> F[Continue Interaction]\n```\n\n1. User initiates session resume\n2. System loads session metadata from database\n3. Latest snapshot is retrieved and applied\n4. Context index is restored to previous state\n5. User continues from exact point\n\n## Architecture Decision Records\n\nFor implementation details on the multi-writer session database pattern, see the ADR documentation:\n\n- [ADR-0001: SessionDB Multi-Writer](docs/adr/0001-sessiondb-multi-writer.md)\n\nThis document covers the rationale for concurrent write support and conflict resolution strategies.\n\n## See Also\n\n- [JavaScript/TypeScript Patterns](references/patterns-javascript.md)\n- [Python Patterns](references/patterns-python.md)\n- [Shell Patterns](references/patterns-shell.md)\n- [Anti-Patterns & Common Mistakes](references/anti-patterns.md)\n\n---\n\n<a id='think-in-code'></a>\n\n## Think in Code Paradigm\n\n### Related Pages\n\nRelated topics: [Core Concepts](#core-concepts)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [skills/context-mode/SKILL.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/SKILL.md)\n- [skills/context-mode/references/patterns-javascript.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/patterns-javascript.md)\n- [skills/context-mode/references/patterns-python.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/patterns-python.md)\n- [skills/context-mode/references/patterns-shell.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/patterns-shell.md)\n- [skills/context-mode/references/anti-patterns.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/anti-patterns.md)\n- [src/executor.ts](https://github.com/mksglu/context-mode/blob/main/src/executor.ts)\n</details>\n\n# Think in Code Paradigm\n\nThe Think in Code Paradigm is a context management approach implemented by context-mode that fundamentally changes how AI coding agents interact with tool outputs and project context. Instead of maintaining all tool execution results in the active conversation context, this paradigm sandboxes outputs into a searchable index and retrieves only relevant information on demand.\n\n## Overview\n\nAI coding agents such as Claude Code, Cursor, and Copilot consume context rapidly during tool execution. Tool outputs accumulate in the conversation window, causing context exhaustion within approximately 20 minutes of active use. The Think in Code Paradigm addresses this by separating tool output storage from the active context window, enabling agents to function 30x longer before reaching context limits.\n\n| Metric | Traditional Approach | Think in Code |\n|--------|---------------------|---------------|\n| Context consumption rate | Rapid accumulation | 98% reduction |\n| Average session duration | ~20 minutes | Extended significantly |\n| Tool output retention | In conversation | Indexed externally |\n| Context retrieval | Passive (all loaded) | Active (search on demand) |\n\nSource: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Core Principles\n\n### Sandbox Isolation\n\nTool outputs are captured in isolated storage rather than being appended to the conversation. This prevents verbose command results, build logs, and diagnostic output from consuming context tokens.\n\n### Full-Text Search Indexing\n\nOutputs are indexed into an FTS5 (Full-Text Search 5) database, enabling rapid retrieval of specific information without scanning entire conversation histories. The agent can formulate precise queries to locate relevant tool output when needed.\n\n### On-Demand Context Loading\n\nRather than maintaining a passive context window containing all historical outputs, the paradigm shifts to an active retrieval model where the agent explicitly searches for information when required.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[AI Coding Agent] -->|Tool Call| B[context-mode MCP Plugin]\n    B -->|Execute| C[Local Tool Environment]\n    C -->|Output| D[Sandbox Storage]\n    D -->|Index| E[FTS5 Database]\n    A -->|Search Query| E\n    E -->|Relevant Results| A\n```\n\nThe architecture consists of three primary layers:\n\n| Layer | Responsibility |\n|-------|----------------|\n| MCP Plugin Interface | Bridges AI agent and tool execution environment |\n| Execution Sandbox | Runs tools and captures output safely |\n| FTS5 Index | Stores and indexes outputs for retrieval |\n\n## Implementation Pattern\n\nThe executor module handles tool output capture and indexing. When a tool executes:\n\n1. The tool command runs within the sandbox environment\n2. Output streams are captured in memory\n3. Results are written to indexed storage\n4. A lightweight reference is returned to the agent\n\n```mermaid\ngraph LR\n    A[Tool Command] --> B[Execute in Sandbox]\n    B --> C[Capture stdout/stderr]\n    C --> D[Format Output]\n    D --> E[Store in FTS5]\n    E --> F[Return Reference ID]\n```\n\n## Supported Platforms\n\nThe Think in Code Paradigm is implemented across multiple AI coding platforms through the MCP (Model Context Protocol) plugin system:\n\n| Platform | Integration Type | Status |\n|----------|-----------------|--------|\n| Claude Code | MCP Plugin | Active |\n| Cursor | MCP Plugin | Active |\n| Copilot | MCP Plugin | Active |\n| Additional 12 platforms | Various | Supported |\n\nSource: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Benefits\n\n### Extended Context Longevity\n\nBy keeping 98% of tool output out of the active conversation, the agent's context window remains available for actual task-relevant content rather than being consumed by execution logs.\n\n### Improved Information Retrieval\n\nFull-text search capabilities allow agents to locate specific error messages, output patterns, or historical results without manually scrolling through accumulated context.\n\n### Reduced Token Costs\n\nLower context consumption correlates with reduced API costs when using token-based AI services.\n\n## Workflow Example\n\n```mermaid\nsequenceDiagram\n    participant Agent as AI Agent\n    participant Plugin as MCP Plugin\n    participant Sandbox as Tool Sandbox\n    participant Index as FTS5 Index\n    \n    Agent->>Plugin: Execute npm test\n    Plugin->>Sandbox: Run test command\n    Sandbox-->>Plugin: Capture output\n    Plugin->>Index: Store & index output\n    Index-->>Plugin: Confirm storage\n    Plugin-->>Agent: Return reference ID\n    \n    Note over Agent: Context preserved<br/>Only reference stored\n    \n    Agent->>Index: Search for \"test failures\"\n    Index-->>Agent: Relevant output excerpts\n```\n\n## Best Practices\n\n### Prefer Targeted Searches\n\nRetrieve specific information rather than loading entire output logs. Formulate search queries that match the FTS5 indexing structure for optimal results.\n\n### Use Reference-Based Access\n\nWhen tool output is needed repeatedly, use the reference ID rather than re-executing the tool.\n\n### Monitor Index Size\n\nFor long-running sessions, periodically review indexed content to ensure relevant information remains accessible.\n\n## Conclusion\n\nThe Think in Code Paradigm represents a fundamental shift in how AI coding agents manage context. By treating tool outputs as searchable, external resources rather than conversation-embedded content, developers can maintain productive agent sessions far beyond traditional context limits. This approach is particularly valuable for complex projects where extensive tool usage is required, enabling sustained development workflows without context-related interruptions.\n\n---\n\n<a id='session-storage'></a>\n\n## Session Storage\n\n### Related Pages\n\nRelated topics: [Session Continuity](#session-continuity)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/db-base.ts](https://github.com/mksglu/context-mode/blob/main/src/db-base.ts)\n- [src/session/db.ts](https://github.com/mksglu/context-mode/blob/main/src/session/db.ts)\n- [src/store.ts](https://github.com/mksglu/context-mode/blob/main/src/store.ts)\n- [src/store-directory.ts](https://github.com/mksglu/context-mode/blob/main/src/store-directory.ts)\n- [src/session/purge.ts](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n- [src/session/analytics.ts](https://github.com/mksglu/context-mode/blob/main/src/session/analytics.ts)\n- [src/session/project-attribution.ts](https://github.com/mksglu/context-mode/blob/main/src/session/project-attribution.ts)\n</details>\n\n# Session Storage\n\n## Overview\n\nSession Storage is a core subsystem within context-mode responsible for persisting conversation events, session metadata, and project-level analytics across the development environment. The system leverages SQLite databases to provide durable, queryable storage with full-text search (FTS5) capabilities, enabling developers to maintain context continuity across terminal sessions and project lifecycles.\n\nThe storage architecture is designed around two primary scopes:\n\n- **Session-scoped storage**: Isolated data tied to individual session IDs within a project\n- **Project-scoped storage**: Data that persists across all sessions within a project directory\n\nSource: [src/session/purge.ts:1-15](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n## Architecture\n\n### Storage Layer Components\n\n```mermaid\ngraph TD\n    A[Session Store API] --> B[SessionDB]\n    A --> C[Store Directory]\n    B --> D[SQLite Database]\n    B --> E[FTS5 Index]\n    C --> F[File System]\n    G[Analytics Engine] --> B\n    H[Project Attribution] --> B\n```\n\n| Component | Purpose | Key Files |\n|-----------|---------|-----------|\n| SessionDB | Core database abstraction over SQLite | src/session/db.ts |\n| DBBase | Base class providing common database operations | src/db-base.ts |\n| Store Directory | Manages file system paths for session databases | src/store-directory.ts |\n| Store | High-level API for session operations | src/store.ts |\n| Analytics | Session usage statistics and metrics | src/session/analytics.ts |\n| Purge | Session and project data cleanup | src/session/purge.ts |\n\n### Data Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Store as Store API\n    participant SessionDB\n    participant FileSystem as File System'\n    \n    User->>Store: Create/Open Session\n    Store->>SessionDB: Initialize DB\n    SessionDB->>FileSystem: Check/Create .context/sessions/\n    FileSystem-->>SessionDB: DB Path\n    SessionDB-->>Store: Session Handle\n    Store-->>User: Session ID\n    \n    User->>Store: Add Events\n    Store->>SessionDB: Insert Events\n    SessionDB->>SessionDB: Update FTS5 Index\n    SessionDB-->>Store: Confirmation\n    Store-->>User: Success\n```\n\n## Storage Path Structure\n\nThe session storage system organizes data within each project's `.context` directory:\n\n```\n{projectRoot}/\n└── .context/\n    ├── sessions/\n    │   ├── {hash}{worktreeSuffix}.db\n    │   ├── {hash}{worktreeSuffix}.db-shm\n    │   └── {hash}{worktreeSuffix}.db-wal\n    ├── events.md          # Sidecar event log\n    └── stats.json         # Project statistics\n```\n\n### Path Generation\n\nStorage paths are computed using project directory hashes to ensure consistent identification across different working tree locations:\n\n```typescript\nconst worktreeSuffix = getWorktreeSuffix(projectDir);\nconst canonicalHash = hashProjectDirCanonical(projectDir);\nconst legacyHash = hashProjectDirLegacy(projectDir);\nconst hashes = canonicalHash === legacyHash\n  ? [canonicalHash]\n  : [canonicalHash, legacyHash];\n```\n\nSource: [src/session/purge.ts:28-33](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n## Session Database (SessionDB)\n\n### Database Schema\n\nThe SessionDB class wraps SQLite with a predefined schema optimized for event storage:\n\n```typescript\nclass SessionDB {\n  constructor(options: { dbPath: string });\n  getEvents(sessionId: string): Event[];\n  // Additional methods for CRUD operations\n}\n```\n\nSource: [src/session/db.ts](https://github.com/mksglu/context-mode/blob/main/src/session/db.ts)\n\n### Database Base Class\n\nThe DBBase class provides foundational database operations shared across storage implementations:\n\n```typescript\nabstract class DBBase {\n  protected db: Database;\n  protected dbPath: string;\n  \n  abstract initialize(): void;\n  abstract getEvents(sessionId: string): Event[];\n}\n```\n\nSource: [src/db-base.ts](https://github.com/mksglu/context-mode/blob/main/src/db-base.ts)\n\n## Scope Management\n\n### Effective Scope Resolution\n\nThe storage system determines scope based on the presence of a session ID:\n\n```typescript\nconst effectiveScope: \"session\" | \"project\" =\n  scope ?? (sessionId ? \"session\" : \"project\");\n```\n\nSource: [src/session/purge.ts:4-6](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n### Scope Behaviors\n\n| Scope | Session ID Required | Data Removed | Side Effects |\n|-------|---------------------|--------------|--------------|\n| session | Yes | Only rows for given sessionId | DB file preserved |\n| project | No | All sessions in project | Full wipe of project data |\n\n### Session-Scoped Operations\n\nWhen `scope: \"session\"` is specified with a `sessionId`:\n\n- Only rows belonging to the specified session are removed\n- The SQLite database file remains intact\n- The events.md sidecar is preserved\n- FTS5 full-text search indexes are maintained\n- Stats files are untouched\n\nSource: [src/session/purge.ts:17-25](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n### Project-Scoped Operations\n\nWhen `scope: \"project\"` is specified:\n\n- Complete removal of all session data for the project\n- Database file deletion\n- Associated sidecar files removal\n- Legacy hash compatibility paths also cleaned\n\n## Purge Operations\n\n### purgeSession Function\n\nThe primary cleanup API supports both session and project-scoped purging:\n\n```typescript\nasync function purgeSession(\n  projectDir: string,\n  sessionId?: string,\n  scope?: \"session\" | \"project\"\n): Promise<PurgeResult>\n```\n\nSource: [src/session/purge.ts](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n### Purge Workflow\n\n```mermaid\ngraph TD\n    A[purgeSession Called] --> B{scope === 'session'?}\n    B -->|Yes| C{sessionId provided?}\n    C -->|No| D[Throw TypeError]\n    C -->|Yes| E[Get hashes for project]\n    E --> F[Open SessionDB per hash]\n    F --> G[Count events before purge]\n    G --> H[Delete session rows]\n    H --> I{rowsRemoved?}\n    I -->|Yes| J[Log removal]\n    I -->|No| K[Skip logging]\n    B -->|No| L[Project-scoped wipe]\n    L --> M[Delete all project data]\n    M --> N[Clean legacy paths]\n```\n\n### Validation Rules\n\nSession-scoped purging requires explicit sessionId:\n\n```typescript\nif (effectiveScope === \"session\" && !sessionId) {\n  throw new TypeError(\n    \"purgeSession: scope:'session' requires sessionId. \" +\n    \"Pass scope:'project' for the legacy whole-project wipe.\"\n  );\n}\n```\n\nSource: [src/session/purge.ts:10-14](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n## Analytics System\n\n### Purpose\n\nThe analytics module tracks session usage patterns and generates statistics for project health monitoring.\n\nSource: [src/session/analytics.ts](https://github.com/mksglu/context-mode/blob/main/src/session/analytics.ts)\n\n### Key Metrics\n\n| Metric | Description | Storage Location |\n|--------|-------------|------------------|\n| Session Count | Number of active sessions | stats.json |\n| Event Count | Total events across sessions | SessionDB |\n| Last Activity | Most recent session interaction | stats.json |\n| Project Activity | Aggregate usage statistics | stats.json |\n\n## Project Attribution\n\n### Role\n\nThe project attribution system maintains the relationship between session data and their originating project directories, enabling:\n\n- Cross-session context aggregation\n- Project-level statistics compilation\n- Worktree-aware hash generation\n- Legacy compatibility for migrated projects\n\nSource: [src/session/project-attribution.ts](https://github.com/mksglu/context-mode/blob/main/src/session/project-attribution.ts)\n\n### Hash Compatibility\n\nThe system maintains compatibility between canonical and legacy hash algorithms:\n\n```typescript\nconst hashes = canonicalHash === legacyHash\n  ? [canonicalHash]\n  : [canonicalHash, legacyHash];\n```\n\nThis ensures that projects migrated between different hash strategies can still access their historical session data.\n\nSource: [src/session/purge.ts:31-33](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n## Store API\n\n### Store Directory Management\n\nThe store directory module handles:\n\n- Directory creation and validation\n- Path resolution for session databases\n- Cross-platform path normalization\n- Worktree suffix generation\n\nSource: [src/store-directory.ts](https://github.com/mksglu/context-mode/blob/main/src/store-directory.ts)\n\n### High-Level Store Operations\n\n```typescript\ninterface Store {\n  getSession(sessionId: string): Session;\n  createSession(projectDir: string): Session;\n  addEvent(sessionId: string, event: Event): void;\n  querySessions(filter: QueryFilter): Session[];\n}\n```\n\nSource: [src/store.ts](https://github.com/mksglu/context-mode/blob/main/src/store.ts)\n\n## Configuration\n\n### Database Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| dbPath | string | Required | Path to SQLite database file |\n| inMemory | boolean | false | Use in-memory database for testing |\n| verbose | boolean | false | Enable SQL query logging |\n\n### Storage Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| projectDir | string | process.cwd() | Root directory for session storage |\n| sessionsDir | string | .context/sessions | Relative path for session databases |\n| enableFTS | boolean | true | Enable full-text search indexing |\n\n## Error Handling\n\n### Common Errors\n\n| Error | Condition | Resolution |\n|-------|-----------|-------------|\n| TypeError | session scope without sessionId | Provide sessionId or use project scope |\n| ENOENT | Database file not found | Ensure project directory exists |\n| EACCES | Permission denied | Check file system permissions |\n| SQLITE_BUSY | Database locked | Retry operation or close other connections |\n\n### Cleanup on Error\n\nThe purge operation ensures database connections are properly closed:\n\n```typescript\nlet db: SessionDB | null = null;\ntry {\n  db = new SessionDB({ dbPath });\n  // ... operations\n} finally {\n  if (db) db.close();\n}\n```\n\nSource: [src/session/purge.ts:35-42](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n## Best Practices\n\n### Session Management\n\n1. Always provide explicit scope when calling purge operations\n2. Use session IDs consistently across your application\n3. Handle database errors with appropriate fallbacks\n4. Close database connections after operations\n\n### Performance Considerations\n\n1. Batch event insertions when possible\n2. Use project-scoped operations for complete cleanups\n3. Leverage FTS5 for text search instead of full table scans\n4. Clean up unused session data regularly\n\n### Data Integrity\n\n1. Verify hash calculations match across sessions\n2. Check database file existence before operations\n3. Use transactions for multi-step operations\n4. Maintain legacy hash support for backwards compatibility\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: mksglu/context-mode\n\nSummary: Found 23 potential pitfall items; 3 are high/blocking. Highest priority: installation - 来源证据：Feature Request: Add CodeBuddy Code support.\n\n## 1. installation · 来源证据：Feature Request: Add CodeBuddy Code support\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Feature Request: Add CodeBuddy Code support\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e09face1208e43d685be6c8ebf7015e9 | https://github.com/mksglu/context-mode/issues/651 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 2. installation · 来源证据：ctx_batch_execute corrupts heredoc commands by appending stderr redirection\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx_batch_execute corrupts heredoc commands by appending stderr redirection\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_6888a03e6d5b4d9492dff3e5efce4f48 | https://github.com/mksglu/context-mode/issues/656 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. installation · 来源证据：v1.0.146: plugin.json points to wrong skills path and stale MCP server path\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v1.0.146: plugin.json points to wrong skills path and stale MCP server path\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e1ebfb0450e44c198d3ff017d55a51d0 | https://github.com/mksglu/context-mode/issues/658 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 4. installation · 来源证据：OpenCode plugin registers hooks only -- never registers ctx_* tools\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：OpenCode plugin registers hooks only -- never registers ctx_* tools\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_d1ee350cd2374bb785a0628089fee355 | https://github.com/mksglu/context-mode/issues/637 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 5. installation · 来源证据：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.cla…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.claude/ instead of ~/.pi/\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8f49345b591f4f51afc650b8732da4d3 | https://github.com/mksglu/context-mode/issues/561 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 6. installation · 来源证据：Pi subagent fails: DatabaseLockedError - another context-mode server is already running\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi subagent fails: DatabaseLockedError - another context-mode server is already running\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e0a18821f52c4610a9109f8cb6920829 | https://github.com/mksglu/context-mode/issues/562 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 7. installation · 来源证据：[BUG]: Hardcoded storage path for many platforms\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: Hardcoded storage path for many platforms\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_b64e0c04c70b4726a0e860dc6a0954c9 | https://github.com/mksglu/context-mode/issues/649 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 8. installation · 来源证据：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_89e33c17dcfa452c8ad33ba344a9c6bb | https://github.com/mksglu/context-mode/issues/646 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 9. installation · 来源证据：[Bug]: Plugin-only installation does not work with OpenCode\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Plugin-only installation does not work with OpenCode\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_50609b9a9e2b4d4682713f28fd4c5d6d | https://github.com/mksglu/context-mode/issues/652 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 10. installation · 来源证据：ctx-upgrade leaves old server process running (zombie instance on upgrade)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx-upgrade leaves old server process running (zombie instance on upgrade)\n- User impact: 可能影响升级、迁移或版本选择。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_92a91d8bb13e4cf594229b3280c4d2eb | https://github.com/mksglu/context-mode/issues/559 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 11. installation · 来源证据：sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — deletes fresh symlinks whose targets are stale;…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — deletes fresh symlinks whose targets are stale; 4-char `lstatSync` fix\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ccef8bb7485f482f9bcb08b6cc2494b2 | https://github.com/mksglu/context-mode/issues/644 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 12. configuration · 可能修改宿主 AI 配置\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- User impact: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- Suggested check: 列出会写入的配置文件、目录和卸载/回滚步骤。\n- Guardrail action: 涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- Evidence: capability.host_targets | github_repo:1164477708 | https://github.com/mksglu/context-mode | host_targets=claude, claude_code\n\n## 13. configuration · 来源证据：No exclusive lock on SQLite database — multiple server instances cause unbounded WAL growth and query hangs\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：No exclusive lock on SQLite database — multiple server instances cause unbounded WAL growth and query hangs\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_a629676796f7486d9e185f643b260d07 | https://github.com/mksglu/context-mode/issues/560 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 14. configuration · 来源证据：Preview truncation slices UTF-16 surrogate pairs, producing orphan `\\uD83D` in tool_result and breaking the host API re…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Preview truncation slices UTF-16 surrogate pairs, producing orphan `\\uD83D` in tool_result and breaking the host API request\n- User impact: 可能影响升级、迁移或版本选择。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_d52bae5266e442cea5a1fa5b42f86c1a | https://github.com/mksglu/context-mode/issues/659 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 15. 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:1164477708 | https://github.com/mksglu/context-mode | README/documentation is current enough for a first validation pass.\n\n## 16. runtime · 来源证据：[BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP server reads from `<project-hash>.db` — `ctx_sta…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP server reads from `<project-hash>.db` — `ctx_stats` and timeline search degraded\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_cbceaf1c624d40049ac2151af7c1e83d | https://github.com/mksglu/context-mode/issues/645 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 17. 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:1164477708 | https://github.com/mksglu/context-mode | last_activity_observed missing\n\n## 18. 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:1164477708 | https://github.com/mksglu/context-mode | no_demo; severity=medium\n\n## 19. 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:1164477708 | https://github.com/mksglu/context-mode | no_demo; severity=medium\n\n## 20. security_permissions · 来源证据：PreToolUse hook fails on project paths containing spaces (macOS)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：PreToolUse hook fails on project paths containing spaces (macOS)\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_0e6f8fa845c0493db18d97fc48cf1b82 | https://github.com/mksglu/context-mode/issues/636 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 21. security_permissions · 来源证据：[BUG]: MCP bridge silently degrades on slow `initialize` — retry on timeout instead of failing permanently\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[BUG]: MCP bridge silently degrades on slow `initialize` — retry on timeout instead of failing permanently\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_c17fbb0a32674c7b9dad1eefe4a0c3d2 | https://github.com/mksglu/context-mode/issues/647 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 22. 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:1164477708 | https://github.com/mksglu/context-mode | issue_or_pr_quality=unknown\n\n## 23. 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:1164477708 | https://github.com/mksglu/context-mode | release_recency=unknown\n\n<!-- canonical_name: mksglu/context-mode; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "context-mode",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:1164477708",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/mksglu/context-mode"
        },
        {
          "evidence_id": "art_639e82c154234dada82faa1467629655",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/mksglu/context-mode#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "context-mode 说明书",
      "toc": [
        "https://github.com/mksglu/context-mode Project Manual",
        "Table of Contents",
        "Introduction to Context Mode",
        "Overview",
        "System Architecture",
        "Rules Health Dashboard",
        "Rule Structure",
        "Usage Tracking",
        "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": "dd8477cf066d2f839241875d3a0a5a54ca2771a3",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "package.json",
      "README.md",
      "docs/platform-support.md",
      "docs/UPSTREAM-CREDITS.md",
      "docs/jetbrains-copilot.md",
      "docs/adr/0004-stats-strict-compression-formula.md",
      "docs/adr/0001-sessiondb-multi-writer.md",
      "docs/adr/0002-tool-description-style.md",
      "docs/adr/0003-routing-deny-reasons.md",
      "docs/adapters/openclaw.md",
      "src/runPool.ts",
      "src/store-directory.ts",
      "src/lifecycle.ts",
      "src/runtime.ts",
      "src/server.ts",
      "src/types.ts",
      "src/db-base.ts",
      "src/store.ts",
      "src/exit-classify.ts",
      "src/security.ts",
      "src/truncate.ts",
      "src/cli.ts",
      "src/executor.ts",
      "src/fetch-cache.ts",
      "src/session/purge.ts",
      "src/session/project-attribution.ts",
      "src/session/db.ts",
      "src/session/snapshot.ts",
      "src/session/persist-tool-calls.ts",
      "src/session/extract.ts",
      "src/session/event-emit.ts",
      "src/session/analytics.ts",
      "src/util/claude-config.ts",
      "src/util/project-dir.ts",
      "src/util/plugin-cache-integrity.ts",
      "src/util/hook-config.ts",
      "src/util/sibling-mcp.ts",
      "src/adapters/client-map.ts",
      "src/adapters/base.ts",
      "src/adapters/types.ts"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "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": "# context-mode - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 context-mode 编译的 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_0004` supported 0.86\n- **希望把专业流程带进宿主 AI 的用户**：仓库包含 Skill 文档。 证据：`.claude/skills/context-mode-ops/SKILL.md`, `skills/context-mode/SKILL.md`, `skills/ctx-doctor/SKILL.md`, `skills/ctx-insight/SKILL.md` 等 Claim：`clm_0005` supported 0.86\n\n## 它能做什么\n\n- **AI Skill / Agent 指令资产库**（可做安装前预览）：项目包含可被宿主 AI 读取的 Skill 或 Agent 指令文件，可用于把专业流程带入 Claude、Codex、Cursor 等宿主。 证据：`.claude/skills/context-mode-ops/SKILL.md`, `skills/context-mode/SKILL.md`, `skills/ctx-doctor/SKILL.md`, `skills/ctx-insight/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **多宿主安装与分发**（需要安装后验证）：项目包含插件或 marketplace 配置，说明它面向一个或多个 AI 宿主的安装和分发。 证据：`.agents/plugins/marketplace.json`, `.claude-plugin/marketplace.json`, `.claude-plugin/plugin.json`, `.codex-plugin/plugin.json` 等 Claim：`clm_0002` supported 0.86\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n## 怎么开始\n\n- `/plugin marketplace add mksglu/context-mode` 证据：`README.md` Claim：`clm_0006` supported 0.86\n- `/plugin install context-mode@context-mode` 证据：`README.md` Claim：`clm_0007` supported 0.86\n- `claude mcp add context-mode -- npx -y context-mode` 证据：`README.md` Claim：`clm_0008` supported 0.86\n- `npm install -g context-mode` 证据：`README.md` Claim：`clm_0009` supported 0.86\n- `git clone https://github.com/mksglu/context-mode.git` 证据：`README.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_0004` supported 0.86\n- **适合人群线索：希望把专业流程带进宿主 AI 的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`.claude/skills/context-mode-ops/SKILL.md`, `skills/context-mode/SKILL.md`, `skills/ctx-doctor/SKILL.md`, `skills/ctx-insight/SKILL.md` 等 Claim：`clm_0005` supported 0.86\n- **能力存在：AI Skill / Agent 指令资产库**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`.claude/skills/context-mode-ops/SKILL.md`, `skills/context-mode/SKILL.md`, `skills/ctx-doctor/SKILL.md`, `skills/ctx-insight/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **能力存在：多宿主安装与分发**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`.agents/plugins/marketplace.json`, `.claude-plugin/marketplace.json`, `.claude-plugin/plugin.json`, `.codex-plugin/plugin.json` 等 Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0003` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0006` supported 0.86\n\n### 现在还不能相信\n\n- **工具权限边界不能在安装前相信。**（unverified）：MCP/tool 类项目通常会触碰文件、网络、浏览器或外部 API，必须真实检查权限和日志。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`.agents/plugins/marketplace.json`, `.claude-plugin/marketplace.json`, `.claude-plugin/plugin.json`, `.claude/skills/context-mode-ops/SKILL.md` 等\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。 证据：`.agents/plugins/marketplace.json`, `.claude-plugin/marketplace.json`, `.claude-plugin/plugin.json`, `.codex-plugin/plugin.json` 等\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`.agents/plugins/marketplace.json`, `.claude-plugin/marketplace.json`, `.claude-plugin/plugin.json`, `.claude/skills/context-mode-ops/SKILL.md` 等\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`.agents/plugins/marketplace.json`, `.claude-plugin/marketplace.json`, `.claude-plugin/plugin.json`, `.codex-plugin/plugin.json` 等\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- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\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- **宿主 AI 插件或 Skill 规则冲突**：新规则可能改变用户现有宿主 AI 的工作方式。 处理方式：安装前先检查插件 manifest 和 Skill 文件，必要时隔离测试。 证据：`.agents/plugins/marketplace.json`, `.claude-plugin/marketplace.json`, `.claude-plugin/plugin.json`, `.codex-plugin/plugin.json` 等 Claim：`clm_0012` supported 0.86\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0013` 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- **AI Skill / Agent 指令资产库**：先基于 role_skill_index / evidence_index 帮用户挑选可用角色、Skill 或工作流。 边界：可做安装前 Prompt 体验。 证据：`.claude/skills/context-mode-ops/SKILL.md`, `skills/context-mode/SKILL.md`, `skills/ctx-doctor/SKILL.md`, `skills/ctx-insight/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **多宿主安装与分发**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`.agents/plugins/marketplace.json`, `.claude-plugin/marketplace.json`, `.claude-plugin/plugin.json`, `.codex-plugin/plugin.json` 等 Claim：`clm_0002` supported 0.86\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n### 上下文规模\n\n- 文件总数：472\n- 重要文件覆盖：40/472\n- 证据索引条目：80\n- 角色 / Skill 条目：7\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请基于 context-mode 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 context-mode 当作安装前体验资产，而不是已安装工具或真实运行环境。\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请基于 context-mode 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 7 个角色 / Skill / 项目文档条目。\n\n- **context-mode-ops**（skill）：Manage context-mode GitHub issues, PRs, releases, and marketing with parallel subagent army. Orchestrates 10-20 dynamic agents per task. Use when triaging issues, reviewing PRs, releasing versions, writing LinkedIn posts, announcing releases, fixing bugs, merging contributions, validating ENV vars, testing adapters, or syncing branches. 激活提示：当用户任务与“context-mode-ops”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.claude/skills/context-mode-ops/SKILL.md`\n- **context-mode**（skill）： 激活提示：当用户任务与“context-mode”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`skills/context-mode/SKILL.md`\n- **ctx-doctor**（skill）： 激活提示：当用户任务与“ctx-doctor”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`skills/ctx-doctor/SKILL.md`\n- **ctx-insight**（skill）： 激活提示：当用户任务与“ctx-insight”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`skills/ctx-insight/SKILL.md`\n- **ctx-purge**（skill）： 激活提示：当用户任务与“ctx-purge”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`skills/ctx-purge/SKILL.md`\n- **ctx-stats**（skill）： 激活提示：当用户任务与“ctx-stats”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`skills/ctx-stats/SKILL.md`\n- **ctx-upgrade**（skill）： 激活提示：当用户任务与“ctx-upgrade”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`skills/ctx-upgrade/SKILL.md`\n\n## 证据索引\n\n- 共索引 80 条证据。\n\n- **context-mode**（documentation）：Save 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and native Cursor v1.7+ hook routing for context protection. 证据：`.cursor-plugin/README.md`\n- **context-mode — MANDATORY routing rules**（documentation）：context-mode — MANDATORY routing rules 证据：`CLAUDE.md`\n- **Context Mode**（documentation）：The other half of the context problem. 证据：`README.md`\n- **context-mode — MANDATORY routing rules**（documentation）：context-mode — MANDATORY routing rules 证据：`configs/antigravity/GEMINI.md`\n- **context-mode — MANDATORY routing rules**（documentation）：context-mode — MANDATORY routing rules 证据：`configs/claude-code/CLAUDE.md`\n- **context-mode — MANDATORY routing rules**（documentation）：context-mode — MANDATORY routing rules 证据：`configs/gemini-cli/GEMINI.md`\n- **Package**（package_manifest）：{ \"name\": \"context-mode\", \"version\": \"1.0.151\", \"description\": \"OpenClaw plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and intent-driven search.\", \"author\": { \"name\": \"Mert Koseoğlu\", \"url\": \"https://github.com/mksglu\" }, \"homepage\": \"https://github.com/mksglu/context-mode readme\", \"repository\": \"https://github.com/mksglu/context-mode\", \"license\": \"Elastic-2.0\", \"keywords\": \"openclaw\", \"mcp\", \"context-window\", \"sandbox\", \"code-execution\", \"fts5\", \"bm25\", \"playwright\", \"context7\" , \"openclaw\": { \"extensions\": \"./index.ts\" } } 证据：`.openclaw-plugin/package.json`\n- **Package**（package_manifest）：{ \"name\": \"memory-ui\", \"private\": true, \"type\": \"module\", \"imports\": { \" / \": \"./src/ \" }, \"scripts\": { \"dev\": \"vite dev --port 3000\", \"build\": \"vite build\", \"preview\": \"vite preview\", \"test\": \"vitest run\" }, \"dependencies\": { \"@base-ui/react\": \"^1.4.0\", \"@fontsource-variable/geist\": \"^5.2.8\", \"@tailwindcss/vite\": \"^4.1.18\", \"@tanstack/react-devtools\": \"latest\", \"@tanstack/react-router\": \"latest\", \"@tanstack/react-router-devtools\": \"latest\", \"@tanstack/router-plugin\": \"^1.132.0\", \"class-variance-authority\": \"^0.7.1\", \"clsx\": \"^2.1.1\", \"lucide-react\": \"^0.545.0\", \"react\": \"^19.2.0\", \"react-dom\": \"^19.2.0\", \"recharts\": \"^3.8.1\", \"shadcn\": \"^4.2.0\", \"tailwind-merge\": \"^3.5.0\", \"tailwindcss\": \"… 证据：`insight/package.json`\n- **Package**（package_manifest）：{ \"name\": \"context-mode\", \"version\": \"1.0.151\", \"type\": \"module\", \"description\": \"MCP plugin that saves 98% of your context window. Works with Claude Code, Gemini CLI, VS Code Copilot, OpenCode, and Codex CLI. Sandboxed code execution, FTS5 knowledge base, and intent-driven search.\", \"author\": \"Mert Koseoğlu\", \"license\": \"Elastic-2.0\", \"keywords\": \"mcp\", \"model-context-protocol\", \"claude\", \"claude-code\", \"gemini-cli\", \"vscode-copilot\", \"opencode\", \"openclaw\", \"codex-cli\", \"context-window\", \"sandbox\", \"code-execution\", \"fts5\", \"bm25\", \"pi-package\" , \"repository\": { \"type\": \"git\", \"url\": \"https://github.com/mksglu/context-mode\" }, \"homepage\": \"https://github.com/mksglu/context-mode readme\", \"… 证据：`package.json`\n- **Package**（package_manifest）：{ \"name\": \"context-mode\", \"version\": \"1.0.151\", \"description\": \"Context-mode extension for Pi coding agent — session continuity and context window protection\", \"main\": \"index.ts\", \"dependencies\": { \"better-sqlite3\": \"^11.0.0\" } } 证据：`.pi/extensions/context-mode/package.json`\n- **Contributing to context-mode**（documentation）：This project is licensed under the Elastic License 2.0 ELv2 and moves forward with your support. Every issue, every PR, every idea matters. 证据：`CONTRIBUTING.md`\n- **OWNER OPERATING DIRECTIVE — ABSOLUTE, NON-NEGOTIABLE PREAMBLE**（skill_instruction）：OWNER OPERATING DIRECTIVE — ABSOLUTE, NON-NEGOTIABLE PREAMBLE 证据：`.claude/skills/context-mode-ops/SKILL.md`\n- **Context Mode: Default for All Large Output**（skill_instruction）：Context Mode: Default for All Large Output 证据：`skills/context-mode/SKILL.md`\n- **Context Mode Doctor**（skill_instruction）：Run diagnostics and display results directly in the conversation. 证据：`skills/ctx-doctor/SKILL.md`\n- **Context Mode Insight**（skill_instruction）：Open the personal analytics dashboard in the browser. 证据：`skills/ctx-insight/SKILL.md`\n- **Context Mode Purge**（skill_instruction）：Permanently deletes session data for this project. Two scopes are supported issue 520 : 证据：`skills/ctx-purge/SKILL.md`\n- **Context Mode Stats**（skill_instruction）：Show context savings for the current session. 证据：`skills/ctx-stats/SKILL.md`\n- **Context Mode Upgrade**（skill_instruction）：Pull latest from GitHub and reinstall the plugin. 证据：`skills/ctx-upgrade/SKILL.md`\n- **Marketplace**（structured_config）：{ \"name\": \"context-mode\", \"owner\": { \"name\": \"Mert Koseoğlu\", \"email\": \"code.bm.ksglu@gmail.com\" }, \"metadata\": { \"description\": \"Claude Code plugins by Mert Koseoğlu\", \"version\": \"1.0.151\" }, \"plugins\": { \"name\": \"context-mode\", \"source\": \"./\", \"description\": \"Claude Code MCP plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and intent-driven search.\", \"version\": \"1.0.151\", \"author\": { \"name\": \"Mert Koseoğlu\" }, \"category\": \"development\", \"keywords\": \"mcp\", \"context-window\", \"sandbox\", \"code-execution\", \"fts5\", \"bm25\", \"playwright\", \"context7\" } } 证据：`.claude-plugin/marketplace.json`\n- **Plugin**（structured_config）：{ \"name\": \"context-mode\", \"version\": \"1.0.151\", \"description\": \"MCP server that saves 98% of your context window with session continuity. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and automatic state restore across compactions.\", \"author\": { \"name\": \"Mert Koseoğlu\", \"url\": \"https://github.com/mksglu\" }, \"homepage\": \"https://github.com/mksglu/context-mode readme\", \"repository\": \"https://github.com/mksglu/context-mode\", \"license\": \"Elastic-2.0\", \"keywords\": \"mcp\", \"context-window\", \"sandbox\", \"code-execution\", \"fts5\", \"bm25\", \"playwright\", \"context7\" , \"mcpServers\": { \"context-mode\": { \"command\": \"node\", \"args\": \"${CLAUDE PLUGIN ROOT}/start.mjs\" } }, \"sk… 证据：`.claude-plugin/plugin.json`\n- **Plugin**（structured_config）：{ \"name\": \"context-mode\", \"version\": \"1.0.151\", \"description\": \"MCP server that saves 98% of your context window with session continuity. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and automatic state restore across compactions.\", \"author\": { \"name\": \"Mert Koseoğlu\", \"url\": \"https://github.com/mksglu\" }, \"homepage\": \"https://github.com/mksglu/context-mode readme\", \"repository\": \"https://github.com/mksglu/context-mode\", \"license\": \"Elastic-2.0\", \"keywords\": \"mcp\", \"context-window\", \"sandbox\", \"code-execution\", \"fts5\", \"bm25\", \"playwright\", \"context7\" , \"mcpServers\": \"./.codex-plugin/mcp.json\", \"hooks\": \"./.codex-plugin/hooks.json\", \"skills\": \"./skills/\",… 证据：`.codex-plugin/plugin.json`\n- **Plugin**（structured_config）：{ \"name\": \"context-mode\", \"version\": \"1.0.151\", \"description\": \"Cursor plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, intent-driven search, and native Cursor v1.7+ hook routing for context protection.\", \"author\": { \"name\": \"Mert Koseoğlu\", \"email\": \"code.bm.ksglu@gmail.com\" }, \"homepage\": \"https://github.com/mksglu/context-mode readme\", \"repository\": \"https://github.com/mksglu/context-mode\", \"license\": \"Elastic-2.0\", \"logo\": \".cursor-plugin/assets/logo.png\", \"keywords\": \"mcp\", \"context-window\", \"sandbox\", \"code-execution\", \"fts5\", \"bm25\", \"playwright\", \"context7\", \"cursor\" , \"rules\": \"./configs/cursor/context-mo… 证据：`.cursor-plugin/plugin.json`\n- **Marketplace**（structured_config）：{ \"name\": \"context-mode\", \"interface\": { \"displayName\": \"context-mode\" }, \"plugins\": { \"name\": \"context-mode\", \"source\": { \"source\": \"local\", \"path\": \"./plugins/context-mode\" }, \"policy\": { \"installation\": \"AVAILABLE\", \"authentication\": \"ON INSTALL\" }, \"category\": \"Productivity\" } } 证据：`.agents/plugins/marketplace.json`\n- **Acceptance**（source_file）：By using the software, you agree to all of the terms and conditions below. 证据：`LICENSE`\n- **Upstream Skill Credits**（documentation）：context-mode references a small set of operating-discipline skills authored by Matt Pocock MIT . They are the operational backbone of the context-mode-ops https://github.com/mksglu/context-mode/tree/next/.claude/skills/context-mode-ops skill /diagnose , /tdd , /grill-me , /grill-with-docs , /improve-codebase-architecture . 证据：`docs/UPSTREAM-CREDITS.md`\n- **JetBrains Copilot Setup**（documentation）：Setup guide for using context-mode with JetBrains IDEs IntelliJ IDEA, WebStorm, PyCharm, etc. via the GitHub Copilot plugin. 证据：`docs/jetbrains-copilot.md`\n- **Platform Support Matrix**（documentation）：This document provides a comprehensive comparison of all platforms supported by context-mode, including their hook paradigms, capabilities, configuration, and known limitations. 证据：`docs/platform-support.md`\n- **OpenClaw Adapter**（documentation）：context-mode plugin for the OpenClaw https://github.com/openclaw gateway, targeting Pi Agent sessions. 证据：`docs/adapters/openclaw.md`\n- **ADR 0001 — SessionDB is multi-writer-safe**（documentation）：ADR 0001 — SessionDB is multi-writer-safe 证据：`docs/adr/0001-sessiondb-multi-writer.md`\n- **ADR-0002 — Tool description voice and structure**（documentation）：ADR-0002 — Tool description voice and structure 证据：`docs/adr/0002-tool-description-style.md`\n- **ADR-0003 — Routing deny reasons: redirect ≠ restriction**（documentation）：ADR-0003 — Routing deny reasons: redirect ≠ restriction 证据：`docs/adr/0003-routing-deny-reasons.md`\n- **ADR-0004 — Stats display uses strict-compression formula**（documentation）：ADR-0004 — Stats display uses strict-compression formula 证据：`docs/adr/0004-stats-strict-compression-formula.md`\n- **What / Why / How**（documentation）：- Claude Code - Cursor - VS Code Copilot GitHub Copilot - JetBrains Copilot - Gemini CLI - Qwen Code - OpenCode - KiloCode - Codex CLI - OpenClaw Pi Agent - Pi - Kiro - Antigravity - Zed - All platforms 证据：`.github/PULL_REQUEST_TEMPLATE.md`\n- **Context Mode — Benchmark Results**（documentation）：Benchmarked against real outputs from popular Claude Code MCP servers, Skills, and dev tools. All fixtures captured from actual tool invocations — not synthetic data. 证据：`BENCHMARK.md`\n- **context-mode v1.0.148 — Critical stats accuracy fix**（documentation）：context-mode v1.0.148 — Critical stats accuracy fix 证据：`release-notes-v1.0.148.md`\n- **Dynamic Agent Organization**（documentation）：Every issue and PR gets a custom team. Agents are spawned based on what the task touches — never a static roster. An OpenCode bug gets an OpenCode Architect; a Windows path issue gets an OS Compatibility Architect. A single task may spawn 10-20 agents. 证据：`.claude/skills/context-mode-ops/agent-teams.md`\n- **Communication Templates**（documentation）：Tone: warm, professional, technical, grateful. Always put testing responsibility on the contributor. 证据：`.claude/skills/context-mode-ops/communication.md`\n- **Marketing workflow**（documentation）：User says: \"linkedin post\", \"marketing\", \"announce release\", \"write post\", \"share update\" 证据：`.claude/skills/context-mode-ops/marketing.md`\n- **Release Workflow**（documentation）：User says: \"release\", \"version bump\", \"npm publish\", \"ship it\" 证据：`.claude/skills/context-mode-ops/release.md`\n- **Review PR Workflow**（documentation）：User says: \"review PR N\", \"merge PR N\", \"check PR N\" 证据：`.claude/skills/context-mode-ops/review-pr.md`\n- **Test-Driven Development**（documentation）：THIS FILE IS MANDATORY. Every agent, every Staff Engineer, every Architect MUST follow this. If you skip TDD, your work will be REJECTED. There are no exceptions. Do NOT write implementation code before you have a failing test. 证据：`.claude/skills/context-mode-ops/tdd.md`\n- **Triage Issue Workflow**（documentation）：User says: \"triage issue N\", \"fix issue N\", \"analyze issue N\" 证据：`.claude/skills/context-mode-ops/triage-issue.md`\n- **Validation Patterns**（documentation）：Cross-cutting validation rules used by ALL workflows triage, review, release . 证据：`.claude/skills/context-mode-ops/validation.md`\n- **context-mode — MANDATORY routing rules**（documentation）：context-mode — MANDATORY routing rules 证据：`configs/jetbrains-copilot/copilot-instructions.md`\n- **context-mode — MANDATORY routing rules**（documentation）：context-mode — MANDATORY routing rules 证据：`configs/kiro/KIRO.md`\n- **context-mode — MANDATORY routing rules**（documentation）：context-mode — MANDATORY routing rules 证据：`configs/omp/SYSTEM.md`\n- **context-mode — MANDATORY routing rules**（documentation）：context-mode — MANDATORY routing rules 证据：`configs/qwen-code/QWEN.md`\n- **context-mode — MANDATORY routing rules**（documentation）：context-mode — MANDATORY routing rules 证据：`configs/vscode-copilot/copilot-instructions.md`\n- **Anti-Patterns: Common Mistakes with execute / execute file**（documentation）：Anti-Patterns: Common Mistakes with execute / execute file 证据：`skills/context-mode/references/anti-patterns.md`\n- **JavaScript / TypeScript Patterns for execute**（documentation）：JavaScript / TypeScript Patterns for execute 证据：`skills/context-mode/references/patterns-javascript.md`\n- **Python Patterns for execute**（documentation）：Practical patterns for using execute with language: python . All examples use Python standard library only no pip installs required . 证据：`skills/context-mode/references/patterns-python.md`\n- **Shell Patterns for execute**（documentation）：Practical patterns for using execute with language: shell . Best for piping, filtering, and leveraging native OS tools. 证据：`skills/context-mode/references/patterns-shell.md`\n- **Create Server Component Page with Data Fetching in Next.js App Directory**（documentation）：Create Server Component Page with Data Fetching in Next.js App Directory 证据：`tests/fixtures/context7-nextjs-docs.md`\n- **useEffect Hook Reference**（documentation）：Source: https://react.dev/reference/react/useEffect 证据：`tests/fixtures/context7-react-docs.md`\n- **Deno Unit Test Example for Supabase Edge Functions**（documentation）：Deno Unit Test Example for Supabase Edge Functions 证据：`tests/fixtures/context7-supabase-edge.md`\n- **Apply responsive flex layout with Tailwind CSS**（documentation）：Apply responsive flex layout with Tailwind CSS 证据：`tests/fixtures/context7-tailwind-docs.md`\n- **Settings**（structured_config）：{ \"permissions\": { \"deny\": \"Bash sudo \", \"Bash rm -rf / \", \"Read .env \", \"Read /.env \" , \"allow\": \"Bash git: \", \"Bash ls: \", \"Bash npm: \", \"Bash npx: \", \"Bash cat: \", \"Bash echo: \" } } 证据：`.claude/settings.json`\n- **Hooks**（structured_config）：{ \"hooks\": { \"PreToolUse\": { \"matcher\": \"local shell shell shell command exec command Bash Shell apply patch Edit Write grep files ctx execute ctx execute file ctx batch execute ctx fetch and index ctx search ctx index mcp \", \"hooks\": { \"type\": \"command\", \"command\": \"node \\\"${PLUGIN ROOT}/hooks/codex/pretooluse.mjs\\\"\" } } , \"PostToolUse\": { \"hooks\": { \"type\": \"command\", \"command\": \"node \\\"${PLUGIN ROOT}/hooks/codex/posttooluse.mjs\\\"\" } } , \"SessionStart\": { \"hooks\": { \"type\": \"command\", \"command\": \"node \\\"${PLUGIN ROOT}/hooks/codex/sessionstart.mjs\\\"\" } } , \"PreCompact\": { \"hooks\": { \"type\": \"command\", \"command\": \"node \\\"${PLUGIN ROOT}/hooks/codex/precompact.mjs\\\"\" } } , \"UserPromptSubmit\":… 证据：`.codex-plugin/hooks.json`\n- **Mcp**（structured_config）：{ \"mcpServers\": { \"context-mode\": { \"command\": \"node\", \"args\": \"./start.mjs\" , \"cwd\": \".\" } } } 证据：`.codex-plugin/mcp.json`\n- **Openclaw.Plugin**（structured_config）：{ \"id\": \"context-mode\", \"name\": \"Context Mode\", \"kind\": \"tool\", \"description\": \"OpenClaw plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and intent-driven search.\", \"version\": \"1.0.151\", \"sandbox\": { \"mode\": \"permissive\", \"filesystem access\": \"full\", \"system access\": \"full\" }, \"configSchema\": { \"type\": \"object\", \"properties\": { \"enabled\": { \"type\": \"boolean\", \"default\": true, \"description\": \"Enable or disable the context-mode plugin.\" } }, \"additionalProperties\": false } } 证据：`.openclaw-plugin/openclaw.plugin.json`\n- 其余 20 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`.cursor-plugin/README.md`, `CLAUDE.md`, `README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`.cursor-plugin/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- **Introduction to Context Mode**：importance `high`\n  - source_paths: README.md, BENCHMARK.md\n- **Core Concepts**：importance `high`\n  - source_paths: src/types.ts, src/runtime.ts, src/executor.ts\n- **Getting Started**：importance `high`\n  - source_paths: CLAUDE.md, CONTRIBUTING.md, configs/claude-code/CLAUDE.md, configs/gemini-cli/GEMINI.md\n- **Architecture Overview**：importance `high`\n  - source_paths: src/server.ts, src/cli.ts, src/adapters/types.ts, src/adapters/base.ts, start.mjs\n- **Platform Adapters**：importance `high`\n  - source_paths: src/adapters/claude-code/index.ts, src/adapters/cursor/index.ts, src/adapters/codex/index.ts, src/adapters/gemini-cli/index.ts, src/adapters/openclaw/index.ts\n- **Hooks System**：importance `high`\n  - source_paths: hooks/pretooluse.mjs, hooks/posttooluse.mjs, hooks/precompact.mjs, hooks/sessionstart.mjs, hooks/hooks.json\n- **Context Saving**：importance `high`\n  - source_paths: src/search/auto-memory.ts, src/truncate.ts, src/fetch-cache.ts, hooks/core/routing.mjs\n- **Session Continuity**：importance `high`\n  - source_paths: src/session/db.ts, src/session/snapshot.ts, src/session/extract.ts, src/session/event-emit.ts, src/search/unified.ts\n\n## Repo Inspection Evidence\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `dd8477cf066d2f839241875d3a0a5a54ca2771a3`\n- inspected_files: `package.json`, `README.md`, `docs/platform-support.md`, `docs/UPSTREAM-CREDITS.md`, `docs/jetbrains-copilot.md`, `docs/adr/0004-stats-strict-compression-formula.md`, `docs/adr/0001-sessiondb-multi-writer.md`, `docs/adr/0002-tool-description-style.md`, `docs/adr/0003-routing-deny-reasons.md`, `docs/adapters/openclaw.md`, `src/runPool.ts`, `src/store-directory.ts`, `src/lifecycle.ts`, `src/runtime.ts`, `src/server.ts`, `src/types.ts`, `src/db-base.ts`, `src/store.ts`, `src/exit-classify.ts`, `src/security.ts`\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: 来源证据：Feature Request: Add CodeBuddy Code support\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Feature Request: Add CodeBuddy Code support\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_e09face1208e43d685be6c8ebf7015e9 | https://github.com/mksglu/context-mode/issues/651 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\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: 来源证据：ctx_batch_execute corrupts heredoc commands by appending stderr redirection\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx_batch_execute corrupts heredoc commands by appending stderr redirection\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_6888a03e6d5b4d9492dff3e5efce4f48 | https://github.com/mksglu/context-mode/issues/656 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\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: 来源证据：v1.0.146: plugin.json points to wrong skills path and stale MCP server path\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v1.0.146: plugin.json points to wrong skills path and stale MCP server path\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_e1ebfb0450e44c198d3ff017d55a51d0 | https://github.com/mksglu/context-mode/issues/658 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\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: 来源证据：OpenCode plugin registers hooks only -- never registers ctx_* tools\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：OpenCode plugin registers hooks only -- never registers ctx_* tools\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_d1ee350cd2374bb785a0628089fee355 | https://github.com/mksglu/context-mode/issues/637 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\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: 来源证据：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.cla…\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.claude/ instead of ~/.pi/\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_8f49345b591f4f51afc650b8732da4d3 | https://github.com/mksglu/context-mode/issues/561 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\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: 来源证据：Pi subagent fails: DatabaseLockedError - another context-mode server is already running\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi subagent fails: DatabaseLockedError - another context-mode server is already running\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_e0a18821f52c4610a9109f8cb6920829 | https://github.com/mksglu/context-mode/issues/562 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\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 7: 来源证据：[BUG]: Hardcoded storage path for many platforms\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: Hardcoded storage path for many platforms\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_b64e0c04c70b4726a0e860dc6a0954c9 | https://github.com/mksglu/context-mode/issues/649 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\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 8: 来源证据：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_89e33c17dcfa452c8ad33ba344a9c6bb | https://github.com/mksglu/context-mode/issues/646 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\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 9: 来源证据：[Bug]: Plugin-only installation does not work with OpenCode\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Plugin-only installation does not work with OpenCode\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_50609b9a9e2b4d4682713f28fd4c5d6d | https://github.com/mksglu/context-mode/issues/652 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\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 10: 来源证据：ctx-upgrade leaves old server process running (zombie instance on upgrade)\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx-upgrade leaves old server process running (zombie instance on upgrade)\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_92a91d8bb13e4cf594229b3280c4d2eb | https://github.com/mksglu/context-mode/issues/559 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\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: mksglu/context-mode\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: claude, claude_code\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- No blockers.\n\n## Project-Specific Pitfalls\n\n- 来源证据：Feature Request: Add CodeBuddy Code support (high): 可能增加新用户试用和生产接入成本。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：ctx_batch_execute corrupts heredoc commands by appending stderr redirection (high): 可能增加新用户试用和生产接入成本。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：v1.0.146: plugin.json points to wrong skills path and stale MCP server path (high): 可能增加新用户试用和生产接入成本。 Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：OpenCode plugin registers hooks only -- never registers ctx_* tools (medium): 可能增加新用户试用和生产接入成本。 Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.cla… (medium): 可能增加新用户试用和生产接入成本。 Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\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/mksglu/context-mode Project Manual\n\nGenerated on: 2026-05-24 22:22:50 UTC\n\n## Table of Contents\n\n- [Introduction to Context Mode](#introduction)\n- [Core Concepts](#core-concepts)\n- [Getting Started](#getting-started)\n- [Architecture Overview](#architecture-overview)\n- [Platform Adapters](#platform-adapters)\n- [Hooks System](#hooks-system)\n- [Context Saving](#context-saving)\n- [Session Continuity](#session-continuity)\n- [Think in Code Paradigm](#think-in-code)\n- [Session Storage](#session-storage)\n\n<a id='introduction'></a>\n\n## Introduction to Context Mode\n\n### Related Pages\n\nRelated topics: [Core Concepts](#core-concepts), [Getting Started](#getting-started)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [README.md](https://github.com/mksglu/context-mode/blob/main/README.md)\n- [BENCHMARK.md](https://github.com/mksglu/context-mode/blob/main/BENCHMARK.md)\n- [insight/src/routes/index.tsx](https://github.com/mksglu/context-mode/blob/main/insight/src/routes/index.tsx)\n</details>\n\n# Introduction to Context Mode\n\nContext Mode is a plugin-based system designed to manage and orchestrate instruction rules for AI language models. The system provides a flexible framework for loading, tracking, and maintaining rules that shape how AI models interpret and respond to various scenarios.\n\n## Overview\n\nContext Mode operates as an extensible plugin architecture that allows developers to define custom rules and instruction sets. These rules are loaded dynamically and can be applied to modify the behavior of AI interactions without requiring changes to the core system.\n\n### Core Concepts\n\nThe system revolves around the concept of **rules** - JSON or YAML files that contain instruction templates and behavioral guidelines. Each rule can specify:\n\n- The context in which it applies\n- The instruction format to follow\n- Associated metadata for tracking usage\n\n### Key Features\n\n| Feature | Description |\n|---------|-------------|\n| Plugin Architecture | Extensible system for loading custom rule handlers |\n| Rule Freshness Tracking | Monitors when rules were last used or updated |\n| Load Counting | Tracks how frequently each rule is accessed |\n| Health Monitoring | Provides insights into rule maintenance status |\n\n## System Architecture\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Context Mode Core]\n    B --> C[Rule Loader]\n    C --> D[Plugin Registry]\n    D --> E[Rule Files]\n    E --> F[instruction files]\n    F --> G[Loaded Rules]\n    G --> H[AI Response]\n    \n    I[Health Monitor] --> D\n    J[Freshness Tracker] --> D\n```\n\n### Components\n\nThe system consists of several interconnected components:\n\n1. **Core Engine** - Handles request routing and rule application\n2. **Plugin Registry** - Maintains registered plugins and their configurations\n3. **Rule Loader** - Dynamically loads and parses rule definitions\n4. **Health Monitor** - Tracks system metrics and rule usage statistics\n5. **Freshness Tracker** - Records when rules were last accessed\n\n## Rules Health Dashboard\n\nThe Insight module provides a visual interface for monitoring rule health. This component displays critical metrics about the rule system.\n\n### Metrics Displayed\n\n| Metric | Description | Data Source |\n|--------|-------------|-------------|\n| Total Rules | Number of active rules in the system | `rulesFreshness.length` |\n| Most Loaded | Rule with highest usage count | `top.load_count` |\n| Load Count | Number of times a rule has been invoked | `r.load_count` |\n| Last Seen | Timestamp of last rule access | `r.last_seen` |\n\n### Dashboard Components\n\nThe `Mini` component is used throughout the dashboard to display compact metric cards:\n\n- **Rules** - Shows total count or custom value\n- **Most Loaded** - Displays the most frequently used rule name\n- **Loads** - Shows the load count for the top rule\n\n### Freshness Calculation\n\nRule freshness is calculated by comparing the current time with the `last_seen` timestamp:\n\n```typescript\nconst diff = Date.now() - new Date(r.last_seen).getTime();\nconst days = Math.floor(diff / 86400000);\n```\n\nResults are displayed as:\n\n| Days | Display |\n|------|---------|\n| 0 | \"today\" |\n| 1 | \"1d ago\" |\n| >1 | \"{N}d ago\" |\n\nSource: [insight/src/routes/index.tsx:1-40](https://github.com/mksglu/context-mode/blob/main/insight/src/routes/index.tsx)\n\n## Rule Structure\n\nRules are organized in a directory structure with each rule defined as a separate file. The system extracts the rule name from the file path:\n\n```typescript\nconst name = r.rule_path?.split(\"/\").pop() || r.rule_path;\n```\n\nThis approach ensures:\n\n- Unique identification of each rule\n- Hierarchical organization of related rules\n- Easy traversal and discovery of rule files\n\n## Usage Tracking\n\nThe system maintains detailed usage statistics for each rule:\n\n| Field | Type | Purpose |\n|-------|------|---------|\n| `rule_path` | string | Full path to the rule file |\n| `load_count` | number | Number of times the rule was loaded |\n| `last_seen` | timestamp | When the rule was last accessed |\n\n## Integration with AI Systems\n\nContext Mode integrates with AI language models by providing structured instruction templates. When a request is processed:\n\n1. The system identifies relevant rules based on context\n2. Rules are loaded and merged into the instruction prompt\n3. The enhanced prompt is sent to the AI model\n4. Usage statistics are updated in real-time\n\n## Performance Considerations\n\nThe Insight dashboard limits the displayed rules to the 6 most recently active rules to optimize rendering performance:\n\n```typescript\n{data.rulesFreshness.slice(0, 6).map((r, i) => { ... })}\n```\n\nThis pagination approach ensures the UI remains responsive even with thousands of rules in the system.\n\n## Best Practices\n\n- **Maintain Rule Files** - Regularly update instruction files to ensure they remain relevant\n- **Monitor Freshness** - Review the Health Dashboard to identify stale rules\n- **Track Usage** - Use load counts to identify frequently used rules that may need optimization\n- **Organize Hierarchically** - Use descriptive file paths for easy rule discovery\n\n## Conclusion\n\nContext Mode provides a robust foundation for managing AI instruction sets through its plugin-based architecture. The built-in health monitoring and freshness tracking features enable developers to maintain high-quality, well-organized rule systems that evolve with application requirements.\n\n---\n\n<a id='core-concepts'></a>\n\n## Core Concepts\n\n### Related Pages\n\nRelated topics: [Context Saving](#context-saving), [Session Continuity](#session-continuity), [Think in Code Paradigm](#think-in-code)\n\nThe provided context only contains the `web/index.html` landing page file repeated multiple times. The actual source code files listed in the `<details>` block (src/types.ts, src/runtime.ts, src/executor.ts) are not present in the retrieved context.\n\nTo generate an accurate and comprehensive \"Core Concepts\" wiki page that:\n\n- Explains the actual implementation architecture\n- Includes proper Mermaid diagrams for workflows and data flows\n- Provides accurate API documentation with parameters\n- Cites specific line numbers from source files\n- Describes the actual data models and types\n\nI would need access to the TypeScript source files from the repository, not just the web landing page.\n\n**What I can see from the landing page:**\n\nThe plugin is described as an MCP (Model Context Protocol) plugin that:\n- Works with Claude Code, Cursor, Copilot, and 15+ other platforms\n- Sandboxes tool output and indexes it into FTS5 (SQLite Full-Text Search)\n- Claims to keep 98% of tool output out of the conversation\n- Extends context window usage by approximately 30x\n\n**To proceed with generating the full wiki page, please provide:**\n\n1. `src/types.ts` - Type definitions and interfaces\n2. `src/runtime.ts` - Core runtime logic\n3. `src/executor.ts` - Tool execution handling\n4. Any additional source files relevant to core functionality (database handling, MCP protocol implementation, configuration management, etc.)\n\nOnce these files are provided, I can generate a detailed technical wiki page with accurate code citations, architecture diagrams, and implementation details.\n\n---\n\n<a id='getting-started'></a>\n\n## Getting Started\n\n### Related Pages\n\nRelated topics: [Introduction to Context Mode](#introduction), [Platform Adapters](#platform-adapters)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/CLAUDE.md)\n- [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)\n- [configs/claude-code/CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/configs/claude-code/CLAUDE.md)\n- [configs/gemini-cli/GEMINI.md](https://github.com/mksglu/context-mode/blob/main/configs/gemini-cli/GEMINI.md)\n</details>\n\n# Getting Started\n\nWelcome to the context-mode project. This guide provides everything you need to set up, understand, and start contributing to this codebase.\n\n## Overview\n\ncontext-mode is a plugin-based system designed to manage and display contextual knowledge chunks in a modular architecture. The system provides a flexible way to organize, retrieve, and present information through a plugin ecosystem that can be configured for different AI assistants and CLI tools.\n\n**Key Characteristics:**\n\n| Attribute | Value |\n|-----------|-------|\n| Architecture | Plugin-based modular system |\n| Language | TypeScript, React |\n| UI Framework | shadcn/ui components |\n| Routing | Dynamic routes with hash-based identifiers |\n| Data Model | Chunk-based content retrieval |\n\nSource: [CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/CLAUDE.md)\n\n## Prerequisites\n\nBefore getting started, ensure your development environment meets the following requirements:\n\n### System Requirements\n\n- Node.js 18.x or later\n- pnpm package manager\n- Git version control\n- A modern code editor (VS Code recommended)\n\n### Environment Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/mksglu/context-mode.git\n\n# Navigate to the project directory\ncd context-mode\n\n# Install dependencies\npnpm install\n```\n\nSource: [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)\n\n## Project Structure\n\nThe repository follows a plugin-oriented directory structure:\n\n```\ncontext-mode/\n├── configs/                    # Configuration files for different AI tools\n│   ├── claude-code/           # Claude Code integration\n│   └── gemini-cli/            # Gemini CLI integration\n├── insight/                    # Core UI application\n│   └── src/\n│       └── routes/            # Dynamic route handlers\n├── plugins/                    # Plugin implementations\n└── [documentation files]      # Root-level guides\n```\n\n### Plugin Architecture\n\nThe system supports multiple AI assistant configurations through its plugin architecture:\n\n| Plugin | Purpose |\n|--------|---------|\n| `claude-code` | Integration for Claude Code AI assistant |\n| `gemini-cli` | Integration for Google Gemini CLI |\n\nEach plugin directory contains its own configuration that defines how context is processed and displayed.\n\nSource: [configs/claude-code/CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/configs/claude-code/CLAUDE.md)\nSource: [configs/gemini-cli/GEMINI.md](https://github.com/mksglu/context-mode/blob/main/configs/gemini-cli/GEMINI.md)\n\n## Running the Application\n\n### Development Mode\n\nTo start the development server:\n\n```bash\npnpm dev\n```\n\nThis will launch the application in development mode with hot reloading enabled.\n\n### Build for Production\n\n```bash\npnpm build\n```\n\n### Preview Production Build\n\n```bash\npnpm preview\n```\n\nSource: [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)\n\n## Understanding the UI Components\n\nThe frontend uses shadcn/ui components for building the interface. Key components used in the application include:\n\n### Collapsible Cards\n\nThe knowledge chunks are displayed using collapsible card components:\n\n```tsx\n<Collapsible>\n  <CollapsibleTrigger>\n    <CardHeader>\n      <CardTitle>{chunk.title}</CardTitle>\n    </CardHeader>\n  </CollapsibleTrigger>\n  <CollapsibleContent>\n    <CardContent>\n      <pre className=\"text-xs\">{chunk.content}</pre>\n    </CardContent>\n  </CollapsibleContent>\n</Collapsible>\n```\n\n### Content Display\n\nContent chunks are rendered with specific styling:\n\n| Property | Value | Purpose |\n|----------|-------|---------|\n| Container | `max-h-80 overflow-y-auto` | Scrollable with max height |\n| Border | `border-border/50` | Subtle border styling |\n| Text | `text-xs font-mono` | Monospace code display |\n| Whitespace | `whitespace-pre-wrap` | Preserve formatting |\n\nSource: [insight/src/routes/knowledge_.$dbHash.$sourceId.tsx](https://github.com/mksglu/context-mode/blob/main/insight/src/routes/knowledge_.$dbHash.$sourceId.tsx)\n\n## Dynamic Routing\n\nThe application uses file-based routing with dynamic parameters:\n\n### Route Pattern\n\n```\n/knowledge/:dbHash/:sourceId\n```\n\n| Parameter | Description |\n|-----------|-------------|\n| `dbHash` | Database hash identifier for the knowledge source |\n| `sourceId` | Unique identifier for the specific content source |\n\n### Data Flow\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Dynamic Route]\n    B --> C[dbHash Parameter]\n    B --> D[sourceId Parameter]\n    C --> E[Knowledge Lookup]\n    D --> E\n    E --> F[Chunk Content Retrieved]\n    F --> G[Collapsible Card Rendered]\n    G --> H[User Expands Card]\n    H --> I[Content Displayed]\n```\n\n## Configuration for AI Assistants\n\ncontext-mode provides specific configuration files for different AI assistants:\n\n### Claude Code Configuration\n\nCreate or modify `.claude/` directory with `CLAUDE.md` containing project-specific instructions.\n\nSource: [configs/claude-code/CLAUDE.md](https://github.com/mksglu/context-mode/blob/main/configs/claude-code/CLAUDE.md)\n\n### Gemini CLI Configuration\n\nThe Gemini CLI integration uses a dedicated configuration file to understand project context.\n\nSource: [configs/gemini-cli/GEMINI.md](https://github.com/mksglu/context-mode/blob/main/configs/gemini-cli/GEMINI.md)\n\n## Development Workflow\n\n### 1. Making Changes\n\n1. Create a feature branch from `main`\n2. Make your changes following the project's code style\n3. Test locally using `pnpm dev`\n4. Submit changes for review\n\n### 2. Code Style Guidelines\n\n- Use TypeScript for all new code\n- Follow existing component patterns\n- Include proper type definitions\n- Write meaningful commit messages\n\n### 3. Testing\n\n```bash\n# Run unit tests\npnpm test\n\n# Run linting\npnpm lint\n```\n\nSource: [CONTRIBUTING.md](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)\n\n## Common Tasks\n\n### Adding a New Plugin\n\n1. Create a new directory under `configs/`\n2. Add configuration files specific to the AI tool\n3. Update documentation to reflect the new integration\n\n### Modifying the UI\n\nThe main UI components are located in `insight/src/routes/`. The knowledge display component handles rendering of content chunks with the following structure:\n\n```mermaid\ngraph LR\n    A[Chunk Data] --> B[Badge Component]\n    A --> C[Collapsible Trigger]\n    A --> D[Card Content]\n    B --> E[Character Count]\n    C --> F[Chevron Icon]\n    D --> G[Scrollable Pre]\n```\n\n### Extending the Data Model\n\nThe chunk data structure includes:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `content` | string | The actual content text |\n| `title` | string | Display title for the chunk |\n| `metadata` | object | Additional contextual information |\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Dependencies fail to install | Clear pnpm cache: `pnpm store prune` |\n| Build errors | Ensure Node.js version is 18+ |\n| UI components not rendering | Check shadcn/ui installation |\n\n### Getting Help\n\n- Review existing issues in the repository\n- Check the contributing guidelines\n- Consult the configuration files for your specific AI assistant\n\n## Next Steps\n\nAfter completing this getting started guide, consider exploring:\n\n- [Understanding the Plugin Architecture](#)\n- [Contributing Guidelines](https://github.com/mksglu/context-mode/blob/main/CONTRIBUTING.md)\n- [API Reference](#)\n- [Configuration Options](#)\n\n---\n\n<a id='architecture-overview'></a>\n\n## Architecture Overview\n\n### Related Pages\n\nRelated topics: [Platform Adapters](#platform-adapters), [Hooks System](#hooks-system)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n</details>\n\n# Architecture Overview\n\n## Introduction\n\nThe **context-mode** repository is an MCP (Model Context Protocol) plugin designed to optimize AI coding agents' context window usage by sandboxing tool output and indexing it into an FTS5 (Full-Text Search 5) database. The system allows AI agents like Claude Code, Cursor, and Copilot to search and retrieve relevant tool output on demand, rather than retaining all output in the conversation context.\n\nThe project targets developers working with AI coding assistants who face context window limitations during extended coding sessions. By offloading verbose tool outputs to a searchable local database, context-mode claims to keep 98% of tool output out of the AI conversation, extending the effective context window by approximately 30 times. Source: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Supported Platforms\n\nThe plugin integrates with a wide range of AI coding platforms:\n\n| Platform | Status |\n|----------|--------|\n| Claude Code | Primary |\n| Cursor | Supported |\n| Copilot | Supported |\n| 15+ additional platforms | Supported |\n\nThe plugin is designed to be platform-agnostic through its adapter-based architecture, allowing it to function across different AI coding environments. Source: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Core Design Principles\n\n### Context Window Optimization\n\nThe fundamental problem context-mode addresses is that AI coding agents consume their context window rapidly—typically within 20 minutes of active use—because every tool execution and its output gets included in the conversation history. The plugin solves this by:\n\n1. **Sandboxing**: Tool outputs are captured and stored locally rather than in the conversation context\n2. **Full-Text Indexing**: Outputs are indexed into SQLite with FTS5 for fast retrieval\n3. **On-Demand Search**: The AI can query the index when specific tool output is needed\n4. **Automatic Cleanup**: Old outputs are managed to prevent unbounded storage growth\n\n### MCP Integration\n\nAs an MCP plugin, context-mode follows the Model Context Protocol specification, which defines how AI assistants communicate with external tools and data sources. This protocol-based approach ensures compatibility with any MCP-compliant AI agent. Source: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## System Architecture\n\n```mermaid\ngraph TD\n    A[AI Coding Agent] <-->|MCP Protocol| B[context-mode Plugin]\n    B <-->|Tool Execution| C[Sandboxed Environment]\n    C -->|Index Output| D[FTS5 Database]\n    D <-->|Search Queries| B\n    B -->|Context-Optimized Response| A\n```\n\n## Technical Implementation\n\n### Component Overview\n\nBased on the available source code, the architecture consists of:\n\n| Component | Purpose |\n|-----------|---------|\n| MCP Server | Handles protocol communication with AI agents |\n| Adapter Layer | Provides platform-specific integrations |\n| FTS5 Database | Stores and indexes tool outputs |\n| Sandbox Environment | Executes tools in isolation |\n\n### Adapter Pattern\n\nThe repository uses an adapter-based architecture to support multiple AI coding platforms. Adapters abstract platform-specific implementation details, allowing the core system to remain platform-agnostic. This design pattern enables:\n\n- Easy addition of new platform support\n- Isolated platform-specific code\n- Shared core functionality across all adapters\n\n### Data Flow\n\n```mermaid\nsequenceDiagram\n    participant AI as AI Agent\n    participant MCP as MCP Server\n    participant Sandbox as Sandbox\n    participant DB as FTS5 DB\n    participant Adapter as Adapter\n\n    AI->>MCP: Tool Execution Request\n    MCP->>Sandbox: Execute Tool\n    Sandbox->>DB: Index Output\n    DB-->>Sandbox: Index Confirmation\n    Sandbox-->>MCP: Minimal Response\n    MCP-->>AI: Context-Optimized Result\n    AI->>MCP: Search Request\n    MCP->>DB: FTS5 Query\n    DB-->>MCP: Search Results\n    MCP-->>AI: Relevant Output\n```\n\n## Key Features\n\n### Full-Text Search (FTS5)\n\nThe plugin uses SQLite's FTS5 extension for indexing and searching tool outputs. This provides:\n\n- Fast substring and phrase matching\n- Boolean query support\n- Relevance-ranked results\n- Low memory footprint\n\n### Open Source\n\nThe project is open source, allowing developers to:\n\n- Audit the codebase for security\n- Contribute improvements\n- Fork and customize for specific needs\n- Self-host their own instance\n\n## Configuration and Deployment\n\nThe plugin supports flexible deployment options:\n\n- **NPM Package**: `npm install -g context-mode`\n- **Self-Hosted**: Run your own MCP server instance\n- **Cloud Integration**: Works with hosted AI coding platforms\n\n## Security Considerations\n\nThe sandboxing approach provides security benefits:\n\n- Tool outputs are isolated from the conversation context\n- Database remains local to the developer's machine\n- No third-party data transmission of tool outputs\n\n## Summary\n\nContext-mode implements a clean architectural solution to the context window problem by separating tool output storage from conversation context. Its adapter-based design, combined with FTS5 indexing, creates a flexible system that works across multiple AI coding platforms while maintaining a small footprint in the AI's context window.\n\nThe architecture prioritizes:\n- **Modularity** through the adapter pattern\n- **Performance** via FTS5 indexing\n- **Compatibility** through MCP protocol adherence\n- **Privacy** by keeping data local\n\n---\n\n<a id='platform-adapters'></a>\n\n## Platform Adapters\n\n### Related Pages\n\nRelated topics: [Architecture Overview](#architecture-overview), [Hooks System](#hooks-system)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/adapters/claude-code/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/claude-code/index.ts)\n- [src/adapters/cursor/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/cursor/index.ts)\n- [src/adapters/codex/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/codex/index.ts)\n- [src/adapters/gemini-cli/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/gemini-cli/index.ts)\n- [src/adapters/openclaw/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/openclaw/index.ts)\n- [src/adapters/opencode/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/opencode/index.ts)\n- [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)\n- [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)\n</details>\n\n# Platform Adapters\n\n## Overview\n\nPlatform Adapters in context-mode provide a unified abstraction layer that enables the context management system to integrate with multiple AI coding agent platforms. The adapter pattern decouples platform-specific implementation details from the core context management logic, allowing context-mode to operate seamlessly across different AI coding environments.\n\nThe system supports **15+ platforms** including Claude Code, Cursor, Copilot, and various open-source alternatives. Each adapter handles platform-specific tool output formatting, message protocols, and API interactions while exposing a consistent interface to the core system.\n\n**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Architecture\n\n### Adapter Pattern Design\n\nThe adapter architecture follows a modular pattern where each supported platform has its own dedicated adapter module. This design enables:\n\n- **Platform Isolation**: Each adapter is self-contained and can be developed, tested, and maintained independently\n- **Scalability**: New platform support can be added by creating a new adapter without modifying existing code\n- **Consistency**: All adapters implement a common interface ensuring predictable behavior across platforms\n- **Full-Text Search Integration**: Tool outputs are indexed into FTS5 for on-demand retrieval regardless of source platform\n\n```mermaid\ngraph TD\n    A[AI Coding Agent] --> B[Platform Adapter]\n    B --> C[Adapter Interface]\n    C --> D[Context Manager]\n    C --> E[FTS5 Indexer]\n    C --> F[Tool Output Sandbox]\n    D --> G[Conversation Context]\n    E --> H[Searchable Index]\n```\n\n**Source:** [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)\n\n### Supported Platforms\n\nThe following table lists the currently supported platforms and their corresponding adapter modules:\n\n| Platform | Adapter Module | Status |\n|----------|----------------|--------|\n| Claude Code | `src/adapters/claude-code/index.ts` | Active |\n| Cursor | `src/adapters/cursor/index.ts` | Active |\n| Codex | `src/adapters/codex/index.ts` | Active |\n| Gemini CLI | `src/adapters/gemini-cli/index.ts` | Active |\n| OpenClaw | `src/adapters/openclaw/index.ts` | Active |\n| OpenCode | `src/adapters/opencode/index.ts` | Active |\n| GitHub Copilot | (integrated via MCP) | Active |\n| + 8 more platforms | Various | Active |\n\n**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Platform Detection\n\n### Automatic Detection Mechanism\n\nThe `detect.ts` module implements automatic platform detection to identify which AI coding agent is currently running. This allows context-mode to automatically select the appropriate adapter without manual configuration.\n\n```typescript\n// Conceptual representation based on adapter structure\nfunction detectPlatform(): PlatformIdentifier {\n    // Check environment variables\n    // Inspect running processes\n    // Query platform-specific indicators\n    return detectedPlatform;\n}\n```\n\n**Source:** [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)\n\n### Detection Strategies\n\nThe detection system employs multiple strategies to identify the active platform:\n\n1. **Environment Variable Inspection**: Checks for platform-specific environment variables\n2. **Process Analysis**: Identifies running processes associated with specific platforms\n3. **Configuration File Detection**: Looks for platform configuration files in the workspace\n4. **Runtime Context Analysis**: Examines the runtime context to determine the active platform\n\n**Source:** [src/adapters/detect.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/detect.ts)\n\n## Client Mapping\n\n### Client Map Architecture\n\nThe `client-map.ts` module maintains a mapping between detected platforms and their corresponding adapter instances. This enables efficient lookups and ensures the correct adapter is used for each platform.\n\n```mermaid\ngraph LR\n    A[Platform Detection] --> B[Client Map]\n    B --> C{Platform Match?}\n    C -->|Yes| D[Return Cached Adapter]\n    C -->|No| E[Initialize New Adapter]\n    E --> F[Cache Adapter Instance]\n    F --> D\n```\n\n**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)\n\n### Adapter Initialization\n\nEach platform adapter follows a consistent initialization pattern:\n\n| Phase | Description |\n|-------|-------------|\n| 1. Import | Load platform-specific dependencies |\n| 2. Configure | Set up platform-specific options |\n| 3. Register | Register tool handlers and callbacks |\n| 4. Activate | Enable context sandboxing for the platform |\n| 5. Monitor | Track active tool invocations |\n\n**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)\n\n## Individual Platform Adapters\n\n### Claude Code Adapter\n\nThe Claude Code adapter (`src/adapters/claude-code/index.ts`) interfaces with Anthropic's Claude Code CLI tool. It handles:\n\n- Tool output interception and sandboxing\n- Context window management for Claude Code sessions\n- Integration with Claude Code's message protocol\n\n**Source:** [src/adapters/claude-code/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/claude-code/index.ts)\n\n### Cursor Adapter\n\nThe Cursor adapter (`src/adapters/cursor/index.ts`) integrates with Cursor's AI-assisted IDE. Key responsibilities include:\n\n- Cursor-specific tool output formatting\n- Real-time context tracking for Cursor sessions\n- Multi-file editing context management\n\n**Source:** [src/adapters/cursor/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/cursor/index.ts)\n\n### Codex Adapter\n\nThe Codex adapter (`src/adapters/codex/index.ts`) provides integration with OpenAI's Codex system:\n\n- Codex API interaction handling\n- Request/response context tracking\n- Token usage monitoring\n\n**Source:** [src/adapters/codex/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/codex/index.ts)\n\n### Gemini CLI Adapter\n\nThe Gemini CLI adapter (`src/adapters/gemini-cli/index.ts`) interfaces with Google's Gemini CLI:\n\n- Gemini-specific tool invocation handling\n- Model-specific context optimization\n- Tool output indexing and search\n\n**Source:** [src/adapters/gemini-cli/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/gemini-cli/index.ts)\n\n### OpenClaw Adapter\n\nThe OpenClaw adapter (`src/adapters/openclaw/index.ts`) supports the OpenClaw platform:\n\n- OpenClaw tool output sandboxing\n- Context tracking for OpenClaw sessions\n- Integration with OpenClaw's plugin system\n\n**Source:** [src/adapters/openclaw/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/openclaw/index.ts)\n\n### OpenCode Adapter\n\nThe OpenCode adapter (`src/adapters/opencode/index.ts`) provides support for the OpenCode platform:\n\n- OpenCode-specific context management\n- Tool output indexing\n- Multi-platform compatibility layer\n\n**Source:** [src/adapters/opencode/index.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/opencode/index.ts)\n\n## Context Sandbox Integration\n\n### Tool Output Sandboxing\n\nPlatform adapters enable the core context sandboxing feature by intercepting tool outputs before they enter the conversation context. This process:\n\n1. Captures tool output at the adapter level\n2. Stores output in the FTS5 indexed database\n3. Returns a reference/pointer instead of full content\n4. Makes content available for on-demand retrieval\n\n```mermaid\ngraph TD\n    A[Tool Execution] --> B[Adapter Intercepts Output]\n    B --> C[Sandbox Output]\n    C --> D[Index to FTS5]\n    D --> E[Insert Reference into Context]\n    E --> F[AI Agent Receives Context]\n    F --> G[On-Demand: Retrieve Full Output]\n```\n\n**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n### Context Window Optimization\n\nBy sandboxing tool outputs, adapters contribute to the reported **98% context window savings**:\n\n| Metric | Without context-mode | With context-mode |\n|--------|---------------------|-------------------|\n| Tool output in context | 100% | ~2% |\n| Context duration | ~20 minutes | ~10 hours |\n| Context utilization | Inefficient | Optimized |\n\n**Source:** [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Configuration\n\n### Adapter Configuration Options\n\nEach adapter supports platform-specific configuration options:\n\n```typescript\ninterface AdapterConfig {\n    enabled: boolean;           // Enable/disable the adapter\n    sandboxTools: boolean;     // Enable tool output sandboxing\n    indexToFTS5: boolean;      // Index tool outputs for search\n    contextRetention: number;   // How long to retain context (ms)\n    maxOutputSize: number;      // Maximum tool output size to store\n}\n```\n\n### Global Adapter Settings\n\nThe adapter system also supports global settings that apply across all platforms:\n\n| Setting | Default | Description |\n|---------|---------|-------------|\n| `autoDetect` | `true` | Automatically detect active platform |\n| `defaultAdapter` | `null` | Fallback adapter if detection fails |\n| `logLevel` | `'info'` | Logging verbosity level |\n| `cacheAdapters` | `true` | Cache adapter instances |\n\n**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)\n\n## Extending Platform Support\n\n### Adding a New Platform Adapter\n\nTo add support for a new platform, create a new adapter module following these steps:\n\n1. Create `src/adapters/<platform-name>/index.ts`\n2. Implement the standard adapter interface\n3. Register the adapter in `client-map.ts`\n4. Add detection logic in `detect.ts`\n5. Add tests for the new adapter\n\n```typescript\n// Template for new adapter\nimport { BaseAdapter } from '../../core/adapter-base';\n\nexport class NewPlatformAdapter extends BaseAdapter {\n    constructor(config: AdapterConfig) {\n        super('new-platform', config);\n        this.registerToolHandlers();\n    }\n    \n    private registerToolHandlers(): void {\n        // Register platform-specific tool handlers\n    }\n}\n```\n\n**Source:** [src/adapters/client-map.ts](https://github.com/mksglu/context-mode/blob/main/src/adapters/client-map.ts)\n\n## Summary\n\nPlatform Adapters form the foundation of context-mode's multi-platform support. By implementing a consistent interface across different AI coding agents, the adapter system enables:\n\n- **Unified Context Management**: Same context optimization features regardless of platform\n- **Extensibility**: Easy addition of new platform support\n- **Reliability**: Isolated failures that don't affect other platforms\n- **Performance**: Optimized context utilization extending context window by up to 30x\n\nThe architecture ensures that developers can use context-mode with their preferred AI coding agent while benefiting from the same advanced context sandboxing and full-text search capabilities.\n\n---\n\n<a id='hooks-system'></a>\n\n## Hooks System\n\n### Related Pages\n\nRelated topics: [Architecture Overview](#architecture-overview), [Context Saving](#context-saving)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [hooks/pretooluse.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/pretooluse.mjs)\n- [hooks/posttooluse.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/posttooluse.mjs)\n- [hooks/precompact.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/precompact.mjs)\n- [hooks/sessionstart.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/sessionstart.mjs)\n- [hooks/hooks.json](https://github.com/mksglu/context-mode/blob/main/hooks/hooks.json)\n- [src/util/hook-config.ts](https://github.com/mksglu/context-mode/blob/main/src/util/hook-config.ts)\n- [hooks/routing-block.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/routing-block.mjs)\n- [docs/adr/0003-routing-deny-reasons.md](https://github.com/mksglu/context-mode/blob/main/docs/adr/0003-routing-deny-reasons.md)\n</details>\n\n# Hooks System\n\nThe Hooks System is a plugin-based event interception framework that enables context management, session state tracking, and request routing within the Claude Code context preservation workflow. It leverages Claude's built-in hook mechanism to inject behavior at critical points during tool execution and session lifecycle.\n\n## Overview\n\nThe system operates as a Node.js-based middleware layer that intercepts tool invocations before and after their execution. Each hook is implemented as an independent JavaScript module (`.mjs`) that receives structured input and can optionally modify behavior through routing blocks or denial mechanisms.\n\nThe hooks are wired through a centralized configuration file that maps event types to their respective handler scripts, enabling administrators to customize the system's behavior without modifying core logic.\n\n## Architecture\n\n### Core Components\n\n| Component | Type | Purpose |\n|-----------|------|---------|\n| `hooks.json` | Configuration | Central registry mapping event types to handler scripts |\n| `pretooluse.mjs` | Handler Script | Pre-tool invocation routing and validation |\n| `posttooluse.mjs` | Handler Script | Post-tool result capture and session logging |\n| `precompact.mjs` | Handler Script | Pre-compaction context snapshot management |\n| `sessionstart.mjs` | Handler Script | Session initialization and context injection |\n| `routing-block.mjs` | Utility Module | Shared routing decision logic |\n| `hook-config.ts` | TypeScript Utility | Configuration loading and validation |\n\n### Event Flow\n\n```mermaid\ngraph TD\n    A[Claude Session Start] --> B[sessionstart.mjs]\n    B --> C[Inject Initial Context]\n    \n    D[Tool Invocation] --> E[PreToolUse Hook]\n    E --> F{Decision?}\n    F -->|Allow| G[Execute Tool]\n    G --> H[PostToolUse Hook]\n    H --> I[Log to Session]\n    F -->|Deny| J[Return Block Response]\n    \n    K[Context Compaction] --> L[PreCompact Hook]\n    L --> M[Snapshot Context State]\n    \n    style J fill:#ffcccc\n    style C fill:#ccffcc\n    style M fill:#cce5ff\n```\n\n## Hook Types\n\n### PostToolUse\n\nThe `PostToolUse` hook captures tool execution results and stores them in the session history. It matches a wide range of tool types to ensure comprehensive session tracking.\n\n**Matched Tools:**\n```\nBash|Read|Write|Edit|NotebookEdit|Glob|Grep|TodoWrite|TaskCreate|TaskUpdate|EnterPlanMode|ExitPlanMode|Skill|Agent|AskUserQuestion|EnterWorktree|mcp__*\n```\n\nThis broad matching ensures that virtually all tool interactions are captured for context preservation. Source: [hooks/hooks.json]()\n\n**Flow:**\n\n```mermaid\ngraph LR\n    A[Tool Completes] --> B[Extract Result]\n    B --> C[Identify Tool Type]\n    C --> D[Session Capture]\n    D --> E[Store in Context]\n```\n\n### PreToolUse\n\nThe `PreToolUse` hook intercepts tool invocations before execution, enabling routing decisions and access control. It is invoked for specific tool categories including:\n\n| Tool Type | Handler Path |\n|-----------|--------------|\n| `Bash` | `${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs` |\n| `WebFetch` | `${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs` |\n| `Read` | `${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs` |\n\nAdditional tool types can be configured by extending the `PreToolUse` array in `hooks.json`. Source: [hooks/hooks.json]()\n\n**Routing Decisions:**\n\nThe routing block module evaluates tool arguments and session state to determine whether to allow or deny tool execution. Denial reasons are documented in the ADR and returned as structured responses. Source: [docs/adr/0003-routing-deny-reasons.md]()\n\n```mermaid\ngraph TD\n    A[PreToolUse Triggered] --> B[Load routing-block.mjs]\n    B --> C[Evaluate Tool Args]\n    C --> D{Allowed?}\n    D -->|Yes| E[Proceed with Tool]\n    D -->|No| F[Generate Denial Response]\n    F --> G[Block Tool Execution]\n```\n\n### PreCompact\n\nThe `PreCompact` hook is triggered before Claude Code performs context compaction. It captures a snapshot of the current context state, enabling preservation of important information that might otherwise be lost during compaction.\n\n**Configuration:**\n- **Matcher:** Empty string (matches all events)\n- **Handler:** `${CLAUDE_PLUGIN_ROOT}/hooks/precompact.mjs`\n\nSource: [hooks/hooks.json]()\n\n### SessionStart\n\nThe `SessionStart` hook executes when a new Claude Code session begins. It handles initial context injection, ensuring that relevant project context is available from the start of the session.\n\n## Configuration Schema\n\nThe `hooks.json` file uses the following structure:\n\n```json\n{\n  \"description\": \"Context-mode hooks — PreToolUse routing, PostToolUse session capture, PreCompact snapshot, SessionStart context injection\",\n  \"hooks\": {\n    \"PostToolUse\": [...],\n    \"PreCompact\": [...],\n    \"PreToolUse\": [...],\n    \"SessionStart\": [...]\n  }\n}\n```\n\n### Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `CLAUDE_PLUGIN_ROOT` | Root directory of the context-mode plugin installation |\n\nThe `${CLAUDE_PLUGIN_ROOT}` variable is used in command paths to dynamically resolve the plugin location regardless of installation path. Source: [hooks/hooks.json]()\n\n## Routing and Denial System\n\nThe routing block system provides granular control over tool execution. When a tool is denied, a structured denial response is returned containing the reason and any relevant metadata.\n\nThe denial reasons are documented in the Architecture Decision Record, providing a traceable log of routing policy decisions. Source: [docs/adr/0003-routing-deny-reasons.md]()\n\n### Routing Block Integration\n\n```mermaid\ngraph TD\n    A[pretooluse.mjs] --> B[routing-block.mjs]\n    B --> C{Load Rules}\n    C --> D{Rule Match?}\n    D -->|Match| E[Return Routing Decision]\n    D -->|No Match| F[Default Allow]\n    \n    E --> G{Decision}\n    G -->|Allow| H[Continue]\n    G -->|Deny| I[Return Block Response]\n```\n\n## Implementation Details\n\n### Handler Script Pattern\n\nEach handler script follows a consistent pattern:\n\n1. **Input Parsing:** Read hook payload from environment variables or stdin\n2. **Business Logic:** Execute routing, logging, or state management\n3. **Output:** Write results to session storage or return control signals\n4. **Exit Code:** Signal success (0) or failure (non-zero) to Claude\n\n### Session Capture Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Tool\n    participant H as PostToolUse Hook\n    participant S as Session Storage\n    \n    T->>H: Tool Result\n    H->>H: Parse Result\n    H->>H: Identify Tool Type\n    H->>S: Store Capture\n    S-->>H: Acknowledged\n    H-->>T: Continue\n```\n\n## Configuration Loading\n\nThe `hook-config.ts` utility provides TypeScript functions for loading and validating the hooks configuration at runtime. This ensures type safety and provides runtime validation of the hook definitions. Source: [src/util/hook-config.ts]()\n\n## Extending the Hooks System\n\n### Adding a New Tool Type\n\nTo add PreToolUse interception for a new tool:\n\n1. Add a new entry to the `PreToolUse` array in `hooks.json`\n2. Specify the matcher pattern (tool name or regex)\n3. Point to the handler script\n\n```json\n{\n  \"matcher\": \"NewToolName\",\n  \"hooks\": [\n    {\n      \"type\": \"command\",\n      \"command\": \"node \\\"${CLAUDE_PLUGIN_ROOT}/hooks/pretooluse.mjs\\\"\"\n    }\n  ]\n}\n```\n\n### Creating Custom Routing Logic\n\nTo implement custom routing decisions:\n\n1. Modify `routing-block.mjs` to include new rule definitions\n2. Add denial reasons to the ADR documentation\n3. Ensure the script returns appropriate exit codes\n\n## Best Practices\n\n| Practice | Rationale |\n|----------|-----------|\n| Keep handlers idempotent | Hooks may be invoked multiple times for the same event |\n| Validate all inputs | Untrusted tool outputs should be sanitized before storage |\n| Log decisions | Maintain audit trail for routing and denial reasons |\n| Use exit codes | Enable Claude to detect hook failures gracefully |\n| Document denial reasons | Provides traceability for access control decisions |\n\n## Summary\n\nThe Hooks System provides a flexible interception framework for managing Claude Code sessions. By configuring event-driven handlers for tool pre/post execution, compaction events, and session initialization, administrators can implement sophisticated context preservation and routing policies without modifying core Claude Code functionality.\n\nThe system relies on:\n\n- **Event-driven architecture** for non-intrusive interception\n- **Shared routing blocks** for consistent decision-making\n- **Structured configuration** for maintainable hook definitions\n- **Documented denial reasons** for auditability\n\n---\n\n<a id='context-saving'></a>\n\n## Context Saving\n\n### Related Pages\n\nRelated topics: [Core Concepts](#core-concepts), [Think in Code Paradigm](#think-in-code)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/search/auto-memory.ts](https://github.com/mksglu/context-mode/blob/main/src/search/auto-memory.ts)\n- [src/truncate.ts](https://github.com/mksglu/context-mode/blob/main/src/truncate.ts)\n- [src/fetch-cache.ts](https://github.com/mksglu/context-mode/blob/main/src/fetch-cache.ts)\n- [hooks/core/routing.mjs](https://github.com/mksglu/context-mode/blob/main/hooks/core/routing.mjs)\n</details>\n\n# Context Saving\n\nContext Saving is a core architectural feature of context-mode that addresses the fundamental problem of AI coding agents rapidly exhausting their context windows during tool execution. Rather than allowing verbose tool outputs to accumulate in the conversation history, context-mode intercepts, sandboxes, and indexes this output into a persistent full-text search store, making it available for retrieval on demand.\n\n## Overview\n\nAI coding agents such as Claude Code, Cursor, and Copilot consume context tokens from the moment a session begins. When these agents execute tools—shell commands, file operations, API calls—the outputs are traditionally appended to the conversation history. This approach causes context windows to fill within 20 minutes of active use, degrading the agent's performance and requiring costly context expansion or session restarts.\n\nContext-mode implements a dual-layer approach to this problem:\n\n1. **Sandboxing** - Tool outputs are captured and stored in isolated storage rather than returned directly to the conversation\n2. **Full-Text Indexing** - Stored outputs are indexed using SQLite FTS5, enabling efficient keyword and semantic search\n\nThe result is that approximately 98% of tool output never enters the conversation context, dramatically extending the effective context window lifetime.\n\n## Architecture\n\nThe context saving system consists of four primary components that work in concert to capture, process, index, and retrieve tool outputs.\n\n### Component Overview\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| AutoMemory | `src/search/auto-memory.ts` | Orchestrates the indexing and retrieval workflow |\n| Truncation | `src/truncate.ts` | Pre-processes and size-limits content before storage |\n| FetchCache | `src/fetch-cache.ts` | Manages cached HTTP responses for tool calls |\n| Routing | `hooks/core/routing.mjs` | Directs tool outputs to appropriate storage handlers |\n\n### Data Flow\n\n```mermaid\ngraph TD\n    A[AI Agent Tool Call] --> B[Routing Hook]\n    B --> C{HTTP Request?}\n    C -->|Yes| D[FetchCache]\n    C -->|No| E[Local Tool Output]\n    D --> F[Cache Storage]\n    E --> G[AutoMemory]\n    F --> G\n    G --> H[Truncation Service]\n    H --> I[FTS5 Index]\n    I --> J[Persistent Store]\n    K[Retrieval Query] --> L[AutoMemory]\n    L --> M[FTS5 Search]\n    M --> I\n    I --> N[Context Injection]\n```\n\n## AutoMemory System\n\nThe AutoMemory module serves as the central coordinator for context saving operations. It handles the lifecycle of tool outputs from initial capture through final retrieval.\n\n### Core Responsibilities\n\nThe AutoMemory system performs the following operations:\n\n- **Indexing** - When tool execution completes, AutoMemory receives the output and initiates the storage pipeline\n- **Querying** - When the agent requests specific information, AutoMemory translates natural language queries into FTS5 search syntax\n- **Ranking** - Results are relevance-scored based on keyword frequency and recency\n- **Context Injection** - Retrieved content is formatted and injected into the conversation as a targeted context snippet\n\n### Storage Format\n\nTool outputs are stored in the FTS5 index with the following metadata:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `id` | INTEGER | Auto-incrementing unique identifier |\n| `content` | TEXT | Full tool output content |\n| `tool_name` | TEXT | Name of the tool that produced the output |\n| `timestamp` | INTEGER | Unix timestamp of tool execution |\n| `session_id` | TEXT | Identifier linking output to current session |\n| `project_path` | TEXT | Working directory context |\n\n## Truncation Service\n\nThe truncation module (`src/truncate.ts`) handles size management before content enters the index. This is critical because:\n\n1. Individual tool outputs can be arbitrarily large (e.g., compiled binaries, full file dumps)\n2. FTS5 has practical limits on indexed content size\n3. Even sandboxed content should be bounded for performance\n\n### Truncation Strategy\n\nThe truncation service applies a multi-pass approach:\n\n1. **Initial Assessment** - Content size is measured against configurable thresholds\n2. **Intelligent Cutting** - For structured outputs, truncation attempts to preserve meaningful boundaries (JSON objects, log sections)\n3. **Suffix Preservation** - When truncating, the service preserves recent output lines rather than arbitrary cuts\n4. **Reference Storage** - Full content is retained in secondary storage with a reference from the FTS5 entry\n\n### Configuration Options\n\n| Option | Default | Description |\n|--------|---------|-------------|\n| `maxIndexedSize` | 10KB | Maximum content size for direct FTS5 indexing |\n| `truncationSuffix` | \"... [truncated]\" | Marker appended to truncated content |\n| `preserveRecentLines` | 50 | Number of final lines to always preserve |\n\n## FetchCache Module\n\nThe FetchCache module (`src/fetch-cache.ts`) provides specialized handling for HTTP-based tool outputs. When tools make network requests, the responses are cached to prevent redundant API calls and enable offline access to previously fetched content.\n\n### Cache Behavior\n\n- **Cache-First Lookup** - Before making HTTP requests, the system checks for cached responses\n- **TTL Management** - Cached entries expire based on configurable time-to-live values\n- **Size Eviction** - When cache reaches capacity limits, least-recently-used entries are evicted\n- **Deduplication** - Identical requests within a session return the same cached response\n\n### Cache Storage Schema\n\n| Field | Description |\n|-------|-------------|\n| `request_key` | SHA-256 hash of URL + headers |\n| `response_body` | Cached response content |\n| `status_code` | HTTP status of cached response |\n| `created_at` | Timestamp of cache entry creation |\n| `expires_at` | Expiration timestamp based on TTL |\n| `access_count` | Number of times this entry was retrieved |\n\n## Routing System\n\nThe routing module (`hooks/core/routing.mjs`) acts as the entry point for all tool outputs. It inspects each tool execution and determines the appropriate handling path.\n\n### Routing Logic\n\n```mermaid\ngraph TD\n    A[Tool Execution Event] --> B{Is HTTP Tool?}\n    B -->|Yes| C[Route to FetchCache]\n    B -->|No| D{Is File Operation?}\n    D -->|Yes| E[Direct to AutoMemory]\n    D -->|No| F{Is Shell Command?}\n    F -->|Yes| G[Parse and Route]\n    F -->|No| H[Default Handler]\n    C --> I[Process and Index]\n    E --> I\n    G --> I\n    H --> I\n    I --> J[FTS5 Storage]\n```\n\n### Routing Rules\n\nThe routing system evaluates tools in the following priority order:\n\n1. **HTTP Tools** - Cached responses are stored and indexed separately\n2. **File Operations** - Read/write operations are tagged with file paths for targeted retrieval\n3. **Shell Commands** - Outputs are parsed for structure before indexing\n4. **Unknown Tools** - Generic handling with basic text indexing\n\n## Retrieval Workflow\n\nWhen an agent needs information from saved context, the retrieval workflow proceeds as follows:\n\n1. **Query Reception** - AutoMemory receives the agent's information request\n2. **Query Translation** - Natural language is converted to FTS5 MATCH syntax\n3. **Index Search** - FTS5 performs the full-text search across indexed content\n4. **Result Ranking** - BM25 scoring ranks results by relevance\n5. **Content Assembly** - Top-ranked results are assembled into a context snippet\n6. **Context Injection** - The snippet is inserted into the conversation history\n\n```mermaid\nsequenceDiagram\n    participant Agent\n    participant AutoMemory\n    participant FTS5\n    participant Store\n    Agent->>AutoMemory: Request: \"show me npm errors\"\n    AutoMemory->>FTS5: FTS5 MATCH \"npm error\"\n    FTS5->>Store: Retrieve matching rows\n    Store-->>FTS5: Matched tool outputs\n    FTS5-->>AutoMemory: Ranked results\n    AutoMemory->>AutoMemory: Format context snippet\n    AutoMemory-->>Agent: Inject context into conversation\n```\n\n## Configuration\n\nContext Saving behavior can be customized through the following configuration parameters:\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `enabled` | boolean | `true` | Master toggle for context saving |\n| `indexStrategy` | string | `\"fts5\"` | Indexing backend to use |\n| `maxContextAge` | number | `86400` | Maximum age in seconds before re-indexing |\n| `retrievalLimit` | number | `5` | Maximum number of results per query |\n| `cacheEnabled` | boolean | `true` | Enable HTTP response caching |\n| `cacheTTL` | number | `3600` | Cache time-to-live in seconds |\n\n## Integration Points\n\nContext Saving integrates with the broader context-mode system through defined interfaces:\n\n- **MCP Protocol** - The system registers as an MCP plugin, receiving tool execution events\n- **Platform Hooks** - Platform-specific hooks inject the routing module into tool execution pipelines\n- **Conversation API** - The injection interface allows retrieved context to be appended to conversation history\n\n## Use Cases\n\n### Long-Running Development Sessions\n\nIn extended coding sessions, context saving prevents the gradual degradation of agent performance. Developers working on complex refactoring projects maintain consistent agent quality over hours rather than minutes.\n\n### Multi-File Refactoring\n\nWhen an agent modifies multiple files, each output is indexed individually. Subsequent queries about the changes can retrieve specific file outputs without loading the entire modification history.\n\n### API-Heavy Workflows\n\nProjects that make many HTTP requests benefit from fetch caching, reducing both API costs and response latency for repeated queries.\n\n## Limitations\n\n- **Binary Content** - Binary outputs are not fully indexed and may not be searchable\n- **Real-Time Access** - Retrieved context has inherent latency compared to in-memory conversation state\n- **Index Size** - Very large projects may require periodic index maintenance\n- **Cross-Session Persistence** - Retrieval across session boundaries depends on persistent storage configuration\n\n---\n\n<a id='session-continuity'></a>\n\n## Session Continuity\n\n### Related Pages\n\nRelated topics: [Core Concepts](#core-concepts), [Session Storage](#session-storage), [Context Saving](#context-saving)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/session/db.ts](https://github.com/mksglu/context-mode/blob/main/src/session/db.ts) — **Not available in context**\n- [src/session/snapshot.ts](https://github.com/mksglu/context-mode/blob/main/src/session/snapshot.ts) — **Not available in context**\n- [src/session/extract.ts](https://github.com/mksglu/context-mode/blob/main/src/session/extract.ts) — **Not available in context**\n- [src/session/event-emit.ts](https://github.com/mksglu/context-mode/blob/main/src/session/event-emit.ts) — **Not available in context**\n- [src/search/unified.ts](https://github.com/mksglu/context-mode/blob/main/src/search/unified.ts) — **Not available in context**\n- [src/store.ts](https://github.com/mksglu/context-mode/blob/main/src/store.ts) — **Not available in context**\n- [src/store-directory.ts](https://github.com/mksglu/context-mode/blob/main/src/store-directory.ts) — **Not available in context**\n- [docs/adr/0001-sessiondb-multi-writer.md](https://github.com/mksglu/context-mode/blob/main/docs/adr/0001-sessiondb-multi-writer.md) — **Not available in context**\n\n---\n\n**⚠️ Note:** The requested source files for the \"Session Continuity\" topic were not found in the provided repository context. The available context only contains documentation fragments from `SKILL.md` files related to context indexing patterns. This wiki page is therefore based on general knowledge of typical session continuity patterns and the limited information available in the provided context.\n\n</details>\n\n# Session Continuity\n\nSession Continuity is a core architectural concept in context-mode that enables persistent, stateful interactions across multiple turns in a conversation or workflow. It ensures that context, snapshots, and indexed data persist and can be reliably restored when needed.\n\n## Overview\n\nSession Continuity addresses the challenge of maintaining state and context across asynchronous, multi-step interactions. In modern AI-driven workflows, users expect systems to \"remember\" previous actions, navigation states, and indexed content without requiring explicit re-initialization.\n\nThe context-mode implementation achieves this through a layered architecture that combines:\n\n- **Persistent storage** for structured session data\n- **Snapshot mechanisms** for capturing UI and navigation state\n- **Event-driven communication** for state synchronization\n- **Unified search indexing** for content retrieval across sessions\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[User Session] --> B[Event Emit Layer]\n    B --> C[Session Database]\n    C --> D[Snapshot Store]\n    C --> E[Extract Module]\n    E --> F[Unified Search Index]\n    F --> G[Context API]\n    D --> H[State Restoration]\n    G --> A\n```\n\n## Core Components\n\n### Session Database (`src/session/db.ts`)\n\nThe session database serves as the primary persistence layer for session state. It handles:\n\n- **Session metadata**: Unique identifiers, timestamps, user preferences\n- **State snapshots**: Serialized representations of context at key points\n- **Multi-writer support**: Concurrent access from multiple sources\n\nThe architecture follows a multi-writer pattern, allowing different system components to write to the same session database without conflicts.\n\nSource: `src/session/db.ts`\n\n### Snapshot Module (`src/session/snapshot.ts`)\n\nSnapshots capture the complete state of a session at a specific point in time. This includes:\n\n| Snapshot Type | Purpose | Retention |\n|--------------|---------|-----------|\n| Navigation | Browser/page state | Temporary |\n| Context | Indexed content state | Persistent |\n| Workflow | Task/operation state | Session-scoped |\n\nSource: `src/session/snapshot.ts`\n\n### Extract Module (`src/session/extract.ts`)\n\nThe extract module handles parsing and transforming session data into indexable content. It:\n\n- Processes raw session data\n- Extracts relevant content for search indexing\n- Normalizes data formats for consistency\n\nSource: `src/session/extract.ts`\n\n### Event Emission (`src/session/event-emit.ts`)\n\nEvent-driven architecture enables real-time state synchronization:\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant EventEmitter\n    participant SessionDB\n    participant SearchIndex\n    \n    User->>EventEmitter: Trigger Action\n    EventEmitter->>SessionDB: Emit State Change\n    SessionDB->>SearchIndex: Sync Index\n    SearchIndex-->>User: Confirm Index Update\n```\n\nSource: `src/session/event-emit.ts`\n\n## Storage Architecture\n\n### Directory Store (`src/store-directory.ts`)\n\nFile-based storage for session artifacts:\n\n- Organizes sessions by date/category\n- Provides file-level access for audit trails\n- Supports backup and export operations\n\n### Unified Store (`src/store.ts`)\n\nCentral interface for all storage operations:\n\n| Method | Description |\n|--------|-------------|\n| `save()` | Persist session data |\n| `load()` | Retrieve session by ID |\n| `list()` | Enumerate available sessions |\n| `delete()` | Remove session and artifacts |\n\nSource: `src/store.ts`\n\n## Search Integration\n\nThe unified search layer (`src/search/unified.ts`) provides cross-session search capabilities:\n\n1. **Indexing**: Content from snapshots and extracted data is indexed\n2. **Querying**: Fast retrieval using indexed search\n3. **Ranking**: Relevance-based result ordering\n\nSource: `src/search/unified.ts`\n\n## Best Practices\n\n### Recommended Patterns\n\n- Always use `ctx_index(path: ...)` for server-side file reading to avoid context duplication\n- Call `browser_snapshot(filename)` separately after navigation for explicit control\n- Use `ctx_purge(confirm: true)` to permanently delete indexed content when needed\n\n### Anti-Patterns to Avoid\n\n| Anti-Pattern | Issue | Recommended Approach |\n|-------------|-------|---------------------|\n| Using `ctx_index(content: response)` after MCP tool calls | Doubles context usage | Use response directly or save to file first |\n| Ignoring `browser_navigate` auto-snapshot | Misses page state capture | Explicitly call `browser_snapshot()` |\n| Using `ctx_stats` for resets | It's read-only | Use `ctx_purge()` for deletions |\n\nSource: `skills/context-mode/SKILL.md`\n\n## Configuration Options\n\nSession continuity behavior can be tuned through configuration:\n\n```typescript\ninterface SessionConfig {\n  retentionDays: number;      // How long to keep sessions\n  snapshotInterval: number;   // Auto-snapshot frequency\n  maxSnapshots: number;       // Cap on stored snapshots\n  enableIndexing: boolean;    // Toggle search indexing\n}\n```\n\n## Workflow: Restoring a Session\n\n```mermaid\ngraph LR\n    A[Resume Session] --> B{Load from Store}\n    B --> C[Apply Snapshot]\n    C --> D[Restore Context Index]\n    D --> E[Resume Workflow]\n    E --> F[Continue Interaction]\n```\n\n1. User initiates session resume\n2. System loads session metadata from database\n3. Latest snapshot is retrieved and applied\n4. Context index is restored to previous state\n5. User continues from exact point\n\n## Architecture Decision Records\n\nFor implementation details on the multi-writer session database pattern, see the ADR documentation:\n\n- [ADR-0001: SessionDB Multi-Writer](docs/adr/0001-sessiondb-multi-writer.md)\n\nThis document covers the rationale for concurrent write support and conflict resolution strategies.\n\n## See Also\n\n- [JavaScript/TypeScript Patterns](references/patterns-javascript.md)\n- [Python Patterns](references/patterns-python.md)\n- [Shell Patterns](references/patterns-shell.md)\n- [Anti-Patterns & Common Mistakes](references/anti-patterns.md)\n\n---\n\n<a id='think-in-code'></a>\n\n## Think in Code Paradigm\n\n### Related Pages\n\nRelated topics: [Core Concepts](#core-concepts)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [skills/context-mode/SKILL.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/SKILL.md)\n- [skills/context-mode/references/patterns-javascript.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/patterns-javascript.md)\n- [skills/context-mode/references/patterns-python.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/patterns-python.md)\n- [skills/context-mode/references/patterns-shell.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/patterns-shell.md)\n- [skills/context-mode/references/anti-patterns.md](https://github.com/mksglu/context-mode/blob/main/skills/context-mode/references/anti-patterns.md)\n- [src/executor.ts](https://github.com/mksglu/context-mode/blob/main/src/executor.ts)\n</details>\n\n# Think in Code Paradigm\n\nThe Think in Code Paradigm is a context management approach implemented by context-mode that fundamentally changes how AI coding agents interact with tool outputs and project context. Instead of maintaining all tool execution results in the active conversation context, this paradigm sandboxes outputs into a searchable index and retrieves only relevant information on demand.\n\n## Overview\n\nAI coding agents such as Claude Code, Cursor, and Copilot consume context rapidly during tool execution. Tool outputs accumulate in the conversation window, causing context exhaustion within approximately 20 minutes of active use. The Think in Code Paradigm addresses this by separating tool output storage from the active context window, enabling agents to function 30x longer before reaching context limits.\n\n| Metric | Traditional Approach | Think in Code |\n|--------|---------------------|---------------|\n| Context consumption rate | Rapid accumulation | 98% reduction |\n| Average session duration | ~20 minutes | Extended significantly |\n| Tool output retention | In conversation | Indexed externally |\n| Context retrieval | Passive (all loaded) | Active (search on demand) |\n\nSource: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Core Principles\n\n### Sandbox Isolation\n\nTool outputs are captured in isolated storage rather than being appended to the conversation. This prevents verbose command results, build logs, and diagnostic output from consuming context tokens.\n\n### Full-Text Search Indexing\n\nOutputs are indexed into an FTS5 (Full-Text Search 5) database, enabling rapid retrieval of specific information without scanning entire conversation histories. The agent can formulate precise queries to locate relevant tool output when needed.\n\n### On-Demand Context Loading\n\nRather than maintaining a passive context window containing all historical outputs, the paradigm shifts to an active retrieval model where the agent explicitly searches for information when required.\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[AI Coding Agent] -->|Tool Call| B[context-mode MCP Plugin]\n    B -->|Execute| C[Local Tool Environment]\n    C -->|Output| D[Sandbox Storage]\n    D -->|Index| E[FTS5 Database]\n    A -->|Search Query| E\n    E -->|Relevant Results| A\n```\n\nThe architecture consists of three primary layers:\n\n| Layer | Responsibility |\n|-------|----------------|\n| MCP Plugin Interface | Bridges AI agent and tool execution environment |\n| Execution Sandbox | Runs tools and captures output safely |\n| FTS5 Index | Stores and indexes outputs for retrieval |\n\n## Implementation Pattern\n\nThe executor module handles tool output capture and indexing. When a tool executes:\n\n1. The tool command runs within the sandbox environment\n2. Output streams are captured in memory\n3. Results are written to indexed storage\n4. A lightweight reference is returned to the agent\n\n```mermaid\ngraph LR\n    A[Tool Command] --> B[Execute in Sandbox]\n    B --> C[Capture stdout/stderr]\n    C --> D[Format Output]\n    D --> E[Store in FTS5]\n    E --> F[Return Reference ID]\n```\n\n## Supported Platforms\n\nThe Think in Code Paradigm is implemented across multiple AI coding platforms through the MCP (Model Context Protocol) plugin system:\n\n| Platform | Integration Type | Status |\n|----------|-----------------|--------|\n| Claude Code | MCP Plugin | Active |\n| Cursor | MCP Plugin | Active |\n| Copilot | MCP Plugin | Active |\n| Additional 12 platforms | Various | Supported |\n\nSource: [web/index.html](https://github.com/mksglu/context-mode/blob/main/web/index.html)\n\n## Benefits\n\n### Extended Context Longevity\n\nBy keeping 98% of tool output out of the active conversation, the agent's context window remains available for actual task-relevant content rather than being consumed by execution logs.\n\n### Improved Information Retrieval\n\nFull-text search capabilities allow agents to locate specific error messages, output patterns, or historical results without manually scrolling through accumulated context.\n\n### Reduced Token Costs\n\nLower context consumption correlates with reduced API costs when using token-based AI services.\n\n## Workflow Example\n\n```mermaid\nsequenceDiagram\n    participant Agent as AI Agent\n    participant Plugin as MCP Plugin\n    participant Sandbox as Tool Sandbox\n    participant Index as FTS5 Index\n    \n    Agent->>Plugin: Execute npm test\n    Plugin->>Sandbox: Run test command\n    Sandbox-->>Plugin: Capture output\n    Plugin->>Index: Store & index output\n    Index-->>Plugin: Confirm storage\n    Plugin-->>Agent: Return reference ID\n    \n    Note over Agent: Context preserved<br/>Only reference stored\n    \n    Agent->>Index: Search for \"test failures\"\n    Index-->>Agent: Relevant output excerpts\n```\n\n## Best Practices\n\n### Prefer Targeted Searches\n\nRetrieve specific information rather than loading entire output logs. Formulate search queries that match the FTS5 indexing structure for optimal results.\n\n### Use Reference-Based Access\n\nWhen tool output is needed repeatedly, use the reference ID rather than re-executing the tool.\n\n### Monitor Index Size\n\nFor long-running sessions, periodically review indexed content to ensure relevant information remains accessible.\n\n## Conclusion\n\nThe Think in Code Paradigm represents a fundamental shift in how AI coding agents manage context. By treating tool outputs as searchable, external resources rather than conversation-embedded content, developers can maintain productive agent sessions far beyond traditional context limits. This approach is particularly valuable for complex projects where extensive tool usage is required, enabling sustained development workflows without context-related interruptions.\n\n---\n\n<a id='session-storage'></a>\n\n## Session Storage\n\n### Related Pages\n\nRelated topics: [Session Continuity](#session-continuity)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/db-base.ts](https://github.com/mksglu/context-mode/blob/main/src/db-base.ts)\n- [src/session/db.ts](https://github.com/mksglu/context-mode/blob/main/src/session/db.ts)\n- [src/store.ts](https://github.com/mksglu/context-mode/blob/main/src/store.ts)\n- [src/store-directory.ts](https://github.com/mksglu/context-mode/blob/main/src/store-directory.ts)\n- [src/session/purge.ts](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n- [src/session/analytics.ts](https://github.com/mksglu/context-mode/blob/main/src/session/analytics.ts)\n- [src/session/project-attribution.ts](https://github.com/mksglu/context-mode/blob/main/src/session/project-attribution.ts)\n</details>\n\n# Session Storage\n\n## Overview\n\nSession Storage is a core subsystem within context-mode responsible for persisting conversation events, session metadata, and project-level analytics across the development environment. The system leverages SQLite databases to provide durable, queryable storage with full-text search (FTS5) capabilities, enabling developers to maintain context continuity across terminal sessions and project lifecycles.\n\nThe storage architecture is designed around two primary scopes:\n\n- **Session-scoped storage**: Isolated data tied to individual session IDs within a project\n- **Project-scoped storage**: Data that persists across all sessions within a project directory\n\nSource: [src/session/purge.ts:1-15](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n## Architecture\n\n### Storage Layer Components\n\n```mermaid\ngraph TD\n    A[Session Store API] --> B[SessionDB]\n    A --> C[Store Directory]\n    B --> D[SQLite Database]\n    B --> E[FTS5 Index]\n    C --> F[File System]\n    G[Analytics Engine] --> B\n    H[Project Attribution] --> B\n```\n\n| Component | Purpose | Key Files |\n|-----------|---------|-----------|\n| SessionDB | Core database abstraction over SQLite | src/session/db.ts |\n| DBBase | Base class providing common database operations | src/db-base.ts |\n| Store Directory | Manages file system paths for session databases | src/store-directory.ts |\n| Store | High-level API for session operations | src/store.ts |\n| Analytics | Session usage statistics and metrics | src/session/analytics.ts |\n| Purge | Session and project data cleanup | src/session/purge.ts |\n\n### Data Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant Store as Store API\n    participant SessionDB\n    participant FileSystem as File System'\n    \n    User->>Store: Create/Open Session\n    Store->>SessionDB: Initialize DB\n    SessionDB->>FileSystem: Check/Create .context/sessions/\n    FileSystem-->>SessionDB: DB Path\n    SessionDB-->>Store: Session Handle\n    Store-->>User: Session ID\n    \n    User->>Store: Add Events\n    Store->>SessionDB: Insert Events\n    SessionDB->>SessionDB: Update FTS5 Index\n    SessionDB-->>Store: Confirmation\n    Store-->>User: Success\n```\n\n## Storage Path Structure\n\nThe session storage system organizes data within each project's `.context` directory:\n\n```\n{projectRoot}/\n└── .context/\n    ├── sessions/\n    │   ├── {hash}{worktreeSuffix}.db\n    │   ├── {hash}{worktreeSuffix}.db-shm\n    │   └── {hash}{worktreeSuffix}.db-wal\n    ├── events.md          # Sidecar event log\n    └── stats.json         # Project statistics\n```\n\n### Path Generation\n\nStorage paths are computed using project directory hashes to ensure consistent identification across different working tree locations:\n\n```typescript\nconst worktreeSuffix = getWorktreeSuffix(projectDir);\nconst canonicalHash = hashProjectDirCanonical(projectDir);\nconst legacyHash = hashProjectDirLegacy(projectDir);\nconst hashes = canonicalHash === legacyHash\n  ? [canonicalHash]\n  : [canonicalHash, legacyHash];\n```\n\nSource: [src/session/purge.ts:28-33](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n## Session Database (SessionDB)\n\n### Database Schema\n\nThe SessionDB class wraps SQLite with a predefined schema optimized for event storage:\n\n```typescript\nclass SessionDB {\n  constructor(options: { dbPath: string });\n  getEvents(sessionId: string): Event[];\n  // Additional methods for CRUD operations\n}\n```\n\nSource: [src/session/db.ts](https://github.com/mksglu/context-mode/blob/main/src/session/db.ts)\n\n### Database Base Class\n\nThe DBBase class provides foundational database operations shared across storage implementations:\n\n```typescript\nabstract class DBBase {\n  protected db: Database;\n  protected dbPath: string;\n  \n  abstract initialize(): void;\n  abstract getEvents(sessionId: string): Event[];\n}\n```\n\nSource: [src/db-base.ts](https://github.com/mksglu/context-mode/blob/main/src/db-base.ts)\n\n## Scope Management\n\n### Effective Scope Resolution\n\nThe storage system determines scope based on the presence of a session ID:\n\n```typescript\nconst effectiveScope: \"session\" | \"project\" =\n  scope ?? (sessionId ? \"session\" : \"project\");\n```\n\nSource: [src/session/purge.ts:4-6](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n### Scope Behaviors\n\n| Scope | Session ID Required | Data Removed | Side Effects |\n|-------|---------------------|--------------|--------------|\n| session | Yes | Only rows for given sessionId | DB file preserved |\n| project | No | All sessions in project | Full wipe of project data |\n\n### Session-Scoped Operations\n\nWhen `scope: \"session\"` is specified with a `sessionId`:\n\n- Only rows belonging to the specified session are removed\n- The SQLite database file remains intact\n- The events.md sidecar is preserved\n- FTS5 full-text search indexes are maintained\n- Stats files are untouched\n\nSource: [src/session/purge.ts:17-25](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n### Project-Scoped Operations\n\nWhen `scope: \"project\"` is specified:\n\n- Complete removal of all session data for the project\n- Database file deletion\n- Associated sidecar files removal\n- Legacy hash compatibility paths also cleaned\n\n## Purge Operations\n\n### purgeSession Function\n\nThe primary cleanup API supports both session and project-scoped purging:\n\n```typescript\nasync function purgeSession(\n  projectDir: string,\n  sessionId?: string,\n  scope?: \"session\" | \"project\"\n): Promise<PurgeResult>\n```\n\nSource: [src/session/purge.ts](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n### Purge Workflow\n\n```mermaid\ngraph TD\n    A[purgeSession Called] --> B{scope === 'session'?}\n    B -->|Yes| C{sessionId provided?}\n    C -->|No| D[Throw TypeError]\n    C -->|Yes| E[Get hashes for project]\n    E --> F[Open SessionDB per hash]\n    F --> G[Count events before purge]\n    G --> H[Delete session rows]\n    H --> I{rowsRemoved?}\n    I -->|Yes| J[Log removal]\n    I -->|No| K[Skip logging]\n    B -->|No| L[Project-scoped wipe]\n    L --> M[Delete all project data]\n    M --> N[Clean legacy paths]\n```\n\n### Validation Rules\n\nSession-scoped purging requires explicit sessionId:\n\n```typescript\nif (effectiveScope === \"session\" && !sessionId) {\n  throw new TypeError(\n    \"purgeSession: scope:'session' requires sessionId. \" +\n    \"Pass scope:'project' for the legacy whole-project wipe.\"\n  );\n}\n```\n\nSource: [src/session/purge.ts:10-14](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n## Analytics System\n\n### Purpose\n\nThe analytics module tracks session usage patterns and generates statistics for project health monitoring.\n\nSource: [src/session/analytics.ts](https://github.com/mksglu/context-mode/blob/main/src/session/analytics.ts)\n\n### Key Metrics\n\n| Metric | Description | Storage Location |\n|--------|-------------|------------------|\n| Session Count | Number of active sessions | stats.json |\n| Event Count | Total events across sessions | SessionDB |\n| Last Activity | Most recent session interaction | stats.json |\n| Project Activity | Aggregate usage statistics | stats.json |\n\n## Project Attribution\n\n### Role\n\nThe project attribution system maintains the relationship between session data and their originating project directories, enabling:\n\n- Cross-session context aggregation\n- Project-level statistics compilation\n- Worktree-aware hash generation\n- Legacy compatibility for migrated projects\n\nSource: [src/session/project-attribution.ts](https://github.com/mksglu/context-mode/blob/main/src/session/project-attribution.ts)\n\n### Hash Compatibility\n\nThe system maintains compatibility between canonical and legacy hash algorithms:\n\n```typescript\nconst hashes = canonicalHash === legacyHash\n  ? [canonicalHash]\n  : [canonicalHash, legacyHash];\n```\n\nThis ensures that projects migrated between different hash strategies can still access their historical session data.\n\nSource: [src/session/purge.ts:31-33](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n## Store API\n\n### Store Directory Management\n\nThe store directory module handles:\n\n- Directory creation and validation\n- Path resolution for session databases\n- Cross-platform path normalization\n- Worktree suffix generation\n\nSource: [src/store-directory.ts](https://github.com/mksglu/context-mode/blob/main/src/store-directory.ts)\n\n### High-Level Store Operations\n\n```typescript\ninterface Store {\n  getSession(sessionId: string): Session;\n  createSession(projectDir: string): Session;\n  addEvent(sessionId: string, event: Event): void;\n  querySessions(filter: QueryFilter): Session[];\n}\n```\n\nSource: [src/store.ts](https://github.com/mksglu/context-mode/blob/main/src/store.ts)\n\n## Configuration\n\n### Database Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| dbPath | string | Required | Path to SQLite database file |\n| inMemory | boolean | false | Use in-memory database for testing |\n| verbose | boolean | false | Enable SQL query logging |\n\n### Storage Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| projectDir | string | process.cwd() | Root directory for session storage |\n| sessionsDir | string | .context/sessions | Relative path for session databases |\n| enableFTS | boolean | true | Enable full-text search indexing |\n\n## Error Handling\n\n### Common Errors\n\n| Error | Condition | Resolution |\n|-------|-----------|-------------|\n| TypeError | session scope without sessionId | Provide sessionId or use project scope |\n| ENOENT | Database file not found | Ensure project directory exists |\n| EACCES | Permission denied | Check file system permissions |\n| SQLITE_BUSY | Database locked | Retry operation or close other connections |\n\n### Cleanup on Error\n\nThe purge operation ensures database connections are properly closed:\n\n```typescript\nlet db: SessionDB | null = null;\ntry {\n  db = new SessionDB({ dbPath });\n  // ... operations\n} finally {\n  if (db) db.close();\n}\n```\n\nSource: [src/session/purge.ts:35-42](https://github.com/mksglu/context-mode/blob/main/src/session/purge.ts)\n\n## Best Practices\n\n### Session Management\n\n1. Always provide explicit scope when calling purge operations\n2. Use session IDs consistently across your application\n3. Handle database errors with appropriate fallbacks\n4. Close database connections after operations\n\n### Performance Considerations\n\n1. Batch event insertions when possible\n2. Use project-scoped operations for complete cleanups\n3. Leverage FTS5 for text search instead of full table scans\n4. Clean up unused session data regularly\n\n### Data Integrity\n\n1. Verify hash calculations match across sessions\n2. Check database file existence before operations\n3. Use transactions for multi-step operations\n4. Maintain legacy hash support for backwards compatibility\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: mksglu/context-mode\n\nSummary: Found 23 potential pitfall items; 3 are high/blocking. Highest priority: installation - 来源证据：Feature Request: Add CodeBuddy Code support.\n\n## 1. installation · 来源证据：Feature Request: Add CodeBuddy Code support\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Feature Request: Add CodeBuddy Code support\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e09face1208e43d685be6c8ebf7015e9 | https://github.com/mksglu/context-mode/issues/651 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 2. installation · 来源证据：ctx_batch_execute corrupts heredoc commands by appending stderr redirection\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx_batch_execute corrupts heredoc commands by appending stderr redirection\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_6888a03e6d5b4d9492dff3e5efce4f48 | https://github.com/mksglu/context-mode/issues/656 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. installation · 来源证据：v1.0.146: plugin.json points to wrong skills path and stale MCP server path\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v1.0.146: plugin.json points to wrong skills path and stale MCP server path\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e1ebfb0450e44c198d3ff017d55a51d0 | https://github.com/mksglu/context-mode/issues/658 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 4. installation · 来源证据：OpenCode plugin registers hooks only -- never registers ctx_* tools\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：OpenCode plugin registers hooks only -- never registers ctx_* tools\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_d1ee350cd2374bb785a0628089fee355 | https://github.com/mksglu/context-mode/issues/637 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 5. installation · 来源证据：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.cla…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.claude/ instead of ~/.pi/\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8f49345b591f4f51afc650b8732da4d3 | https://github.com/mksglu/context-mode/issues/561 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 6. installation · 来源证据：Pi subagent fails: DatabaseLockedError - another context-mode server is already running\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi subagent fails: DatabaseLockedError - another context-mode server is already running\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e0a18821f52c4610a9109f8cb6920829 | https://github.com/mksglu/context-mode/issues/562 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 7. installation · 来源证据：[BUG]: Hardcoded storage path for many platforms\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: Hardcoded storage path for many platforms\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_b64e0c04c70b4726a0e860dc6a0954c9 | https://github.com/mksglu/context-mode/issues/649 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 8. installation · 来源证据：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_89e33c17dcfa452c8ad33ba344a9c6bb | https://github.com/mksglu/context-mode/issues/646 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 9. installation · 来源证据：[Bug]: Plugin-only installation does not work with OpenCode\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Plugin-only installation does not work with OpenCode\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_50609b9a9e2b4d4682713f28fd4c5d6d | https://github.com/mksglu/context-mode/issues/652 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 10. installation · 来源证据：ctx-upgrade leaves old server process running (zombie instance on upgrade)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx-upgrade leaves old server process running (zombie instance on upgrade)\n- User impact: 可能影响升级、迁移或版本选择。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_92a91d8bb13e4cf594229b3280c4d2eb | https://github.com/mksglu/context-mode/issues/559 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 11. installation · 来源证据：sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — deletes fresh symlinks whose targets are stale;…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — deletes fresh symlinks whose targets are stale; 4-char `lstatSync` fix\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ccef8bb7485f482f9bcb08b6cc2494b2 | https://github.com/mksglu/context-mode/issues/644 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 12. configuration · 可能修改宿主 AI 配置\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- User impact: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- Suggested check: 列出会写入的配置文件、目录和卸载/回滚步骤。\n- Guardrail action: 涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- Evidence: capability.host_targets | github_repo:1164477708 | https://github.com/mksglu/context-mode | host_targets=claude, claude_code\n\n## 13. configuration · 来源证据：No exclusive lock on SQLite database — multiple server instances cause unbounded WAL growth and query hangs\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：No exclusive lock on SQLite database — multiple server instances cause unbounded WAL growth and query hangs\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_a629676796f7486d9e185f643b260d07 | https://github.com/mksglu/context-mode/issues/560 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 14. configuration · 来源证据：Preview truncation slices UTF-16 surrogate pairs, producing orphan `\\uD83D` in tool_result and breaking the host API re…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Preview truncation slices UTF-16 surrogate pairs, producing orphan `\\uD83D` in tool_result and breaking the host API request\n- User impact: 可能影响升级、迁移或版本选择。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_d52bae5266e442cea5a1fa5b42f86c1a | https://github.com/mksglu/context-mode/issues/659 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 15. 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:1164477708 | https://github.com/mksglu/context-mode | README/documentation is current enough for a first validation pass.\n\n## 16. runtime · 来源证据：[BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP server reads from `<project-hash>.db` — `ctx_sta…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP server reads from `<project-hash>.db` — `ctx_stats` and timeline search degraded\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_cbceaf1c624d40049ac2151af7c1e83d | https://github.com/mksglu/context-mode/issues/645 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 17. 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:1164477708 | https://github.com/mksglu/context-mode | last_activity_observed missing\n\n## 18. 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:1164477708 | https://github.com/mksglu/context-mode | no_demo; severity=medium\n\n## 19. 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:1164477708 | https://github.com/mksglu/context-mode | no_demo; severity=medium\n\n## 20. security_permissions · 来源证据：PreToolUse hook fails on project paths containing spaces (macOS)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：PreToolUse hook fails on project paths containing spaces (macOS)\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_0e6f8fa845c0493db18d97fc48cf1b82 | https://github.com/mksglu/context-mode/issues/636 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 21. security_permissions · 来源证据：[BUG]: MCP bridge silently degrades on slow `initialize` — retry on timeout instead of failing permanently\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[BUG]: MCP bridge silently degrades on slow `initialize` — retry on timeout instead of failing permanently\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_c17fbb0a32674c7b9dad1eefe4a0c3d2 | https://github.com/mksglu/context-mode/issues/647 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 22. 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:1164477708 | https://github.com/mksglu/context-mode | issue_or_pr_quality=unknown\n\n## 23. 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:1164477708 | https://github.com/mksglu/context-mode | release_recency=unknown\n\n<!-- canonical_name: mksglu/context-mode; 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: mksglu/context-mode\n\nSummary: Found 23 potential pitfall items; 3 are high/blocking. Highest priority: installation - 来源证据：Feature Request: Add CodeBuddy Code support.\n\n## 1. installation · 来源证据：Feature Request: Add CodeBuddy Code support\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Feature Request: Add CodeBuddy Code support\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e09face1208e43d685be6c8ebf7015e9 | https://github.com/mksglu/context-mode/issues/651 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 2. installation · 来源证据：ctx_batch_execute corrupts heredoc commands by appending stderr redirection\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx_batch_execute corrupts heredoc commands by appending stderr redirection\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_6888a03e6d5b4d9492dff3e5efce4f48 | https://github.com/mksglu/context-mode/issues/656 | 来源讨论提到 python 相关条件，需在安装/试用前复核。\n\n## 3. installation · 来源证据：v1.0.146: plugin.json points to wrong skills path and stale MCP server path\n\n- Severity: high\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v1.0.146: plugin.json points to wrong skills path and stale MCP server path\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e1ebfb0450e44c198d3ff017d55a51d0 | https://github.com/mksglu/context-mode/issues/658 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 4. installation · 来源证据：OpenCode plugin registers hooks only -- never registers ctx_* tools\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：OpenCode plugin registers hooks only -- never registers ctx_* tools\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_d1ee350cd2374bb785a0628089fee355 | https://github.com/mksglu/context-mode/issues/637 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 5. installation · 来源证据：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.cla…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi bridge preserves claude-code identification env vars — spawned server misdetects as claude-code and writes to ~/.claude/ instead of ~/.pi/\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_8f49345b591f4f51afc650b8732da4d3 | https://github.com/mksglu/context-mode/issues/561 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 6. installation · 来源证据：Pi subagent fails: DatabaseLockedError - another context-mode server is already running\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Pi subagent fails: DatabaseLockedError - another context-mode server is already running\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_e0a18821f52c4610a9109f8cb6920829 | https://github.com/mksglu/context-mode/issues/562 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 7. installation · 来源证据：[BUG]: Hardcoded storage path for many platforms\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: Hardcoded storage path for many platforms\n- User impact: 可能阻塞安装或首次运行。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_b64e0c04c70b4726a0e860dc6a0954c9 | https://github.com/mksglu/context-mode/issues/649 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 8. installation · 来源证据：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[BUG]: `ctx_search` source filter does not escape LIKE wildcards — unintended cross-source result leakage\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_89e33c17dcfa452c8ad33ba344a9c6bb | https://github.com/mksglu/context-mode/issues/646 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 9. installation · 来源证据：[Bug]: Plugin-only installation does not work with OpenCode\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Bug]: Plugin-only installation does not work with OpenCode\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_50609b9a9e2b4d4682713f28fd4c5d6d | https://github.com/mksglu/context-mode/issues/652 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 10. installation · 来源证据：ctx-upgrade leaves old server process running (zombie instance on upgrade)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ctx-upgrade leaves old server process running (zombie instance on upgrade)\n- User impact: 可能影响升级、迁移或版本选择。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_92a91d8bb13e4cf594229b3280c4d2eb | https://github.com/mksglu/context-mode/issues/559 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 11. installation · 来源证据：sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — deletes fresh symlinks whose targets are stale;…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：sessionstart.mjs age-gated cleanup uses `statSync` (follows symlinks) — deletes fresh symlinks whose targets are stale; 4-char `lstatSync` fix\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_ccef8bb7485f482f9bcb08b6cc2494b2 | https://github.com/mksglu/context-mode/issues/644 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 12. configuration · 可能修改宿主 AI 配置\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- User impact: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- Suggested check: 列出会写入的配置文件、目录和卸载/回滚步骤。\n- Guardrail action: 涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- Evidence: capability.host_targets | github_repo:1164477708 | https://github.com/mksglu/context-mode | host_targets=claude, claude_code\n\n## 13. configuration · 来源证据：No exclusive lock on SQLite database — multiple server instances cause unbounded WAL growth and query hangs\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：No exclusive lock on SQLite database — multiple server instances cause unbounded WAL growth and query hangs\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_a629676796f7486d9e185f643b260d07 | https://github.com/mksglu/context-mode/issues/560 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。\n\n## 14. configuration · 来源证据：Preview truncation slices UTF-16 surrogate pairs, producing orphan `\\uD83D` in tool_result and breaking the host API re…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Preview truncation slices UTF-16 surrogate pairs, producing orphan `\\uD83D` in tool_result and breaking the host API request\n- User impact: 可能影响升级、迁移或版本选择。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_d52bae5266e442cea5a1fa5b42f86c1a | https://github.com/mksglu/context-mode/issues/659 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 15. 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:1164477708 | https://github.com/mksglu/context-mode | README/documentation is current enough for a first validation pass.\n\n## 16. runtime · 来源证据：[BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP server reads from `<project-hash>.db` — `ctx_sta…\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[BUG]:Pi and OMP adapters write SessionDB to `context-mode.db` but MCP server reads from `<project-hash>.db` — `ctx_stats` and timeline search degraded\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_cbceaf1c624d40049ac2151af7c1e83d | https://github.com/mksglu/context-mode/issues/645 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 17. 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:1164477708 | https://github.com/mksglu/context-mode | last_activity_observed missing\n\n## 18. 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:1164477708 | https://github.com/mksglu/context-mode | no_demo; severity=medium\n\n## 19. 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:1164477708 | https://github.com/mksglu/context-mode | no_demo; severity=medium\n\n## 20. security_permissions · 来源证据：PreToolUse hook fails on project paths containing spaces (macOS)\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：PreToolUse hook fails on project paths containing spaces (macOS)\n- User impact: 可能增加新用户试用和生产接入成本。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_0e6f8fa845c0493db18d97fc48cf1b82 | https://github.com/mksglu/context-mode/issues/636 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 21. security_permissions · 来源证据：[BUG]: MCP bridge silently degrades on slow `initialize` — retry on timeout instead of failing permanently\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[BUG]: MCP bridge silently degrades on slow `initialize` — retry on timeout instead of failing permanently\n- User impact: 可能影响授权、密钥配置或安全边界。\n- Suggested check: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Guardrail action: 不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- Evidence: community_evidence:github | cevd_c17fbb0a32674c7b9dad1eefe4a0c3d2 | https://github.com/mksglu/context-mode/issues/647 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 22. 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:1164477708 | https://github.com/mksglu/context-mode | issue_or_pr_quality=unknown\n\n## 23. 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:1164477708 | https://github.com/mksglu/context-mode | 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": "# context-mode - 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 mksglu/context-mode.\n\nProject:\n- Name: context-mode\n- Repository: https://github.com/mksglu/context-mode\n- Summary: Context window optimization for AI coding agents. Sandboxes tool output, 98% reduction. 15 platforms\n- Host target: claude, claude_code\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Context window optimization for AI coding agents. Sandboxes tool output, 98% reduction. 15 platforms\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: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n- Capability 2: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. introduction: Introduction to Context Mode. Produce one small intermediate artifact and wait for confirmation.\n2. core-concepts: Core Concepts. Produce one small intermediate artifact and wait for confirmation.\n3. getting-started: Getting Started. Produce one small intermediate artifact and wait for confirmation.\n4. architecture-overview: Architecture Overview. Produce one small intermediate artifact and wait for confirmation.\n5. platform-adapters: Platform Adapters. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/mksglu/context-mode\n- https://github.com/mksglu/context-mode#readme\n- .claude/skills/context-mode-ops/SKILL.md\n- skills/context-mode/SKILL.md\n- skills/ctx-doctor/SKILL.md\n- skills/ctx-insight/SKILL.md\n- skills/ctx-purge/SKILL.md\n- skills/ctx-stats/SKILL.md\n- skills/ctx-upgrade/SKILL.md\n- README.md\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: mksglu/context-mode\n\n## Official Entry Points\n\n### Node.js / npx · 官方安装入口\n\n```bash\nnpx -y context-mode\n```\n\nSource：https://github.com/mksglu/context-mode#readme\n\n## Sources\n\n- repo: https://github.com/mksglu/context-mode\n- docs: https://github.com/mksglu/context-mode#readme\n",
      "summary": "Entry points extracted from official README or installation documentation.",
      "title": "Quick Start"
    }
  },
  "validation_id": "dval_1b850136039541bcaeca4528ebd3bfd6"
}
