AIStoreHub Package Vault: Context Mode
Package Slug: context-mode
Archetype: mcp_server
Upstream Repository: https://github.com/mksglu/context-mode
Workspace Files & Specifications (68 files)
- .agents/plugins/marketplace.json (377 bytes)
{ "name": "context-mode", "interface": { "displayName": "context-mode" }, "plugins": [ { "name": "context-mode", "source": { "source": "local", "path": "./plugins/claude-code" }, "policy": { "installation": "AVAILABLE", "authentication": "ON_INSTALL" }, "category": "Productivity" } ] } - .claude-plugin/marketplace.json (981 bytes)
{ "description": "Context window saver for 11 coding agents. Local and free: sandboxed code execution, FTS5 search, session continuity.", "name": "context-mode", "owner": { "name": "context-mode" }, "plugins": [ { "author": { "name": "Mert Koseoglu", "url": "https://github.com/mksglu/context-mode#readme" }, "description": "Context window saver for 11 coding agents. Local and free: sandboxed code execution, FTS5 search, session continuity.", "name": "context-mode", "source": "./plugins/claude-code", "version": "2.2.1", "keywords": [ "claude-code", "codex", "gemini-cli", "qwen-code", "copilot-cli", "vscode", "opencode", "pi", "kiro", "zcode", "omp", "mcp", "context-window", "sandbox", "fts5", "pi-package" ] } ], "metadata": { "version": "2.2.1" } } - .claude-plugin/plugin.json (852 bytes)
{ "name": "context-mode", "version": "2.2.1", "description": "Context window saver for 11 coding agents. Local and free: sandboxed code execution, FTS5 search, session continuity.", "author": { "name": "Mert Koseoglu", "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": [ "claude-code", "codex", "gemini-cli", "qwen-code", "copilot-cli", "vscode", "opencode", "pi", "kiro", "zcode", "omp", "mcp", "context-window", "sandbox", "fts5", "pi-package" ], "mcpServers": { "context-mode": { "command": "node", "args": [ "${CLAUDE_PLUGIN_ROOT}/start.mjs" ] } }, "skills": "./skills/" } - .claude/settings.json (284 bytes)
{ "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/skills/release/SKILL.md (2786 bytes)
--- name: release description: Release context-mode v2 from the v2 branch. Runs the checks and the live test, shows the next version and notes, then starts the release workflow and watches it. disable-model-invocation: true --- Release context-mode v2 (ADR-0013). Starting the skill is the approval for this release; the preview in step 6 is for information, not a second approval. Stop and report at the first step that fails; do not retry a failed step with a different method. 1. Check the start state. Run `git branch --show-current` and `git status --porcelain`. The branch must be `v2` and the tree must be clean; if not, stop and report what is dirty. Run `gh auth status` and `git pull --ff-only`. 2. Run the E2E cases: `node e2e/cases/run.mjs`. If a row is `FAIL`, stop and report the failing case ids. 3. Run the v1 KEEP-PASS unit tests (GS4). `npm ci` installs the dev toolchain only (ADR-0013 "Trust boundary"); users never run npm. Then run `npx vitest run`. If one of the 131 tracked tests fails, stop and show its name. 4. Run the live test: `node e2e/live/run.mjs --all` (Sonnet 5, effort low, ADR-0017) and show its table. If a row is `FAIL`, stop. Then update the live-skip streak in `e2e/live/skip-streak.json` (`{ "streak": <n> }`): if the table has one or more `SKIPPED` rows, add 1 to `streak`; if it has none, reset it to 0. If the file changed, commit it on `v2` and push. If `streak` is now `LIVE_SKIP_LIMIT` (3) or more, refuse to continue: report which cases were skipped and the note on each row. 5. v1 migration checkpoint (GS10). The cases `e2e/live/cases/v1-migration-*.json` ran in step 4 (their `covers` paths include `v1-transition`, so `--all` selects them). Do not run them again; confirm each one is `PASS` in the step 4 table, and stop if one is not. 6. Preview. Run `node scripts/release/plan.mjs --dry-run`. Show the owner the next version and the release notes. If it says there is nothing to release, stop. 7. Start the release: `gh workflow run release.yml --ref v2 -f sha=$(git rev-parse HEAD)`. 8. Follow the new run with `gh run watch` and report each job status as it changes. At the end, report in one short table: version, release commit on `release`, GitHub Release URL, live test (passed, or skipped), and the smoke-install result per agent. `skip-live`: if the owner types `/release skip-live`, skip steps 4 and 5 (the streak file does not change) and in step 6 run `node scripts/release/plan.mjs --dry-run --skip-live`, so the release notes carry the line "Live E2E skipped for this release." Say in the final report that the live test was skipped. This skill never runs these one-time steps: switching the marketplace to `ref: "release"`, adding workflows to `main`, and `npm deprecate`. Ask the owner about each one separately. - .codex-plugin/hooks.json (1450 bytes)
{ "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": [ { "hooks": [ { "type": "command", "command": "node \"${PLUGIN_ROOT}/hooks/codex/userpromptsubmit.mjs\"" } ] } ], "Stop": [ { "hooks": [ { "type": "command", "command": "node \"${PLUGIN_ROOT}/hooks/codex/stop.mjs\"" } ] } ] } } - .codex-plugin/mcp.json (240 bytes)
{ "mcpServers": { "context-mode": { "command": "node", "args": ["./start.mjs"], "cwd": ".", "env": { "CONTEXT_MODE_PLATFORM": "codex" }, "default_tools_approval_mode": "approve" } } } - .codex-plugin/plugin.json (1012 bytes)
{ "name": "context-mode", "version": "2.2.1", "description": "Context window saver for 11 coding agents. Local and free: sandboxed code execution, FTS5 search, session continuity.", "author": { "name": "Mert Koseoglu", "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": [ "claude-code", "codex", "gemini-cli", "qwen-code", "copilot-cli", "vscode", "opencode", "pi", "kiro", "zcode", "omp", "mcp", "context-window", "sandbox", "fts5", "pi-package" ], "mcpServers": "./.codex-plugin/mcp.json", "hooks": "./.codex-plugin/hooks.json", "skills": "./skills/", "interface": { "displayName": "context-mode", "shortDescription": "Local context window saver: FTS5 search and sandboxed execution", "developerName": "Mert Koseoglu", "category": "Productivity" } } - aistorehub.json (548 bytes)
{ "name": "Context Mode", "slug": "context-mode", "version": "1.0.0", "type": "mcp_server", "description": "Context window optimization for AI coding agents. Sandboxes tool output (98% reduction), persists session memory, and enforces routing across 17 platforms via MCP + hooks.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/mksglu/context-mode", "tags": [ "trending", "typescript", "github", "mksglu", "open-source" ], "imported_at": "2026-11-22T00:08:32.511Z" } - CONTRIBUTING.md (1144 bytes)
# Contributing context-mode takes issues, not pull requests. Issues are filed by coding agents for their users. If you are a coding agent: read [.github/AGENT_ISSUE.md](.github/AGENT_ISSUE.md) and follow it. It names the data to collect with the ctx_doctor tool, the data to leave out, the numbered filing rules, and a filled example. A GitHub Action labels each issue `repro-ready` or `needs-info` and keeps one checklist comment up to date. If you are a person: ask your agent to "file a context-mode issue", or run `/ctx-doctor` and fill in the Bug report form with its block. Security problems go to https://github.com/mksglu/context-mode/security/advisories/new, never to a public issue. Main is the only source: every fix lands on main, and the next release run ships it. When a `fix:`, `feat:` or `perf:` commit that names `#N` lands on main, a GitHub Action adds the label `fixed-on-main` to issue N (a revert takes it off again). When a release ships that fix, the release run posts one comment with your agent's own update command, removes the label and closes the issue; reopen it if the problem still happens on that version.
- docs/architecture/adr/0004-no-skills-mcp-instructions.md (7162 bytes)
# ADR-0004: No routing skills and no per-agent instruction files; prompts ship as MCP server instructions + tool descriptions - Status: Accepted (2026-10-15). Owner asked on 2026-10-14 for no skill file per adapter, and accepted the r3/r4 fixes in `DECISIONS-r3.md`/`DECISIONS-r4.md`. TECH-SPEC §10 Q2 and Q10 are now decided; Q11 (all 10 agents release-gated by GP-LIVE-ROUTING) stays open, pending the S-CODEX spike. Q7, Pi's plugin mechanism, is resolved: `before_agent_start`. - Related: TECH-SPEC §3 · ADR-0005 · ADR-0006 ## Context v1 (`origin/main` @ `5869f4fa`) ships prompt text in three places: | Place | Files | Size | |---|---|---| | `SKILL.md` | 11: `skills/` ×8, `configs/copilot-cli/skills/context-mode`, `configs/antigravity-cli/skills/context-mode`, `.claude/skills/context-mode-ops` (maintainer only) | the routing skill alone is 16,683 B; its 3 copies are 300, 38 and 77 lines | | Per-agent routing files in `configs/` | 13: `CLAUDE.md`, `AGENTS.md` ×6, `GEMINI.md` ×2, `QWEN.md`, `SYSTEM.md`, `copilot-instructions.md` ×2 | 55,870 B | | Tool descriptions | 11 tools | 17,075 chars of descriptions + 9,749 chars of input schemas. 5 descriptions are longer than Claude Code's 2,048-char cut | - Manifests that ship skills: - `.claude-plugin/plugin.json:30` - `.codex-plugin/plugin.json:24` - `.cursor-plugin/plugin.json:25` - `configs/antigravity-cli/plugin.json:11` - `configs/copilot-cli/.github/plugin/plugin.json:20` - `package.json:34` (`pi.skills`) and `package.json:68` (`files`) - Adapters that write routing files into user space: Codex (`ROUTING_INSTRUCTIONS_PATH = "configs/codex/AGENTS.md"`), Kimi, OpenClaw, Qwen (`targetPath: "QWEN.md"`). - The v1 server sends **no** `instructions`. `new McpServer({name, version})` at `src/server.ts:143`, and a live `initialize` returned `instructions: null`. MCP defines one portable channel for this: `InitializeResult.instructions`. - Schema 2025-11-25: "this information MAY be added to the system prompt". - Schema 2026-07-28: instructions "should not duplicate information already in tool descriptions". Which agents pass `instructions` to the model is in TECH-SPEC §3.1. Summary: - **Confirmed** in source or by a live probe: Claude Code, Gemini CLI, Qwen Code, OpenCode 2, VS Code Copilot. - **Pi:** does not receive `instructions` over MCP in v2. v2 runs Pi as an in-process plugin, not over MCP (TECH-SPEC §3.1, §3.9; matches Decision 5 below), so it gets the same `instructions.md` bytes through its `before_agent_start` plugin hook instead. - **Codex:** the instructions are wired to the tool namespace, but a live probe saw nothing at session start. S-CODEX (closed 2026-10-17, `https://github.com/mksglu/context-mode/blob/274600e2ffab843e89c1dfa09b0d649e650c962f/tickets/spikes-r5/S-CODEX.md`) confirms by live probe (3/3, ChatGPT login, `gpt-6-astra`) that this is deferred loading: the model sees no namespace marker and no tool description before it calls a tool, and sees the full description only once it looks up / calls the tool. - **Copilot CLI:** verified by live probe (`copilot plugin install` on Copilot CLI 1.0.60, same method v1 used in 9f34c6f1): a plugin can register MCP servers and hooks, and `InitializeResult.instructions` reaches the model. This replaces the earlier "probable; no source check" line. - **Not supported:** Kiro (kirodotdev/Kiro#11096 is still open). - **No evidence:** ZCode. - **This project's own routing-block style.** This repo's maintainer-facing `CLAUDE.md` uses a MANDATORY/BLOCKED caps-heavy routing block. That pattern is named in #946 as one that can trip AI safety classifiers. `CLAUDE.md` is in this ADR's delete scope for Claude Code (it is one of the 13 per-agent routing files in the Context table above) and must be rewritten in plain style, not caps-heavy MANDATORY/BLOCKED blocks, when decision 4 is carried out. ## Decision 1. **One prompt source in the repo:** `src/prompt/instructions.md` and `src/prompt/tools/<tool>.md`. The build inlines them into the bundle. No other file in the repo or in user space carries routing text. 2. **Two channels, split by job, with no duplication:** - **Server `instructions`:** what the server is for, when to search for and use its tools, and when not to. - **Tool descriptions:** what each tool does and how to call it. Each one is self-contained, because it is the only channel on agents that ignore `instructions`. 3. **Exception (2026-10-14):** three user-command skills stay, `/ctx-stats`, `/ctx-doctor`, `/ctx-upgrade`. They hold no routing text; each only calls its tool (TECH-SPEC §3.9). One `skills/` source dir. 4. **Deleted:** - the routing skill and the other v1 `SKILL.md` files (11), replaced by the 3 command skills - all 13 routing files - the `skills` keys in every manifest and in `package.json` - every adapter code path that writes `AGENTS.md`, `QWEN.md`, `GEMINI.md`, `CLAUDE.md` or `copilot-instructions.md` The maintainer skill `.claude/skills/context-mode-ops` is removed from the repo too (Q4, decided 2026-10-14). 4. Agents that ignore `instructions` (Kiro, possibly ZCode) get routing from tool descriptions only. No steering file is added for them. 5. Pi runs as an in-process plugin, not over MCP. It gets the same `instructions.md` bytes through its `before_agent_start` plugin hook (TECH-SPEC §3.1, §3.9). ## Consequences - One text to review, lint (ADR-0005) and golden-test (GP2). - On Claude Code with tool search on, `instructions` is the **only** context-mode text the model sees before it searches for a tool. This is verified by a live probe (TECH-SPEC §3.1). It makes ADR-0006 necessary. - On Codex, the live probe showed neither instructions nor tool descriptions at session start. Routing quality on Codex has to be measured in E2E-live before release. - User-owned instruction files are never touched again. This removes a v1 bug class: install and upgrade overwrote user hooks and config (#1235, #1239, #1160). - On OpenCode 2, the 3 command skills have no slash-command path: OpenCode 2 only lets the model call a `skill` tool with a matching id (`packages/core/src/tool/plugin/skill.ts`, pinned `1438073`). A user cannot type `/ctx-stats` there and be guaranteed it runs; the model has to decide to call `skill` with that id. This gap is accepted, named here, and detailed in TECH-SPEC §3.9 (S-SKILLS), the same pattern as GS5's other per-agent carve-outs. ## Alternatives considered - **Per-agent instruction files (AGENTS.md etc.).** Rejected: 13 diverging copies, written into user-owned files. - **Skills.** Rejected: each agent packages them differently, MCP-only agents never load them, and they need one copy per agent. - **MCP prompts.** Rejected for routing: the user has to invoke them. One prompt is kept as a user command: `ctx-stats` (TECH-SPEC §3.9). ## Changes - r4: scoped this project's own `CLAUDE.md` into the delete/rewrite list (A56); verified Copilot CLI's `instructions` support by live probe instead of "probable" (B9); resolved Pi's plugin mechanism as `before_agent_start`, closing Q7 (B19); named the OpenCode 2 command-skill gap explicitly (B16). - gemini-extension.json (387 bytes)
{ "description": "Context window saver for 11 coding agents. Local and free: sandboxed code execution, FTS5 search, session continuity.", "mcpServers": { "context-mode": { "args": [ "${extensionPath}${/}plugins/claude-code/server.mjs", "--agent", "gemini" ], "command": "node" } }, "name": "context-mode", "version": "2.2.1" } - INSTRUCTIONS.md (260 bytes)
--- name: ctx-upgrade description: Update context-mode to the latest release. disable-model-invocation: true --- Call the ctx_upgrade tool and show its table to the user. Then call ctx_doctor and show its table. If a restart is needed, say so in one sentence.
- LICENSE (3840 bytes)
Elastic License 2.0 (ELv2) Copyright 2026 Mert Koseoglu ## Acceptance By using the software, you agree to all of the terms and conditions below. ## Copyright License The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below. ## Limitations You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software. You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key. You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor's trademarks is subject to applicable law. ## Patents The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company. ## Notices You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms. If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software. ## No Other Rights These terms do not imply any licenses other than those expressly granted in these terms. ## Termination If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently. ## No Liability *As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.* ## Definitions The **licensor** is the entity offering these terms, and the **software** is the software the licensor makes available under these terms, including any portion of it. **you** refers to the individual or entity agreeing to these terms. **your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. **control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect. **your licenses** are all the licenses granted to you for the software under these terms. **use** means anything you do with the software requiring one of your licenses. **trademark** means trademarks, service marks, and similar rights.
- package.json (1369 bytes)
{ "name": "context-mode", "version": "2.2.1", "type": "module", "description": "Context window saver for 11 coding agents. Local and free: sandboxed code execution, FTS5 search, session continuity.", "author": "Mert Koseoglu", "license": "Elastic-2.0", "keywords": [ "claude-code", "codex", "gemini-cli", "qwen-code", "copilot-cli", "vscode", "opencode", "pi", "kiro", "zcode", "omp", "mcp", "context-window", "sandbox", "fts5", "pi-package" ], "repository": { "type": "git", "url": "git+https://github.com/mksglu/context-mode.git" }, "homepage": "https://github.com/mksglu/context-mode#readme", "bugs": { "url": "https://github.com/mksglu/context-mode/issues" }, "scripts": { "build": "node scripts/v1-upgrade-stop.mjs", "build:release": "node build/build.mjs --out release-out", "typecheck": "tsc --noEmit", "gate": "node scripts/gate.mjs", "e2e": "node e2e/cases/run.mjs" }, "devDependencies": { "@clack/prompts": "^1.0.1", "@modelcontextprotocol/sdk": "^1.26.0", "@modelcontextprotocol/server": "2.3.1", "@types/node": "^22.19.11", "esbuild": "0.24.0", "htmlparser2": "^12.0.0", "toml-eslint-parser": "1.0.3", "typescript": "^5.7.0", "zod": "^3.25.0" }, "engines": { "node": ">=24.15.0" } } - plugins/claude-code/codex/skills/ctx-doctor/SKILL.md (269 bytes)
--- name: ctx-doctor description: Check that context-mode is installed and working, as a table. disable-model-invocation: true --- Call the mcp__context_mode__ctx_doctor tool and show its table to the user unchanged. If a row failed, list the fixes it names, in order.
- plugins/claude-code/codex/skills/ctx-stats/SKILL.md (341 bytes)
--- name: ctx-stats description: Show how much context context-mode saved, as a detailed report. disable-model-invocation: true --- Call the mcp__context_mode__ctx_stats tool and show the text block of its reply to the user unchanged, inside a code block so the columns stay aligned. Add one sentence under it that names the largest saving.
- plugins/claude-code/codex/skills/ctx-upgrade/SKILL.md (298 bytes)
--- name: ctx-upgrade description: Update context-mode to the latest release. disable-model-invocation: true --- Call the mcp__context_mode__ctx_upgrade tool and show its table to the user. Then call mcp__context_mode__ctx_doctor and show its table. If a restart is needed, say so in one sentence.
- plugins/claude-code/pi/skills/ctx-doctor/SKILL.md (250 bytes)
--- name: ctx-doctor description: Check that context-mode is installed and working, as a table. disable-model-invocation: true --- Call the ctx_doctor tool and show its table to the user unchanged. If a row failed, list the fixes it names, in order.
- plugins/claude-code/pi/skills/ctx-stats/SKILL.md (322 bytes)
--- name: ctx-stats description: Show how much context context-mode saved, as a detailed report. disable-model-invocation: true --- Call the ctx_stats tool and show the text block of its reply to the user unchanged, inside a code block so the columns stay aligned. Add one sentence under it that names the largest saving.
- plugins/claude-code/pi/skills/ctx-upgrade/SKILL.md (260 bytes)
--- name: ctx-upgrade description: Update context-mode to the latest release. disable-model-invocation: true --- Call the ctx_upgrade tool and show its table to the user. Then call ctx_doctor and show its table. If a restart is needed, say so in one sentence.
- plugins/claude-code/skills/ctx-doctor/SKILL.md (367 bytes)
--- name: ctx-doctor description: Check that context-mode is installed and working, as a table. disable-model-invocation: true --- Call the mcp__plugin_context-mode_context-mode__ctx_doctor or mcp_context-mode_ctx_doctor or mcp__context-mode__ctx_doctor or ctx_doctor tool and show its table to the user unchanged. If a row failed, list the fixes it names, in order.
- plugins/claude-code/skills/ctx-stats/SKILL.md (436 bytes)
--- name: ctx-stats description: Show how much context context-mode saved, as a detailed report. disable-model-invocation: true --- Call the mcp__plugin_context-mode_context-mode__ctx_stats or mcp_context-mode_ctx_stats or mcp__context-mode__ctx_stats or ctx_stats tool and show the text block of its reply to the user unchanged, inside a code block so the columns stay aligned. Add one sentence under it that names the largest saving.
- plugins/claude-code/skills/ctx-upgrade/SKILL.md (497 bytes)
--- name: ctx-upgrade description: Update context-mode to the latest release. disable-model-invocation: true --- Call the mcp__plugin_context-mode_context-mode__ctx_upgrade or mcp_context-mode_ctx_upgrade or mcp__context-mode__ctx_upgrade or ctx_upgrade tool and show its table to the user. Then call mcp__plugin_context-mode_context-mode__ctx_doctor or mcp_context-mode_ctx_doctor or mcp__context-mode__ctx_doctor or ctx_doctor and show its table. If a restart is needed, say so in one sentence.
- qwen-extension.json (415 bytes)
{ "description": "Context window saver for 11 coding agents. Local and free: sandboxed code execution, FTS5 search, session continuity.", "hooks": "hooks/qwen.json", "mcpServers": { "context-mode": { "args": [ "${extensionPath}${/}plugins/claude-code/server.mjs", "--agent", "qwen" ], "command": "node" } }, "name": "context-mode", "version": "2.2.1" } - README.md (49521 bytes)
# Context Mode **A free, local plugin for 11 coding agents. It keeps tool output out of your agent's context window and keeps all usage data on your machine. The plugin is free forever.** [](https://www.npmjs.com/package/context-mode) [](https://github.com/mksglu/context-mode) [](https://discord.gg/DCN9jUgN5v) [](LICENSE) **34K GitHub stars · 892K npm downloads** (read 2026-11-21, [stats.json](stats.json)) · on the Hacker News front page and GitHub Trending: [charts and sources](#adoption-stars-and-npm-downloads) > The Context Mode plugin is free and local, with its source open on GitHub. **Context Mode Gateway** is a separate hosted service with its own account and subscription. It takes the same idea from tool output to the whole conversation: Gateway Recall keeps long sessions searchable, and Gateway Memory shares what your agents learn across sessions and tools. [See how the Gateway works](https://contextmode.ai/docs/how-saving-works?utm_source=github&utm_medium=readme&utm_content=quote) <picture> <source media="(prefers-color-scheme: dark)" srcset="docs/assets/readme/hero-dark.png"> <img src="docs/assets/readme/hero-light.png" alt="Context Mode plugin: free and local, zero telemetry, the plugin keeps your data on your machine. Bench of 2026-11-01: 99.4% of output bytes saved (median of 36 rows with 10 KB or more of raw output). A full debugging session (row g-session-total): 281,261 B raw to 3,266 B in context, about 70K to 817 tokens (an estimate at 4 B per token). Resume after compaction (row e-long-session): a 442,893 B transcript to a 2,019 B block, about 111K to 505 tokens (an estimate). Runs in 10 coding agents with 9 MCP tools."> </picture> **Contents:** [Why](#why) · [Adoption](#adoption-stars-and-npm-downloads) · [Install](#install) · [Try it](#try-it) · [Use cases](#use-cases) · [Benchmarks](#benchmarks) · [How it works](#how-it-works) · [Tools](#tools) · [Security and privacy](#security-and-privacy) · [Context Mode Gateway](#context-mode-gateway) · [License](#license) · [Community](#community) ## Why A coding agent reads files, runs commands and fetches pages, and every result goes into its context window. The Context Mode plugin runs that work in a local sandbox, keeps the full output in a SQLite index on your machine, and gives the agent the part it asks for. - **The plugin is free forever.** Use it at home and at work, free of charge, under a source-available license. - **Runs on your machine.** The hooks, the sandbox and search run as local processes next to your agent. - **The plugin keeps your data on your machine.** Every index lives in `~/.context-mode`: one `context.db` per project. - **Zero telemetry.** The plugin keeps all usage data on your machine. [Security and privacy](#security-and-privacy) lists each network call it makes. - **Works offline after install.** Sandbox runs, file indexing and search use local SQLite and your own runtimes. - **Code Mode.** The agent writes a short script instead of reading the data, and only what the script prints reaches the context: see [How it works, step 5](#code-mode). - **Small replies.** On the 36 bench rows with 10 KB or more of raw output, the plugin's median reply is 99.4% smaller than the raw output. ## Adoption: stars and npm downloads <table><tr> <td width="50%"><a href="https://contextmode.ai/open-source/stats?utm_source=github&utm_medium=readme&utm_content=adoption#stars"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/assets/readme/star-history-dark.png"><img src="docs/assets/readme/star-history-light.png" alt="Line chart of cumulative GitHub stars for mksglu/context-mode since 2026-02-23. A daily job redraws it."></picture></a></td> <td width="50%"><a href="https://contextmode.ai/open-source/stats?utm_source=github&utm_medium=readme&utm_content=adoption#daily"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/assets/readme/npm-downloads-dark.png"><img src="docs/assets/readme/npm-downloads-light.png" alt="Area chart of npm downloads per day for context-mode, the last 90 days. A daily job redraws it."></picture></a></td> </tr></table> Open the [interactive chart](https://contextmode.ai/open-source/stats?utm_source=github&utm_medium=readme&utm_content=adoption#daily) and point at a bar to read its value. Tabs there show days, weeks, months and years. Stars come from the GitHub GraphQL API (`starredAt`); npm downloads come from `api.npmjs.org/downloads/range`. The total up to 2026-10-29 is 683K npm downloads (`stats.json` keeps a daily copy). A daily job redraws both charts. - **Hacker News.** "MCP server that reduces Claude Code context consumption by 98%" reached the front page with 570+ points and 107 comments on 2026-02-28 ([thread](https://news.ycombinator.com/item?id=47193064)). - **GitHub Trending.** A bot that watches GitHub Trending logged the repo there on 14 days from 2026-04-24 to 2026-10-17 ([uibm/trending-watcher](https://github.com/uibm/trending-watcher/issues?q=%22mksglu%2Fcontext-mode%22)). <picture> <source media="(prefers-color-scheme: dark)" srcset="docs/assets/readme/stargazers-dark.png"> <img src="docs/assets/readme/stargazers-light.png" alt="Companies that stargazers of mksglu/context-mode name in their GitHub profile, Microsoft, Tencent, Alibaba, ByteDance, Google and more."> </picture> Starred by engineers at these companies: each name is the company field of 2 or more stargazer profiles, read with the GitHub GraphQL API on 2026-11-01 ([data](docs/assets/readme/data/stargazer-companies.json)). ## Install Pick your agent: [Claude Code](#install-claude-code) · [Codex](#install-codex) · [Gemini CLI](#install-gemini) · [Qwen Code](#install-qwen) · [Pi](#install-pi) · [OMP](#install-omp) · [OpenCode](#install-opencode) · [Copilot CLI](#install-copilot-cli) · [Kiro](#install-kiro) · [VS Code](#install-vscode) · [ZCode](#install-zcode) Open its block and copy its own install command. Each block also holds the update, check and remove steps, and the [Install guide](https://contextmode.ai/docs/engine/install?utm_source=github&utm_medium=readme&utm_content=install) walks through them. The plugin needs Node 24.15.0 or later, from the engines field in [package.json](package.json). On Windows, add Git for Windows: the shell tools run in Git Bash, and doctor checks for it. contextmode installs as the npm package and command `context-mode`. Claude Code, Codex, Gemini CLI and Qwen Code install from GitHub, and each of their commands names the release branch. <details id="install-claude-code"><summary><b>Claude Code</b></summary> ```sh claude plugin marketplace add mksglu/context-mode claude plugin install context-mode@context-mode ``` ```sh # update claude plugin update context-mode@context-mode # check claude plugin list # remove claude plugin marketplace remove context-mode ``` Hooks ✓ (package) · MCP ✓ · Skills ✓ </details> <details id="install-codex"><summary><b>Codex</b></summary> ```sh codex plugin marketplace add mksglu/context-mode codex plugin add context-mode@context-mode # one-time step: trust the plugin hooks npm i -g context-mode context-mode setup --agents codex ``` ```sh # update codex plugin marketplace upgrade context-mode # check codex mcp list # remove codex plugin remove context-mode@context-mode ``` Hooks ✓ (hook file) · MCP ✓ · Skills ✓ </details> <details id="install-gemini"><summary><b>Gemini CLI</b></summary> ```sh gemini extensions install https://github.com/mksglu/context-mode ``` ```sh # update gemini extensions update context-mode # check GEMINI_CLI_TRUST_WORKSPACE=true gemini mcp list # remove gemini extensions uninstall context-mode ``` Hooks ✓ (package) · MCP ✓ · Skills ✓ </details> <details id="install-qwen"><summary><b>Qwen Code</b></summary> ```sh qwen extensions install https://github.com/mksglu/context-mode:context-mode ``` ```sh # update qwen extensions update context-mode # check qwen extensions list # remove qwen extensions uninstall context-mode ``` Hooks ✓ (package) · MCP ✓ · Skills ✓ </details> <details id="install-pi"><summary><b>Pi</b></summary> ```sh pi install npm:context-mode ``` ```sh # update pi update --extensions # check pi list # remove pi remove npm:context-mode ``` Hooks ✓ (the plugin's own event handlers) · MCP ✓ (ctx tools built into the plugin) · Skills ✓ </details> <details id="install-omp"><summary><b>OMP</b></summary> ```sh omp plugin install context-mode ``` ```sh # update omp plugin upgrade context-mode # check omp plugin list # remove omp plugin uninstall context-mode ``` Hooks ✓ (the plugin's own event handlers) · MCP ✓ (ctx tools built into the plugin) · Skills ✓ </details> <details id="install-opencode"><summary><b>OpenCode</b></summary> ```sh opencode plugin add context-mode ``` ```sh # update opencode plugin update # check opencode mcp list --pure # OpenCode 1.19 opencode mcp list --standalone # OpenCode 2 # remove opencode plugin remove context-mode ``` Hooks ✓ (the plugin's own event handlers) · MCP ✓ · Skills ✓ </details> <details id="install-copilot-cli"><summary><b>Copilot CLI</b></summary> ```sh npm i -g context-mode context-mode setup --agents copilot-cli ``` ```sh # update context-mode upgrade # check context-mode doctor --agents copilot-cli copilot mcp list # remove context-mode setup --remove --agents copilot-cli ``` Hooks ✓ (hook file) · MCP ✓ · Skills ✓ </details> <details id="install-kiro"><summary><b>Kiro</b></summary> ```sh npm i -g context-mode context-mode setup --agents kiro ``` ```sh # update context-mode upgrade # check context-mode doctor --agents kiro # remove context-mode setup --remove --agents kiro ``` Hooks ✓ (hook file) · MCP ✓ · Skills ✓ </details> <details id="install-vscode"><summary><b>VS Code (Copilot)</b></summary> ```sh npm i -g context-mode context-mode setup --agents vscode ``` ```sh # update context-mode upgrade # check context-mode doctor --agents vscode # remove context-mode setup --remove --agents vscode ``` Hooks ✓ (hook file) · MCP ✓ · Skills ✓ </details> <details id="install-zcode"><summary><b>ZCode</b></summary> ```sh zcode plugins marketplace add mksglu/context-mode zcode plugins install context-mode@context-mode ``` ```sh # update zcode plugins update context-mode@context-mode # check zcode plugins list # remove zcode plugins uninstall context-mode@context-mode ``` Hooks ✓ (hook file) · MCP ✓ · Skills ✓ </details> The npm route works for every agent: ```sh npm i -g context-mode context-mode setup ``` Setup is also the repair. It shows a plan, saves your earlier config, then applies the plan; when a step ends early, it restores the saved config. To uninstall: ```sh context-mode setup --remove npm rm -g context-mode ``` Restart the agent, then run `/ctx-doctor` in it. Each check prints PASS or a fix command, and the [Doctor guide](https://contextmode.ai/docs/engine/doctor?utm_source=github&utm_medium=readme&utm_content=install-doctor) explains each check. <details><summary><b>How we tested the install</b></summary> Every agent gets hooks, the MCP server and the plugin skills; the last line of each block above says how. Hooks reach each agent in one of three ways: in the plugin package (Claude Code, Gemini CLI, Qwen Code), in a hook file (Codex, Copilot CLI, Kiro, VS Code, ZCode), or in a plugin inside the agent (OpenCode, Pi, OMP). The [Agents guide](https://contextmode.ai/docs/engine/agents?utm_source=github&utm_medium=readme&utm_content=install-agents) shows what each agent runs. We ran the real binary of each agent with the plugin hook: Claude Code, Codex, Gemini CLI, Qwen Code, Pi, OpenCode, Copilot CLI and ZCode. Each run used a clean temp home and a local test model, on 2.0.0-next.15. OMP 18.20.0 ran the same way with ADR-0026, and CI installs the real OMP on Linux, macOS and Windows. For VS Code and Kiro, the check covers the hook setup: VS Code runs the hook command with the documented payload, and kiro-cli 2.35.2 loads all 6 hook entries. CI runs setup, doctor, a hook and an MCP handshake for all 11 agents from the packed package on Linux, macOS and Windows. Record: [HOOKS-FIRE.md](docs/architecture/release/HOOKS-FIRE.md). Each agent uses its own install command, and [ADR-0023](docs/architecture/adr/ADR-0023-native-install.md) says why. </details> Your first task with the plugin, step by step: [First session](https://contextmode.ai/docs/engine/first-session?utm_source=github&utm_medium=readme&utm_content=install-next). Or paste a prompt from [Try it](#try-it) right now. ## Try it Paste one of these prompts into your agent after the install. Each one ran once, live, in Claude Code 2.1.312, and its answer matched the source data ([evidence and rerun steps](bench/evidence/try-it-2026-11-02/README.md)). The headline numbers in [Benchmarks](#benchmarks) use the median of 5 runs. Other agents do the same job with the same tools: `ctx_execute`, `ctx_index` and `ctx_search`. After a prompt, run the stats skill and read the report yourself ([See the saving](#see-the-saving)). ```text On https://react.dev/reference/react/useEffect, show me the example that connects to a chat server and cleans up, and list the rules for the dependency array. ``` The hook sends WebFetch to the sandbox, and the agent searches the page for the example and the rules. 601,984 B raw, 20,860 B reached the context, 96.5% saved (2026-11-02, 2.0.0-next.26, claude-haiku-5-5). ```text Fetch https://jsonplaceholder.typicode.com/photos. Which photo has the longest title (give its id and title), and how many photos have a title that contains the word "est"? ``` The agent runs code over 5,000 JSON records in the sandbox and gets back two answers. 1,039,898 B raw, 393 B reached the context, 99.96% saved (2026-11-02, 2.0.0-next.26, claude-haiku-5-5). The answer is two short facts, so this is the best case of the four. ```text Here is a Linux syslog sample: https://raw.githubusercontent.com/logpai/loghub/master/Linux/Linux_2k.log. How many authentication failures does it contain, and which 3 remote hosts caused the most? ``` The agent counts failures in a 1,999-line syslog in the sandbox. 216,485 B raw, 566 B reached the context, 99.7% saved (2026-11-02, 2.0.0-next.26, claude-haiku-5-5). ```text What are the top 10 stories on the Hacker News front page right now? Give title, points and domain for each. ``` The hook sends WebFetch to the sandbox, and the agent reads ten stories from the page. 35,087 B raw, 1,501 B reached the context, 95.7% saved (2026-11-02, 2.0.0-next.26, claude-haiku-5-5). The front page changes, so the raw size changes with each run. ### See the saving Run the sta
- SKILL.md (2786 bytes)
--- name: release description: Release context-mode v2 from the v2 branch. Runs the checks and the live test, shows the next version and notes, then starts the release workflow and watches it. disable-model-invocation: true --- Release context-mode v2 (ADR-0013). Starting the skill is the approval for this release; the preview in step 6 is for information, not a second approval. Stop and report at the first step that fails; do not retry a failed step with a different method. 1. Check the start state. Run `git branch --show-current` and `git status --porcelain`. The branch must be `v2` and the tree must be clean; if not, stop and report what is dirty. Run `gh auth status` and `git pull --ff-only`. 2. Run the E2E cases: `node e2e/cases/run.mjs`. If a row is `FAIL`, stop and report the failing case ids. 3. Run the v1 KEEP-PASS unit tests (GS4). `npm ci` installs the dev toolchain only (ADR-0013 "Trust boundary"); users never run npm. Then run `npx vitest run`. If one of the 131 tracked tests fails, stop and show its name. 4. Run the live test: `node e2e/live/run.mjs --all` (Sonnet 5, effort low, ADR-0017) and show its table. If a row is `FAIL`, stop. Then update the live-skip streak in `e2e/live/skip-streak.json` (`{ "streak": <n> }`): if the table has one or more `SKIPPED` rows, add 1 to `streak`; if it has none, reset it to 0. If the file changed, commit it on `v2` and push. If `streak` is now `LIVE_SKIP_LIMIT` (3) or more, refuse to continue: report which cases were skipped and the note on each row. 5. v1 migration checkpoint (GS10). The cases `e2e/live/cases/v1-migration-*.json` ran in step 4 (their `covers` paths include `v1-transition`, so `--all` selects them). Do not run them again; confirm each one is `PASS` in the step 4 table, and stop if one is not. 6. Preview. Run `node scripts/release/plan.mjs --dry-run`. Show the owner the next version and the release notes. If it says there is nothing to release, stop. 7. Start the release: `gh workflow run release.yml --ref v2 -f sha=$(git rev-parse HEAD)`. 8. Follow the new run with `gh run watch` and report each job status as it changes. At the end, report in one short table: version, release commit on `release`, GitHub Release URL, live test (passed, or skipped), and the smoke-install result per agent. `skip-live`: if the owner types `/release skip-live`, skip steps 4 and 5 (the streak file does not change) and in step 6 run `node scripts/release/plan.mjs --dry-run --skip-live`, so the release notes carry the line "Live E2E skipped for this release." Say in the final report that the live test was skipped. This skill never runs these one-time steps: switching the marketplace to `ref: "release"`, adding workflows to `main`, and `npm deprecate`. Ask the owner about each one separately. - skills/ctx-doctor/SKILL.md (250 bytes)
--- name: ctx-doctor description: Check that context-mode is installed and working, as a table. disable-model-invocation: true --- Call the ctx_doctor tool and show its table to the user unchanged. If a row failed, list the fixes it names, in order.
- skills/ctx-stats/SKILL.md (322 bytes)
--- name: ctx-stats description: Show how much context context-mode saved, as a detailed report. disable-model-invocation: true --- Call the ctx_stats tool and show the text block of its reply to the user unchanged, inside a code block so the columns stay aligned. Add one sentence under it that names the largest saving.
- skills/ctx-upgrade/SKILL.md (260 bytes)
--- name: ctx-upgrade description: Update context-mode to the latest release. disable-model-invocation: true --- Call the ctx_upgrade tool and show its table to the user. Then call ctx_doctor and show its table. If a restart is needed, say so in one sentence.
- src/adapters/claude-code.ts (15272 bytes)
// impl/10 §2 + shared decode/encode pseudocode; ADR-0001 (Claude Code is the reference contract). // Also exports the Claude-shape decode/encode that codex.ts instantiates with its own fields (impl/10 §3). import type { AgentId } from "../core/contracts/agents.ts"; import type { CanonicalEventName, CanonicalHookEvent, Decision, HookOutput, ToolCall, ToolResultInfo } from "../core/contracts/types.ts"; export const TOOL_NAME_PREFIX = "mcp__plugin_context-mode_context-mode__"; // impl/10 §1.3, TECH-SPEC §3.8 (plugin install) // D-CC-PWSH-1 (#1212): Claude Code 2.1.274 binary: `var Gt="PowerShell"`, input schema {command: "The PowerShell command // to execute", timeout?, description?, run_in_background?, dangerouslyDisableSandbox?}, output {stdout, stderr, interrupted, ...} // (the Bash shapes). Enabled on Windows (CLAUDE_CODE_USE_POWERSHELL_TOOL). It is the same canonical shell as Bash. export const SHELL_TOOL_NAMES: readonly string[] = Object.freeze(["Bash", "PowerShell"]); const POWERSHELL_TOOL = "PowerShell"; const SHELL_CANONICAL = "Bash"; const CLAUDE_SHAPE_EVENTS: readonly CanonicalEventName[] = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse"]; // impl/10 §1.4 const MCP_PREFIX = "mcp__"; const MCP_SEP = "__"; type Source = NonNullable<CanonicalHookEvent["source"]>; const CLAUDE_SOURCES: Readonly<Record<string, Source>> = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" }; // Own tool -> bare ctx_* name; mcp__<server>__<tool> -> "mcp:<server>:<tool>"; native names unchanged (impl/01 §2). function canonicalName(name: string, ownPrefix: string): string { if (name.startsWith(ownPrefix)) return name.slice(ownPrefix.length); if (!name.startsWith(MCP_PREFIX)) return name; const rest = name.slice(MCP_PREFIX.length); const sep = rest.indexOf(MCP_SEP); if (sep < 0) return name; return "mcp:" + rest.slice(0, sep) + ":" + rest.slice(sep + MCP_SEP.length); } // D-M7-RR-1: a Bash tool_response {stdout, stderr, ...} is read as the output the model sees (stdout, then // stderr on its own line), so the replace selects and indexes plain lines, not one escaped JSON string. function outputOf(resp: unknown): string { if (resp === undefined) return ""; if (typeof resp === "string") return resp; if (Array.isArray(resp)) return blocksOf(resp).text; // D-M2-MCP-1 if (typeof resp === "object" && resp !== null) { const r = resp as { stdout?: unknown; stderr?: unknown; content?: unknown; mode?: unknown }; // D-FU-RF-DECODE-1: a Bash shape with only one of stdout/stderr reads the missing one as "". if (typeof r.stdout === "string" || typeof r.stderr === "string") { const out = typeof r.stdout === "string" ? r.stdout : ""; const err = typeof r.stderr === "string" ? r.stderr : ""; return err === "" ? out : out === "" ? err : out + "\n" + err; } } // D-M2-MCP-1, D-CC-SHAPE-1: a native tool object whose text sits in one field: that field is the output the model sees. if (typeof resp === "object" && resp !== null && !Array.isArray(resp)) { const slot = textSlot(resp as Record<string, unknown>); if (slot !== null) return slot.text; } return JSON.stringify(resp); } // D-CC-SHAPE-1 (#1304): Claude Code checks updatedToolOutput against the tool's own output schema and keeps the // original output on a mismatch. Shapes from the Claude Code 2.1.274 binary (outputSchema of each tool): // Read text {type:"text", file:{filePath, content, numLines, startLine, totalLines}}, Grep content {mode:"content", // content, ...}, Grep files and Glob {filenames: string[], numFiles, ...}, WebFetch {result, url, code, ...}. // The replace keeps every other field and swaps only the text field, so the object still parses. type Slot = { text: string; put: (resp: Record<string, unknown>, output: string) => Record<string, unknown> }; function textSlot(r: Record<string, unknown>): Slot | null { const file = r.file; if (r.type === "text" && typeof file === "object" && file !== null && typeof (file as { content?: unknown }).content === "string") { return { text: (file as { content: string }).content, put: (o, output) => ({ ...o, file: readFile(o.file as Record<string, unknown>, output) }) }; } if (isGrepContent(r)) return { text: r.content as string, put: (o, output) => ({ ...o, content: output }) }; if (Array.isArray(r.filenames) && r.filenames.every((f) => typeof f === "string")) { return { text: r.filenames.join("\n"), put: (o, output) => ({ ...o, filenames: output.split("\n") }) }; } if (typeof r.result === "string") return { text: r.result, put: (o, output) => ({ ...o, result: output }) }; return null; } // D-R33-CC-READ-LINES-1 (claude-code-2): Claude Code 2.1.318 numbers each Read line from file.startLine. The replace // keeps the first run of output lines that are real file lines, at their own numbers, then the handle line. A later chunk // after a gap stays in the store (the handle searches it). No real file line kept: the lines start past the lines read, // so no number names a file line it does not show. function readFile(file: Record<string, unknown>, output: string): Record<string, unknown> { const start = typeof file.startLine === "number" ? file.startLine : 1; const lines = String(file.content).split("\n"); const read = typeof file.numLines === "number" ? file.numLines : lines.length; const out = output.split("\n"); const run = firstRun(lines, out); if (run === null) return { ...file, content: output, startLine: start + read, numLines: out.length }; const kept = out.slice(0, run.length); if (run.length < out.length) kept.push(out[out.length - 1]); // the handle line is the last line of a replace return { ...file, content: kept.join("\n"), startLine: start + run.at, numLines: kept.length }; } // The file line index where the longest run of the output's leading lines starts, and the run length; null when the // first output line is no file line. function firstRun(lines: readonly string[], out: readonly string[]): { at: number; length: number } | null { let best: { at: number; length: number } | null = null; for (let i = 0; i < lines.length; i++) { if (lines[i] !== out[0]) continue; let n = 1; while (n < out.length && i + n < lines.length && lines[i + n] === out[n]) n++; if (best === null || n > best.length) best = { at: i, length: n }; if (n === out.length) break; } return best; } function isShellShape(resp: object): boolean { const r = resp as { stdout?: unknown; stderr?: unknown }; return typeof r.stdout === "string" || typeof r.stderr === "string"; } // D-R33-CC-GREP-COUNT-1 (claude-code-3): count mode shows content (per-file counts) too, so content is its text slot. function isGrepContent(resp: object): boolean { const r = resp as { mode?: unknown; content?: unknown }; return (r.mode === "content" || r.mode === "count") && typeof r.content === "string"; } // D-M2-MCP-1: an MCP result is an array of content blocks; the text blocks joined by a newline are the output. // A block of another type (image, resource) is not ours to rewrite: keep marks the result as untouchable. function blocksOf(resp: unknown[]): { text: string; keep: boolean } { const parts: string[] = []; let keep = false; for (const b of resp) { const blk = typeof b === "object" && b !== null ? (b as { type?: unknown; text?: unknown }) : {}; if (blk.type === "text" && typeof blk.text === "string") parts.push(blk.text); else keep = true; } return { text: parts.join("\n"), keep }; } function readResult(resp: unknown): ToolResultInfo { const text = outputOf(resp); const isError = typeof resp === "object" && resp !== null && (resp as { is_error?: unknown }).is_error === true; const info: ToolResultInfo = { isError, bytes: Buffer.byteLength(text), text }; // D-CC-SHAPE-1: an object the replace can rebuild keeps its shape; any other non-Bash object stays as the host made it. if (typeof resp === "object" && resp !== null && !Array.isArray(resp) && isShellShape(resp)) info.shape = resp as Record<string, unknown>; // D-R33-CC-SHELL-1 if (typeof resp === "object" && resp !== null && !Array.isArray(resp) && !isShellShape(resp)) { if (textSlot(resp as Record<string, unknown>) !== null) info.shape = resp as Record<string, unknown>; else info.keep = true; } if (Array.isArray(resp)) { info.blocks = true; if (blocksOf(resp).keep) info.keep = true; } // D-M2-SHAPE-2: above its inline limit Claude Code gives the hook only the head of stdout and keeps the // whole output in persistedOutputPath (persistedOutputSize bytes). The adapter names the file; dispatch reads it. if (typeof resp === "object" && resp !== null) { const r = resp as { persistedOutputPath?: unknown; persistedOutputSize?: unknown }; if (typeof r.persistedOutputPath === "string" && r.persistedOutputPath !== "" && typeof r.persistedOutputSize === "number" && r.persistedOutputSize > info.bytes) { info.persistedPath = r.persistedOutputPath; } } return info; } export function decodeClaudeShape(raw: unknown, agent: AgentId, ownPrefix: string, sources: Readonly<Record<string, Source>>): CanonicalHookEvent { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error(agent + ": hook payload is not a JSON object"); const p = raw as Record<string, unknown>; const event = CLAUDE_SHAPE_EVENTS.find((e) => e === p.hook_event_name); if (event === undefined) throw new Error(agent + ": unknown hook event " + String(p.hook_event_name)); const ev: CanonicalHookEvent = { event, agent, sessionId: String(p.session_id ?? ""), cwd: String(p.cwd ?? "") }; if (typeof p.agent_id === "string") { ev.agentId = p.agent_id; if (typeof p.agent_type === "string") ev.agentType = p.agent_type; } if (event === "SessionStart" && typeof p.source === "string" && sources[p.source] !== undefined) ev.source = sources[p.source]; if (event === "UserPromptSubmit" && typeof p.prompt === "string") ev.prompt = p.prompt; if (event === "PreToolUse" || event === "PostToolUse") { const name = String(p.tool_name ?? ""); const input = typeof p.tool_input === "object" && p.tool_input !== null ? (p.tool_input as Record<string, unknown>) : {}; const tool: ToolCall = { name, canonicalName: canonicalName(name, ownPrefix), input }; if (typeof p.tool_use_id === "string" && p.tool_use_id !== "") tool.callId = p.tool_use_id; ev.tool = tool; } if (event === "PostToolUse") ev.result = readResult(p.tool_response); return ev; } // Deny exits 0: the reason travels in the JSON deny field, and Claude-shape hosts ignore stdout JSON on // exit 2 (only stderr is read there; HookOutput has no stderr). DEVIATIONS D-M0-T8-1. // D-M7-SV-1: Claude Code checks updatedToolOutput against the tool's own output schema and keeps the // original output on a mismatch ("does not match Bash's output shape; using original output"). Bash // output is an object {stdout, stderr, interrupted}, so a bare string never reached the model. // D-R33-CC-SHELL-1 (claude-code-1): the shell replace is the host's own object with stdout and stderr swapped, so // interrupted, returnCodeInterpretation and the rest reach the model as the host made them. The persisted-output fields go: // the replace stands for the whole output, and its pointer names the file (D-CC-POINTER-6, PERSISTED_FILE_LINE). function replaceShape(ev: CanonicalHookEvent, output: string): unknown { const shape = ev.result?.shape; if (ev.tool?.canonicalName === "Bash") { const { persistedOutputPath: _p, persistedOutputSize: _s, ...host } = shape ?? {}; return { interrupted: false, ...host, stdout: output, stderr: "" }; } const slot = shape === undefined ? null : textSlot(shape); if (shape !== undefined && slot !== null) return slot.put(shape, output); // D-CC-SHAPE-1: the tool's own object if (ev.result?.blocks === true) return [{ type: "text", text: output }]; // D-M2-MCP-1: the MCP result shape return output; } export function encodeClaudeShape(ev: CanonicalHookEvent, d: Decision, hasReplace: boolean): HookOutput { const out = (fields: Record<string, unknown>): HookOutput => ({ stdout: JSON.stringify({ hookSpecificOutput: { hookEventName: ev.event, ...fields } }), exitCode: 0, }); switch (d.kind) { case "allow": return { stdout: "", exitCode: 0 }; case "hint": return out({ additionalContext: d.text }); case "deny": return out({ permissionDecision: "deny", permissionDecisionReason: d.rewritten === undefined ? d.reason : d.rewritten + "\n" + d.reason }); case "replace": return hasReplace && ev.event === "PostToolUse" ? out({ updatedToolOutput: replaceShape(ev, d.output) }) : { stdout: "", exitCode: 0 }; } } // D-FU-RF-DECODE-1: fields the decode cannot run without. The hooks docs list them as always present; // a payload without one fails decode with a line naming the field (handleHook writes it to stderr and // answers with the empty allow shape), never a silent empty answer. Every other field has a default. const REQUIRED_FIELDS: Readonly<Partial<Record<CanonicalEventName, readonly string[]>>> = { PreToolUse: ["tool_name"], PostToolUse: ["tool_name", "tool_response"], }; // FNV-1a 32-bit, hex: a short stable id from a string. Not for security; the hook path stays free of // node:crypto (D-M7-HP-2). function fnv1a(s: string): string { let h = 0x811c9dc5; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 0x01000193); } return (h >>> 0).toString(16).padStart(8, "0"); } function requireFields(raw: unknown): void { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return; // decodeClaudeShape throws const p = raw as Record<string, unknown>; if (p.hook_event_name === undefined) throw new Error("claude-code: missing required field hook_event_name"); for (const f of REQUIRED_FIELDS[p.hook_event_name as CanonicalEventName] ?? []) { if (p[f] === undefined) throw new Error("claude-code: missing required field " + f); } } export function decode(raw: unknown): CanonicalHookEvent { requireFields(raw); const ev = decodeClaudeShape(raw, "claude-code", TOOL_NAME_PREFIX, CLAUDE_SOURCES); // D-CC-PWSH-1: PowerShell keeps its native name and is decided, replaced and encoded as canonical Bash. if (ev.tool !== undefined && ev.tool.name === POWERSHELL_TOOL) ev.tool.canonicalName = SHELL_CANONICAL; // D-FU-RF-DECODE-1 defaults. cwd: the project dir Claude Code sets for its hooks, else the hook's own cwd. if (ev.cwd === "") ev.cwd = process.env.CLAUDE_PROJECT_DIR || process.cwd(); // tool_use_id: a label from a hash of the command and the turn, so one command in one turn keeps one source. if (ev.event === "PostToolUse" && ev.tool !== undefined && ev.tool.callId === undefined) { const cmd = typeof ev.tool.input.command === "string" ? ev.tool.input.command : JSON.strin - src/adapters/codex.ts (1821 bytes)
// impl/10 §3: Codex CLI 0.156.1 uses the Claude hook shape (plus turn_id, model). // Own prefix is underscore (DECISIONS-r9 R1); source "fork" -> "resume" (impl/10 A4); no replace field. import type { CanonicalHookEvent, Decision, HookOutput } from "../core/contracts/types.ts"; import { decodeClaudeShape, encodeClaudeShape } from "./claude-code.ts"; export const TOOL_NAME_PREFIX = "mcp__context_mode__"; // impl/10 §1.3, DECISIONS-r9 R1 type Source = NonNullable<CanonicalHookEvent["source"]>; const CODEX_SOURCES: Readonly<Record<string, Source>> = { startup: "startup", resume: "resume", clear: "clear", compact: "compact", fork: "resume" }; // D-1323-CODEX-STOP-1 (#1323): Codex runs a Stop handler at each turn end (rust-v0.166.0 stop.command.input: cwd, session_id, // stop_hook_active, turn_id, ...). An older install left a context-mode Stop entry, so the event reaches this hook. It decodes // as Stop and gets the empty reply: Codex then ends the turn as usual. context-mode has no Stop work of its own. const STOP_EVENT = "Stop"; const EMPTY: HookOutput = { stdout: "", exitCode: 0 }; export function decode(raw: unknown): CanonicalHookEvent { if (typeof raw === "object" && raw !== null && !Array.isArray(raw) && (raw as Record<string, unknown>).hook_event_name === STOP_EVENT) { const p = raw as Record<string, unknown>; return { event: STOP_EVENT, agent: "codex", sessionId: String(p.session_id ?? ""), cwd: String(p.cwd ?? "") }; } return decodeClaudeShape(raw, "codex", TOOL_NAME_PREFIX, CODEX_SOURCES); } export function encode(ev: CanonicalHookEvent, d: Decision, _extra?: string): HookOutput { if (ev.event === STOP_EVENT) return EMPTY; // D-1323-CODEX-STOP-1: Codex's Stop reply {continue, decision, ...} has no hookSpecificOutput return encodeClaudeShape(ev, d, false); } - src/adapters/copilot-cli.ts (8548 bytes)
// impl/10 §6 + shared decode/encode pseudocode; spike-hooks-verified §2 (Copilot CLI 1.0.96). // Dual-cased payload: camelCase event names carry camelCase keys (hookEventName, sessionId, toolName, // toolArgs, toolResult); PascalCase event names carry snake_case keys (hook_event_name, session_id, // tool_name, tool_input, tool_result). Subagent fields [U] (S-NAMES): never set. // Deny is plain deny-with-reason, never modifiedArgs (ADR-0008 per-adapter table: unverified). // Decisions not fixed by the docs: DEVIATIONS D-M3-A3-1..4. import type { CanonicalEventName, CanonicalHookEvent, Decision, HookOutput, ToolCall, ToolResultInfo } from "../core/contracts/types.ts"; // Copilot CLI 1.0.103 names MCP tools <server>-<tool> ("github-mcp-server-search_code", // "playwright-browser_take_screenshot" in the shipped bundle); server key "context-mode" (D-HQ-COPILOT-NAMES-2). export const TOOL_NAME_PREFIX = "context-mode-"; type Source = NonNullable<CanonicalHookEvent["source"]>; type Casing = "camel" | "snake"; interface NativeEvent { event: CanonicalEventName; casing: Casing; failure: boolean } // impl/10 §1.4 + §6 event row: both casings, plus the PostToolUse failure variant. const NATIVE_EVENTS: Readonly<Record<string, NativeEvent>> = { sessionStart: { event: "SessionStart", casing: "camel", failure: false }, userPromptSubmitted: { event: "UserPromptSubmit", casing: "camel", failure: false }, preToolUse: { event: "PreToolUse", casing: "camel", failure: false }, postToolUse: { event: "PostToolUse", casing: "camel", failure: false }, postToolUseFailure: { event: "PostToolUse", casing: "camel", failure: true }, SessionStart: { event: "SessionStart", casing: "snake", failure: false }, UserPromptSubmit: { event: "UserPromptSubmit", casing: "snake", failure: false }, PreToolUse: { event: "PreToolUse", casing: "snake", failure: false }, PostToolUse: { event: "PostToolUse", casing: "snake", failure: false }, PostToolUseFailure: { event: "PostToolUse", casing: "snake", failure: true }, }; // impl/10 §6: enum startup/resume/new; "new" is a first start (D-M3-A3-2). No compact re-fire. const COPILOT_SOURCES: Readonly<Record<string, Source>> = { startup: "startup", resume: "resume", new: "startup" }; const KEYS: Readonly<Record<Casing, { event: string; session: string; tool: string; args: string; result: string }>> = { camel: { event: "hookEventName", session: "sessionId", tool: "toolName", args: "toolArgs", result: "toolResult" }, snake: { event: "hook_event_name", session: "session_id", tool: "tool_name", args: "tool_input", result: "tool_result" }, }; const RESULT_SUCCESS = "success"; function isRecord(v: unknown): v is Record<string, unknown> { return typeof v === "object" && v !== null && !Array.isArray(v); } // copilot-cli 1.0.103 native shell tool id -> canonical name (D-HA-COPILOT-NAMES-1, SDK docs toolName "bash"). // D-PWSH-DUMP-1: the Windows shell tool is "powershell" (same as vscode.ts SHELL_TOOL_NAMES); it is the same canonical shell. export const SHELL_TOOL_NAMES: readonly string[] = Object.freeze(["bash", "powershell"]); const NATIVE_TO_CANONICAL: Readonly<Record<string, string>> = Object.fromEntries(SHELL_TOOL_NAMES.map((n) => [n, "Bash"])); // Own tool -> bare ctx_* name; native names mapped; any other name unchanged. Another server's // <server>-<tool> name cannot be split (both parts may hold "-"), so it stays whole (D-HQ-COPILOT-NAMES-2). function canonicalName(name: string): string { if (name.startsWith(TOOL_NAME_PREFIX)) return name.slice(TOOL_NAME_PREFIX.length); if (Object.hasOwn(NATIVE_TO_CANONICAL, name)) return NATIVE_TO_CANONICAL[name]; return name; } // D-R41-READ-OFFSET-1 (#1314): copilot-cli `view` {path, view_range [start, end]} gets the Claude range keys offset/limit, // as vscode.ts policyInput does. Source keys are kept; the canonical name stays "view" (D-HQ-COPILOT-NAMES-2). const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v); function viewRange(name: string, input: Record<string, unknown>): Record<string, unknown> { const r = input.view_range; if (name !== "view" || !Array.isArray(r) || !isNum(r[0])) return input; const out: Record<string, unknown> = { ...input, offset: r[0] }; if (isNum(r[1]) && r[1] >= r[0]) out.limit = r[1] - r[0] + 1; return out; } // toolArgs arrives as an object or as a JSON-encoded string (D-M3-A3-3); anything else is {}. function readArgs(v: unknown): Record<string, unknown> { if (isRecord(v)) return v; if (typeof v !== "string") return {}; try { const parsed: unknown = JSON.parse(v); return isRecord(parsed) ? parsed : {}; } catch { return {}; } } // One result shape per casing (D-HA-COPILOT-REPLACE-1): camel toolResult {resultType, textResultForLlm}, // snake tool_result {result_type, text_result_for_llm}. const RESULT_KEYS: Readonly<Record<Casing, { type: string; text: string }>> = { camel: { type: "resultType", text: "textResultForLlm" }, snake: { type: "result_type", text: "text_result_for_llm" }, }; function readResult(v: unknown, casing: Casing, failure: boolean): ToolResultInfo { const k = RESULT_KEYS[casing]; const r = isRecord(v) ? v : {}; const text = typeof r[k.text] === "string" ? (r[k.text] as string) : ""; const isError = failure || (typeof r[k.type] === "string" && r[k.type] !== RESULT_SUCCESS); return { isError, bytes: Buffer.byteLength(text), text }; } // D-HQ-COPILOT-EVENT-1: the documented camelCase payload (docs.github.com/en/copilot/reference/hooks-configuration) // names no event. Each event has its own key set: toolResult = postToolUse, toolName = preToolUse, // prompt = userPromptSubmitted, source = sessionStart. A payload that names its event keeps that name. const EVENT_BY_KEY: readonly (readonly [string, string])[] = [ ["toolResult", "postToolUse"], ["toolName", "preToolUse"], ["prompt", "userPromptSubmitted"], ["source", "sessionStart"], ]; function eventName(raw: Record<string, unknown>): unknown { if (typeof raw.hookEventName === "string") return raw.hookEventName; if (raw.hook_event_name !== undefined) return raw.hook_event_name; return EVENT_BY_KEY.find(([key]) => Object.hasOwn(raw, key))?.[1]; } export function decode(raw: unknown): CanonicalHookEvent { if (!isRecord(raw)) throw new Error("copilot-cli: hook payload is not a JSON object"); const name = eventName(raw); const native = typeof name === "string" ? NATIVE_EVENTS[name] : undefined; if (native === undefined) throw new Error("copilot-cli: unknown hook event " + String(name)); const k = KEYS[native.casing]; const event = native.event; const ev: CanonicalHookEvent = { event, agent: "copilot-cli", sessionId: String(raw[k.session] ?? ""), cwd: String(raw.cwd ?? "") }; if (event === "SessionStart" && typeof raw.source === "string" && COPILOT_SOURCES[raw.source] !== undefined) ev.source = COPILOT_SOURCES[raw.source]; if (event === "UserPromptSubmit" && typeof raw.prompt === "string") ev.prompt = raw.prompt; if (event === "PreToolUse" || event === "PostToolUse") { const toolName = String(raw[k.tool] ?? ""); const tool: ToolCall = { name: toolName, canonicalName: canonicalName(toolName), input: viewRange(toolName, readArgs(raw[k.args])) }; ev.tool = tool; } if (event === "PostToolUse") ev.result = readResult(raw[k.result], native.casing, native.failure); return ev; } const EMPTY: HookOutput = { stdout: "", exitCode: 0 }; // Deny exits 0 with the JSON deny field (DEVIATIONS D-M0-T8-1, same rule as the Claude shape). // hint on PostToolUse and deny off PreToolUse have no native field: silent no-op (D-M3-A3-4). export function encode(ev: CanonicalHookEvent, d: Decision, _extra?: string): HookOutput { switch (d.kind) { case "allow": return EMPTY; case "hint": return ev.event === "PostToolUse" ? EMPTY : { stdout: JSON.stringify({ additionalContext: d.text }), exitCode: 0 }; case "deny": if (ev.event !== "PreToolUse") return EMPTY; return { stdout: JSON.stringify({ permissionDecision: "deny", permissionDecisionReason: d.rewritten === undefined ? d.reason : d.rewritten + "\n" + d.reason }), exitCode: 0, }; case "replace": // D-HA-COPILOT-REPLACE-1: postToolUse output modifiedResult replaces the tool result (copilot SDK types.d.ts). if (ev.event !== "PostToolUse") return EMPTY; return { stdout: JSON.stringify({ modifiedResult: { resultType: RESULT_SUCCESS, textResultForLlm: d.output } }), exitCode: 0 }; } } - src/adapters/gemini.ts (9920 bytes)
// impl/10 §4 + shared decode/encode pseudocode. Gemini CLI (gemini-cli@51617c1, spike-hooks-verified.md Gemini row). // Native events: SessionStart (decoded, but no hook entry since D-FU-GCH-1) / BeforeAgent / BeforeTool / AfterTool, plus PreCompress -> aux PreCompact (impl/10 §1.4). // Own prefix mcp_context-mode_ (single underscore, TECH-SPEC §3.8). No subagent field, no BeforeTool hint field, // replace is AfterTool decision deny + reason (D-HA-GEMINI-REPLACE-1). Deny is the JSON `decision` field on exit 0 (DEVIATIONS D-M3-A1-1). import type { CanonicalHookEvent, Decision, HookOutput, ToolResultInfo } from "../core/contracts/types.ts"; export const TOOL_NAME_PREFIX = "mcp_context-mode_"; // impl/10 §1.3, TECH-SPEC §3.8 Gemini row type Event = CanonicalHookEvent["event"]; type Source = NonNullable<CanonicalHookEvent["source"]>; // Reverse of the table.ts gemini eventMap row (impl/10 §1.4). const GEMINI_EVENTS: Readonly<Record<string, Event>> = { SessionStart: "SessionStart", BeforeAgent: "UserPromptSubmit", BeforeTool: "PreToolUse", AfterTool: "PostToolUse", PreCompress: "PreCompact", }; // Gemini SessionStartSource is startup|resume|clear only; compact never arrives (impl/10 §4 gap row). const GEMINI_SOURCES: Readonly<Record<string, Source>> = { startup: "startup", resume: "resume", clear: "clear" }; // Events whose native output reads hookSpecificOutput.additionalContext (spike matrix; BeforeTool has none). const HINT_EVENTS: readonly Event[] = ["SessionStart", "UserPromptSubmit", "PostToolUse"]; // Events whose native output reads decision deny/block (spike matrix: BeforeAgent, BeforeTool). const DENY_EVENTS: readonly Event[] = ["UserPromptSubmit", "PreToolUse"]; const EMPTY: HookOutput = { stdout: "", exitCode: 0 }; // D-R38-GEMINI-REPLACE-OK-1: first line of an AfterTool replace reason; the host shows it after "Tool result blocked: ". export const GEMINI_REPLACE_LEAD = "the tool ran and succeeded; context-mode indexed its full output, and this is the part that answers the call:\n"; function own(p: Record<string, unknown>, key: string): unknown { return Object.hasOwn(p, key) ? p[key] : undefined; } // Own tool -> bare ctx_* name; another MCP server's tool -> "mcp:<server>:<tool>" read from the payload's // mcp_context {server_name, tool_name}, never split out of the sanitized name (DEVIATIONS D-M3-A1-2); // the four native ids in NATIVE_TO_CANONICAL map to canonical names; other native names unchanged (impl/01 §2). // gemini-cli 0.65.0 SHELL/READ_FILE/GREP/WEB_FETCH_TOOL_NAME -> canonical name (D-HA-GEMINI-NAMES-1). const NATIVE_TO_CANONICAL: Readonly<Record<string, string>> = { run_shell_command: "Bash", read_file: "Read", grep_search: "Grep", web_fetch: "WebFetch", }; function canonicalName(name: string, mcp: unknown): string { if (name.startsWith(TOOL_NAME_PREFIX)) return name.slice(TOOL_NAME_PREFIX.length); if (Object.hasOwn(NATIVE_TO_CANONICAL, name)) return NATIVE_TO_CANONICAL[name]; if (typeof mcp !== "object" || mcp === null) return name; const m = mcp as Record<string, unknown>; const server = own(m, "server_name"); const tool = own(m, "tool_name"); if (typeof server !== "string" || typeof tool !== "string") return name; return "mcp:" + server + ":" + tool; } // D-R38-GEMINI-PARTS-1 (host audit gemini-6): read_many_files and MCP tools give llmContent as a Part list. When every // Part is a text Part, the joined text is what the model sees, so it is the result text (head lines and a real query). function partsText(llm: unknown): string | undefined { if (!Array.isArray(llm) || llm.length === 0) return undefined; const out: string[] = []; for (const part of llm) { if (typeof part === "string") { out.push(part); continue; } if (typeof part !== "object" || part === null) return undefined; const t = own(part as Record<string, unknown>, "text"); if (typeof t !== "string") return undefined; out.push(t); } return out.join(""); } // tool_response is Gemini's {llmContent, returnDisplay, error?}; a non-null `error` marks failure (DEVIATIONS D-M3-A1-3). // D-HA-GEMINI-REPLACE-1: a string llmContent is the text the model sees, so it is the result text a replace selects // from; a text-only Part list is joined (D-R38-GEMINI-PARTS-1); any other shape stays the JSON text, as before. function readResult(resp: unknown): ToolResultInfo { const obj = typeof resp === "object" && resp !== null ? (resp as Record<string, unknown>) : undefined; const llm = obj === undefined ? undefined : own(obj, "llmContent"); const text = resp === undefined ? "" : typeof resp === "string" ? resp : typeof llm === "string" ? llm : partsText(llm) ?? JSON.stringify(resp); const err = obj === undefined ? undefined : own(obj, "error"); const info: ToolResultInfo = { isError: err !== undefined && err !== null, bytes: Buffer.byteLength(text), text }; // D-R47-READ-MEDIA-1 (#1321): an image/PDF read_file is llmContent {inlineData} (gemini-cli fileUtils.ts); a Part that is // not text is a block the model sees as media, so the result stays as the host made it (as D-M2-MCP-1 keep). if (hasMediaPart(llm)) info.keep = true; return info; } function hasMediaPart(llm: unknown): boolean { const parts = Array.isArray(llm) ? llm : [llm]; return parts.some((p) => typeof p === "object" && p !== null && (Object.hasOwn(p, "inlineData") || Object.hasOwn(p, "fileData"))); } // D-R38-GEMINI-URL-1 (host audit gemini-5): web_fetch takes only `prompt`, with the URLs inside the free text. // The first http(s) word of the prompt is the url the WebFetch policy and the intent read. const URL_STARTS = ["https://", "http://"]; const URL_TRAIL = ".,;:!?)]}>'\""; const SPACE = " \t\n\r\f\v"; function words(text: string): string[] { const out: string[] = []; let cur = ""; for (const ch of text) { if (SPACE.includes(ch)) { if (cur !== "") out.push(cur); cur = ""; } else cur += ch; } if (cur !== "") out.push(cur); return out; } function firstUrl(prompt: unknown): string | undefined { if (typeof prompt !== "string") return undefined; for (const word of words(prompt)) { const lower = word.toLowerCase(); const at = URL_STARTS.map((s) => lower.indexOf(s)).filter((i) => i >= 0).sort((a, b) => a - b)[0]; if (at === undefined) continue; let url = word.slice(at); while (url.length > 0 && URL_TRAIL.includes(url[url.length - 1])) url = url.slice(0, -1); return url; } return undefined; } // D-R38-GEMINI-PARTS-1: read_many_files names its files in `include` (string list); they are the replace query. function nativeInput(name: string, input: Record<string, unknown>): Record<string, unknown> { if (name === "web_fetch" && own(input, "url") === undefined) { const url = firstUrl(own(input, "prompt")); return url === undefined ? input : { ...input, url }; } if (name === "read_many_files" && own(input, "file_path") === undefined) { const inc = own(input, "include"); const list = Array.isArray(inc) ? inc.filter((v): v is string => typeof v === "string") : []; return list.length === 0 ? input : { ...input, file_path: list.join(" ") }; } return input; } export function decode(raw: unknown): CanonicalHookEvent { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("gemini: hook payload is not a JSON object"); const p = raw as Record<string, unknown>; const native = own(p, "hook_event_name"); const event = typeof native === "string" && Object.hasOwn(GEMINI_EVENTS, native) ? GEMINI_EVENTS[native] : undefined; if (event === undefined) throw new Error("gemini: unknown hook event " + String(native)); const ev: CanonicalHookEvent = { event, agent: "gemini", sessionId: String(own(p, "session_id") ?? ""), cwd: String(own(p, "cwd") ?? "") }; const source = own(p, "source"); if (event === "SessionStart" && typeof source === "string" && Object.hasOwn(GEMINI_SOURCES, source)) ev.source = GEMINI_SOURCES[source]; const prompt = own(p, "prompt"); if (event === "UserPromptSubmit" && typeof prompt === "string") ev.prompt = prompt; if (event === "PreToolUse" || event === "PostToolUse") { const name = String(own(p, "tool_name") ?? ""); const input = own(p, "tool_input"); ev.tool = { name, canonicalName: canonicalName(name, own(p, "mcp_context")), input: nativeInput(name, typeof input === "object" && input !== null && !Array.isArray(input) ? (input as Record<string, unknown>) : {}), }; } if (event === "PostToolUse") ev.result = readResult(own(p, "tool_response")); return ev; } export function encode(ev: CanonicalHookEvent, d: Decision, _extra?: string): HookOutput { switch (d.kind) { case "allow": return EMPTY; case "hint": // BeforeTool has no hint field: dropped (impl/10 shared encode step 1); PreCompress is advisory. if (!HINT_EVENTS.includes(ev.event)) return EMPTY; return { stdout: JSON.stringify({ hookSpecificOutput: { additionalContext: d.text } }), exitCode: 0 }; case "deny": if (!DENY_EVENTS.includes(ev.event)) return EMPTY; return { stdout: JSON.stringify({ decision: "deny", reason: d.rewritten === undefined ? d.reason : d.rewritten + "\n" + d.reason }), exitCode: 0 }; case "replace": // gemini-cli 0.65.0 docs/hooks/reference.md AfterTool: decision "deny" + reason, the reason replaces the tool // result sent to the model (D-HA-GEMINI-REPLACE-1). The host code wraps it as "Tool result blocked: <reason>" // with error execution_failed, and it has no other replace channel, so the reason starts with a line that tells // the model the tool ran and succeeded (D-R38-GEMINI-REPLACE-OK-1, host audit gemini-4). if (ev.event !== "PostToolUse") return EMPTY; return { stdout: JSON.stringify({ decision: "deny", reason: GEMINI_REPLACE_LEAD + d.output }), exitCode: 0 }; } } - src/adapters/kiro.ts (6302 bytes)
// impl/10 §8 + shared decode/encode pseudocode; impl/09 §5.2 item 6 + A28; DECISIONS-r3 Q24. // Kiro CLI V3 hooks are plain text only (https://github.com/mksglu/context-mode/blob/274600e2ffab843e89c1dfa09b0d649e650c962f/tickets/spike-hooks-verified.md §2): exit 0 stdout goes to context, // any non-zero exit blocks. denyChannel "hint-only" (impl/10 A3): no structured hint, deny or replace field. import type { CanonicalEventName, CanonicalHookEvent, Decision, HookOutput, ToolResultInfo } from "../core/contracts/types.ts"; // D-R33-KIRO-NAMES-1: Kiro CLI 3.0 lists an MCP tool as "mcp_" + lowercase("<server>_<tool>") with every space and "-" turned // into "_" (V3 engine bundle, function uel), so context-mode's tools are mcp_context_mode_ctx_*. The 2.x spelling // mcp_context-mode_ stays a decode alias for hook payloads from older builds. export const TOOL_NAME_PREFIX = "mcp_context_mode_"; const LEGACY_TOOL_NAME_PREFIX = "mcp_context-mode_"; // Native event name -> canonical; legacy names are aliases (impl/10 §8 event-name row, §1.4). // UserPromptSubmit is the trigger the build writes (D-FU-RM-KIRO-1) and the hook_event_name in the Kiro docs' // prompt hook payload (D-FU-RM-KIRO-2); PromptSubmit stays for hook files written by older builds. const KIRO_EVENTS: Readonly<Record<string, CanonicalEventName>> = { SessionStart: "SessionStart", agentSpawn: "SessionStart", UserPromptSubmit: "UserPromptSubmit", PromptSubmit: "UserPromptSubmit", userPromptSubmit: "UserPromptSubmit", PreToolUse: "PreToolUse", preToolUse: "PreToolUse", PostToolUse: "PostToolUse", postToolUse: "PostToolUse", }; // D-R33-KIRO-PROMPT-1: Kiro CLI 3.0 sends the prompt on stdin as "prompt" (V3 engine bundle, function sJn) and sets no // USER_PROMPT; the env var stays the fallback for Kiro CLI 2.x (impl/10 §8). const PROMPT_FIELD = "prompt"; const PROMPT_ENV = "USER_PROMPT"; const MCP_PREFIX = "mcp_"; // D-N7-KIRO-1. Event names: kiro.dev/docs/cli/v3/hooks-migration (2026-10-10), 2.x camelCase -> V3 PascalCase. // Shell tool: the registered matcher "shell" is a category tag; kiro.dev/docs/custom-agents/configuration-reference (2026-10-10) // lists the built-in ids execute_bash and execute_pwsh, and Kiro CLI 2.34.2 names the tool "shell" (execute_bash is its legacy alias). export const SHELL_TOOL_NAMES: readonly string[] = Object.freeze(["execute_bash", "execute_pwsh", "shell"]); const NATIVE_TO_CANONICAL: Readonly<Record<string, string>> = Object.fromEntries(SHELL_TOOL_NAMES.map((n) => [n, "Bash"])); const MCP_SEP = "_"; type Source = NonNullable<CanonicalHookEvent["source"]>; const KIRO_SOURCES: Readonly<Record<string, Source>> = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" }; // Own tool -> bare ctx_*; mcp_<server>_<tool> -> "mcp:<server>:<tool>", split at the first "_" after "mcp_" // (same rule as the VS Code family, DEVIATIONS D-M3-A4-3 / D-M3-A5-2); native names unchanged. function canonicalName(name: string): string { if (name.startsWith(TOOL_NAME_PREFIX)) return name.slice(TOOL_NAME_PREFIX.length); if (name.startsWith(LEGACY_TOOL_NAME_PREFIX)) return name.slice(LEGACY_TOOL_NAME_PREFIX.length); if (Object.hasOwn(NATIVE_TO_CANONICAL, name)) return NATIVE_TO_CANONICAL[name]; if (!name.startsWith(MCP_PREFIX)) return name; const rest = name.slice(MCP_PREFIX.length); const sep = rest.indexOf(MCP_SEP); if (sep <= 0 || sep === rest.length - 1) return name; return "mcp:" + rest.slice(0, sep) + ":" + rest.slice(sep + MCP_SEP.length); } // Kiro documents no error field on PostToolUse; isError stays false, never guessed (impl/10 §8 result row). function readResult(resp: unknown): ToolResultInfo { const text = resp === undefined ? "" : typeof resp === "string" ? resp : JSON.stringify(resp); return { isError: false, bytes: Buffer.byteLength(text), text }; } export function decode(raw: unknown): CanonicalHookEvent { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("kiro: hook payload is not a JSON object"); const p = raw as Record<string, unknown>; const native = typeof p.hook_event_name === "string" ? p.hook_event_name : ""; const event = Object.prototype.hasOwnProperty.call(KIRO_EVENTS, native) ? KIRO_EVENTS[native] : undefined; if (event === undefined) throw new Error("kiro: unknown hook event " + String(p.hook_event_name)); // No subagent field on Kiro (Q24 item 7): agentId/agentType stay undefined. const ev: CanonicalHookEvent = { event, agent: "kiro", sessionId: String(p.session_id ?? ""), cwd: String(p.cwd ?? "") }; if (event === "SessionStart" && typeof p.source === "string" && KIRO_SOURCES[p.source] !== undefined) ev.source = KIRO_SOURCES[p.source]; if (event === "UserPromptSubmit") { const field = p[PROMPT_FIELD]; const prompt = typeof field === "string" ? field : process.env[PROMPT_ENV]; if (prompt !== undefined) ev.prompt = prompt; } if (event === "PreToolUse" || event === "PostToolUse") { const name = String(p.tool_name ?? ""); const input = typeof p.tool_input === "object" && p.tool_input !== null && !Array.isArray(p.tool_input) ? (p.tool_input as Record<string, unknown>) : {}; ev.tool = { name, canonicalName: canonicalName(name), input }; } if (event === "PostToolUse") ev.result = readResult(p.tool_response); return ev; } // UserPromptSubmit: hint -> plain stdout, exit 0 (D-R33-KIRO-RECALL-1: Kiro CLI 3.0 uJn/cJn sends it to the model); // every other decision -> stdout "" exit 0 (A28). // hint -> plain text stdout, exit 0. deny -> plain text reason (rewrite first) on stderr, exit 2: Kiro blocks the // tool and returns STDERR to the agent (Kiro CLI 2.x reference; D-HF-KIRO-SHELL-1, was D-M3-A5-1). replace -> no-op. export function encode(ev: CanonicalHookEvent, d: Decision, _extra?: string): HookOutput { if (ev.event === "UserPromptSubmit") return { stdout: d.kind === "hint" ? d.text : "", exitCode: 0 }; switch (d.kind) { case "allow": return { stdout: "", exitCode: 0 }; case "hint": return { stdout: d.text, exitCode: 0 }; case "deny": return { stdout: "", stderr: d.rewritten === undefined ? d.reason : d.rewritten + "\n" + d.reason, exitCode: 2 }; case "replace": return { stdout: "", exitCode: 0 }; } } - src/adapters/opencode.ts (5665 bytes)
// impl/10 §11; DEVIATIONS D-M5-arch-2, D-M5-A1-1. OpenCode 2 is in-process (ADR-0001 §3): the plugin entry calls // handleHook with a raw object whose `type` is the hook call-site name, plus the hook argument fields. // decode/encode exist so handleHook stays one code path for every agent (ADR-0001 Decision 3). import { SERVER_KEY } from "../core/contracts/constants.ts"; import type { AuxEventName, CanonicalEventName, CanonicalHookEvent, Decision, HookOutput, ToolResultInfo } from "../core/contracts/types.ts"; export const TOOL_NAME_PREFIX = ""; // impl/10 §1.3 // Wire prefix OpenCode puts on this server's tools: `context-mode_ctx_execute` (TECH-SPEC §3.8, impl/12 §4.4 step 1). const OWN_WIRE_PREFIX = SERVER_KEY + "_"; // Call-site name -> canonical event (impl/10 §1.4; Usage = step-finish cost row, D-M5-arch-2). const OPENCODE_EVENTS: Readonly<Record<string, CanonicalEventName | AuxEventName>> = { context: "SessionStart", prompt: "UserPromptSubmit", "execute.before": "PreToolUse", "execute.after": "PostToolUse", compaction: "PreCompact", "step-finish": "Usage", }; // OpenCode native tool name -> canonical name decide() knows (#1052). Names not listed stay as received. // D-HF-OPENCODE-SHELL-1: OpenCode's built-in shell tool is `bash` with `args.command` (opencode.ai/docs/tools, opencode-ai 1.19.4). // D-OC2-SETUP-1: OpenCode 2.2.5 names the same tool `shell` (args.command); 1.19 and KiloCode keep `bash`. export const SHELL_TOOL_NAME = "bash"; export const READ_TOOL_NAME = "read"; // D-R44-OC-READ-1: OpenCode's own read tool (input filePath, or filePaths on 2.x) export const SHELL_TOOL_NAMES: readonly string[] = Object.freeze([SHELL_TOOL_NAME, "shell"]); // both map to canonical Bash; the table row keeps "bash" (nativeTools is the 1.19 name) // D-1404-SKILL-LOAD-1 (#1404): OpenCode's skill tool (`skill`, args.name; output <skill_content name=...>, 1.19.5 binary) // is the canonical Skill, as on Claude Code. export const SKILL_TOOL_NAME = "skill"; const NATIVE_TO_CANONICAL: Readonly<Record<string, string>> = { webfetch: "WebFetch", [READ_TOOL_NAME]: "Read", [SKILL_TOOL_NAME]: "Skill", ...Object.fromEntries(SHELL_TOOL_NAMES.map((n) => [n, "Bash"])) }; export function toCanonicalTool(name: string): string { if (name.startsWith(OWN_WIRE_PREFIX)) return name.slice(OWN_WIRE_PREFIX.length); return Object.prototype.hasOwnProperty.call(NATIVE_TO_CANONICAL, name) ? NATIVE_TO_CANONICAL[name] : name; } function record(v: unknown): Record<string, unknown> { return typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {}; } function readResult(p: Record<string, unknown>): ToolResultInfo { const text = p.output === undefined ? "" : typeof p.output === "string" ? p.output : JSON.stringify(p.output); const info: ToolResultInfo = { isError: p.isError === true, bytes: Buffer.byteLength(text), text }; if (typeof p.exitCode === "number") info.exitCode = p.exitCode; return info; } // cwd is the plugin-init `directory` (impl/10 §11 cwd row). The per-request `context` firing is de-duplicated by // the caller (impl/10 §11 Errors), so decode stays a pure mapping. export function decode(raw: unknown): CanonicalHookEvent { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("opencode: hook payload is not an object"); const p = raw as Record<string, unknown>; const native = typeof p.type === "string" ? p.type : ""; const event = Object.prototype.hasOwnProperty.call(OPENCODE_EVENTS, native) ? OPENCODE_EVENTS[native] : undefined; if (event === undefined) throw new Error("opencode: unknown hook event " + String(p.type)); const ev: CanonicalHookEvent = { event, agent: "opencode", sessionId: String(p.sessionID ?? ""), cwd: String(p.directory ?? "") }; // D-R54-OC-AGENT-1 (#1348): 1.19 has no agent field, so these stay undefined there. The 2.x bridge sets them for an // agent whose Agent.Info.mode is "subagent", with the tools its permissions leave on (ADR-0016 l.23). if (typeof p.agentID === "string" && p.agentID !== "") { ev.agentId = p.agentID; ev.agentType = p.agentID; } if (Array.isArray(p.agentTools)) ev.agentTools = p.agentTools.filter((t): t is string => typeof t === "string"); if (event === "UserPromptSubmit" && typeof p.message === "string") ev.prompt = p.message; if (event === "PreToolUse" || event === "PostToolUse") { const name = String(p.tool ?? ""); ev.tool = { name, canonicalName: toCanonicalTool(name), input: record(p.args) }; if (typeof p.callID === "string") ev.tool.callId = p.callID; } if (event === "PostToolUse") ev.result = readResult(p); if (typeof p.turn === "number") ev.turn = p.turn; return ev; } // hint: only the session `context` hook carries text (no tool hint field). deny: only `execute.before` can fail // (Tool.Error(reason)), rewrite first, exit 2; the `prompt` hook cannot fail. replace: no documented field, no-op. // Never throws (shared encode step 3). export function encode(ev: CanonicalHookEvent, d: Decision, _extra?: string): HookOutput { switch (d.kind) { case "allow": return { stdout: "", exitCode: 0 }; case "hint": return { stdout: ev.event === "SessionStart" ? d.text : "", exitCode: 0 }; case "deny": if (ev.event !== "PreToolUse") return { stdout: "", exitCode: 0 }; return { stdout: d.rewritten === undefined ? d.reason : d.rewritten + "\n" + d.reason, exitCode: 2 }; case "replace": // D-R54-OC-REPLACE-1 (#1347): the plugin writes stdout back into the host's result object return { stdout: ev.event === "PostToolUse" ? d.output : "", exitCode: 0 }; } } - src/adapters/pi.ts (5404 bytes)
// impl/10 §10; DEVIATIONS D-M5-A1-1. Pi is in-process (ADR-0001 §3): the plugin entry calls handleHook with a raw // object whose `type` is the call-site event name (`pi.on(<type>, ...)`), plus the handler argument fields. // decode/encode exist so handleHook stays one code path for every agent (ADR-0001 Decision 3). import { PI_ROLE } from "../core/contracts/constants.ts"; import type { CanonicalEventName, CanonicalHookEvent, Decision, HookOutput, ToolResultInfo } from "../core/contracts/types.ts"; export const TOOL_NAME_PREFIX = ""; // impl/10 §1.3: Pi registers ctx_* under their bare names type Source = NonNullable<CanonicalHookEvent["source"]>; interface EventRow { event: CanonicalEventName; source?: Source } // Call-site name -> canonical event (impl/10 §1.4, §10 SessionStart.source row). const PI_EVENTS: Readonly<Record<string, EventRow>> = { session_start: { event: "SessionStart", source: "startup" }, session_compact: { event: "SessionStart", source: "compact" }, input: { event: "UserPromptSubmit" }, tool_call: { event: "PreToolUse" }, tool_result: { event: "PostToolUse" }, }; /** Pi's encoded output: the native HookOutput plus the custom-role message the entry injects (#1263, #1180). */ export interface PiHookOutput extends HookOutput { role: typeof PI_ROLE; content: string; timestamp: number; } // pi 1.4.0 built-in tool names -> canonical names (D-HA-PI-NAMES-1, dist/core/tools name: "bash" / "read"). // D-R38-PI-EDIT-1 (host audit pi-6): "edit" / "write" map to Edit / Write, so their tool_result is journaled as an edit. const NATIVE_TO_CANONICAL: Readonly<Record<string, string>> = { bash: "Bash", read: "Read", edit: "Edit", write: "Write" }; function record(v: unknown): Record<string, unknown> { return typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {}; } function readResult(p: Record<string, unknown>): ToolResultInfo { const text = p.content === undefined ? "" : typeof p.content === "string" ? p.content : JSON.stringify(p.content); const info: ToolResultInfo = { isError: p.isError === true, bytes: Buffer.byteLength(text), text }; if (typeof p.exitCode === "number") info.exitCode = p.exitCode; if (p.keep === true) info.keep = true; // D-R54-PI-META-1 (#1352): an excludeTools name stays as the host made it return info; } /** ADR-0026 (D-OMP-FIRE-1): OMP sends the Pi payload; the event names the agent omp, so its rows say omp. */ export function decodeOmp(raw: unknown): CanonicalHookEvent { return { ...decode(raw), agent: "omp" }; } export function decode(raw: unknown): CanonicalHookEvent { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("pi: hook payload is not an object"); const p = raw as Record<string, unknown>; const native = typeof p.type === "string" ? p.type : ""; const row = Object.prototype.hasOwnProperty.call(PI_EVENTS, native) ? PI_EVENTS[native] : undefined; if (row === undefined) throw new Error("pi: unknown hook event " + String(p.type)); // No documented subagent field on Pi: agentId/agentType stay undefined (impl/10 §10). const ev: CanonicalHookEvent = { event: row.event, agent: "pi", sessionId: String(p.sessionId ?? ""), cwd: String(p.cwd ?? "") }; if (row.source !== undefined) ev.source = row.source; if (row.event === "UserPromptSubmit" && typeof p.message === "string") ev.prompt = p.message; if (row.event === "PreToolUse" || row.event === "PostToolUse") { const name = String(p.toolName ?? ""); ev.tool = { name, canonicalName: Object.hasOwn(NATIVE_TO_CANONICAL, name) ? NATIVE_TO_CANONICAL[name] : name, input: record(p.input) }; if (typeof p.toolCallId === "string") ev.tool.callId = p.toolCallId; } if (row.event === "PostToolUse") ev.result = readResult(p); if (typeof p.turn === "number") ev.turn = p.turn; return ev; } // hint: only session text carries it (no tool_call hint field, impl/10 §10). deny: tool_call {block, reason}, // rewrite first, exit 2. replace: the tool_result rewrite (ADR-0016 case C). Never throws: a decision Pi // cannot express, or none at all, encodes as the empty allow (shared encode step 3). function stdoutFor(ev: CanonicalHookEvent, d: Decision | undefined): HookOutput { switch (d?.kind) { case "hint": return { stdout: ev.event === "SessionStart" ? d.text : "", exitCode: 0 }; case "deny": if (ev.event !== "PreToolUse") return { stdout: "", exitCode: 0 }; return { stdout: d.rewritten === undefined ? d.reason : d.rewritten + "\n" + d.reason, exitCode: 2 }; case "replace": return { stdout: ev.event === "PostToolUse" ? d.output : "", exitCode: 0 }; } return { stdout: "", exitCode: 0 }; } // allow injects nothing: the native empty shape. Every other result carries the custom-role message fields. export function encode(ev: CanonicalHookEvent, d: Decision, _extra?: string): HookOutput | PiHookOutput { const out = stdoutFor(ev, d); if (d?.kind === "allow") return out; return { stdout: out.stdout, exitCode: out.exitCode, role: PI_ROLE, content: out.stdout, timestamp: Date.now() }; } /** impl/10 §10 deny field: the `tool_call` handler return value for an encoded output. */ export function checkPermission(out: HookOutput): { block: true; reason: string } | undefined { return out.exitCode === 2 ? { block: true, reason: out.stdout } : undefined; } - src/adapters/qwen.ts (2165 bytes)
// impl/10 §5: Qwen Code 0.25.1 uses the Claude hook shape (plus transcript_path, permission_mode, timestamp). // Own prefix is the hyphen form (DECISIONS-r9 R2); no replace field. Native tool ids map to the canonical // names of impl/01 §2 by table lookup; both shell names stay until S-NAMES closes (impl/10 §1.5b, A6). // PostToolUseFailure decodes to canonical PostToolUse with isError (impl/10 §5 "+Failure", DEVIATIONS D-M3-A2-1). import type { CanonicalHookEvent, Decision, HookOutput } from "../core/contracts/types.ts"; import { decodeClaudeShape, encodeClaudeShape } from "./claude-code.ts"; export const TOOL_NAME_PREFIX = "mcp__context-mode__"; // impl/10 §1.3, DECISIONS-r9 R2 type Source = NonNullable<CanonicalHookEvent["source"]>; const QWEN_SOURCES: Readonly<Record<string, Source>> = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" }; // impl/10 §1.3a qwen row -> canonical name; Claude aliases are not listed and pass through unchanged. const NATIVE_TO_CANONICAL: Readonly<Record<string, string>> = { run_shell_command: "Bash", Shell: "Bash", read_file: "Read", grep_search: "Grep", web_fetch: "WebFetch", }; const FAILURE_EVENT = "PostToolUseFailure"; export function decode(raw: unknown): CanonicalHookEvent { const failure = typeof raw === "object" && raw !== null && !Array.isArray(raw) && (raw as Record<string, unknown>).hook_event_name === FAILURE_EVENT; const payload = failure ? { ...(raw as Record<string, unknown>), hook_event_name: "PostToolUse" } : raw; const ev = decodeClaudeShape(payload, "qwen", TOOL_NAME_PREFIX, QWEN_SOURCES); if (ev.tool !== undefined && Object.hasOwn(NATIVE_TO_CANONICAL, ev.tool.name)) ev.tool.canonicalName = NATIVE_TO_CANONICAL[ev.tool.name]; if (failure) { const error = (raw as Record<string, unknown>).error; const text = typeof error === "string" ? error : error === undefined ? "" : JSON.stringify(error); ev.result = { isError: true, bytes: Buffer.byteLength(text), text }; } return ev; } export function encode(ev: CanonicalHookEvent, d: Decision, _extra?: string): HookOutput { return encodeClaudeShape(ev, d, false); } - src/adapters/table.ts (12451 bytes)
// impl/10 §1.1-§1.5: one AdapterRow per agent, PRD §3 order. Row data only; build/manifests.ts renders the // hook configs from it (impl/13 §3). pi and opencode are in-process adapters (impl/10 §10, §11); their rows // also carry the in-process helpers the plugin entries call (DEVIATIONS D-M5-A1-1). import type { AgentId } from "../core/contracts/agents.ts"; import { HOOK_TIMEOUT_MS, IN_PROCESS_TIMEOUT_MS } from "../core/contracts/constants.ts"; import type { AdapterRow, HookOutput } from "../core/contracts/types.ts"; import * as claudeCode from "./claude-code.ts"; import * as codex from "./codex.ts"; import * as gemini from "./gemini.ts"; import * as qwen from "./qwen.ts"; import * as copilotCli from "./copilot-cli.ts"; import * as vscode from "./vscode.ts"; import * as kiro from "./kiro.ts"; import * as zcode from "./zcode.ts"; import * as pi from "./pi.ts"; import * as opencode from "./opencode.ts"; const CLAUDE_EVENTS = { SessionStart: "SessionStart", UserPromptSubmit: "UserPromptSubmit", PreToolUse: "PreToolUse", PostToolUse: "PostToolUse" }; const CLAUDE_TOOLS = { shell: ["Bash"], read: ["Read"], grep: ["Grep"], webfetch: ["WebFetch"], edit: ["Write", "Edit", "NotebookEdit"] }; // D-CC-PWSH-1 (#1212): Claude Code also has a PowerShell tool on Windows; zcode keeps the Bash-only Claude names. const CLAUDE_CODE_TOOLS = { ...CLAUDE_TOOLS, shell: [...claudeCode.SHELL_TOOL_NAMES] }; // In-process rows add one helper each for their plugin entry (DEVIATIONS D-M5-A1-1): Pi turns an encoded deny into // its tool_call {block, reason} return; OpenCode maps a native tool name to the canonical name decide() uses. type Row = AdapterRow & { checkPermission?: (out: HookOutput) => { block: true; reason: string } | undefined; toCanonicalTool?: (name: string) => string; }; export const ADAPTERS: readonly AdapterRow[] = Object.freeze([ { id: "claude-code", installMode: "marketplace", projectSource: "env:CLAUDE_PROJECT_DIR", toolNamePrefix: claudeCode.TOOL_NAME_PREFIX, nativeTools: CLAUDE_CODE_TOOLS, execReadOnlyHint: false, eventMap: CLAUDE_EVENTS, compactDelivery: "sessionstart", compactSummary: "none", hookTimeoutMs: HOOK_TIMEOUT_MS, denyChannel: "deny-reason", hookChannel: { kind: "package", path: "hooks/claude-code.json" }, skillChannel: { kind: "package", path: "skills" }, // ADR-0020, D-R33-CC-SKILLS-1: Claude Code always loads <plugin>/skills, shared with gemini and qwen decode: claudeCode.decode, encode: claudeCode.encode, }, { id: "codex", installMode: "config-mcp", projectSource: "arg:--agent+cwd", toolNamePrefix: codex.TOOL_NAME_PREFIX, nativeTools: { shell: ["Bash"], edit: ["apply_patch"] }, execReadOnlyHint: true, eventMap: CLAUDE_EVENTS, compactDelivery: "sessionstart", compactSummary: "none", hookTimeoutMs: HOOK_TIMEOUT_MS, denyChannel: "deny-reason", hookChannel: { kind: "home-file", path: ".codex/hooks.json" }, skillChannel: { kind: "home-dir", path: ".codex/skills" }, // ADR-0020 decode: codex.decode, encode: codex.encode, }, { id: "gemini", installMode: "extension", projectSource: "spawn-cwd", toolNamePrefix: gemini.TOOL_NAME_PREFIX, // D-HA-GEMINI-NAMES-1: gemini-cli 0.65.0 *_TOOL_NAME constants. nativeTools: { shell: ["run_shell_command"], read: ["read_file"], grep: ["grep_search"], webfetch: ["web_fetch"] }, execReadOnlyHint: false, // D-FU-GCH-1: no SessionStart. Claude Code also loads hooks/hooks.json (Gemini's file) and would run a SessionStart // entry through /bin/sh, which fails on ${extensionPath}. Gemini's SessionStart only sent the resume hint (compact never // arrives there), and GP6 forbids that hint on BeforeAgent, so Gemini goes without it. eventMap: { UserPromptSubmit: "BeforeAgent", PreToolUse: "BeforeTool", PostToolUse: "AfterTool", PreCompact: "PreCompress" }, compactDelivery: "pending-flag", compactSummary: "none", hookTimeoutMs: HOOK_TIMEOUT_MS, denyChannel: "deny-reason", hookChannel: { kind: "package", path: "hooks/hooks.json" }, skillChannel: { kind: "package", path: "skills" }, // ADR-0020 decode: gemini.decode, encode: gemini.encode, }, { id: "qwen", installMode: "extension", projectSource: "spawn-cwd", toolNamePrefix: qwen.TOOL_NAME_PREFIX, nativeTools: { shell: ["run_shell_command", "Shell"], read: ["read_file"], grep: ["grep_search"], webfetch: ["web_fetch"] }, execReadOnlyHint: false, eventMap: CLAUDE_EVENTS, compactDelivery: "sessionstart", compactSummary: "none", hookTimeoutMs: HOOK_TIMEOUT_MS, denyChannel: "deny-reason", hookChannel: { kind: "package", path: "hooks/qwen.json" }, skillChannel: { kind: "package", path: "skills" }, // ADR-0020, D-HQ-SKILLS-3: qwen loads <extension>/skills, shared with gemini decode: qwen.decode, encode: qwen.encode, }, { id: "copilot-cli", installMode: "plugin", projectSource: "arg:--agent+cwd", toolNamePrefix: copilotCli.TOOL_NAME_PREFIX, nativeTools: { shell: [...copilotCli.SHELL_TOOL_NAMES] }, execReadOnlyHint: false, // D-PWSH-DUMP-1 eventMap: { SessionStart: "sessionStart", UserPromptSubmit: "userPromptSubmitted", PreToolUse: "preToolUse", PostToolUse: "postToolUse" }, compactDelivery: "pending-flag", compactSummary: "none", hookTimeoutMs: HOOK_TIMEOUT_MS, denyChannel: "deny-reason", hookChannel: { kind: "home-file", path: ".copilot/hooks/context-mode.json" }, skillChannel: { kind: "home-dir", path: ".copilot/skills" }, // ADR-0020 decode: copilotCli.decode, encode: copilotCli.encode, }, { id: "vscode", installMode: "mcp-entry", projectSource: "arg:workspaceFolder", toolNamePrefix: vscode.TOOL_NAME_PREFIX, // PreCompact sets the pending flag (ADR-0009 §6, DEVIATIONS D-M3-A4-1). nativeTools: { shell: [...vscode.SHELL_TOOL_NAMES], read: [...vscode.READ_TOOL_NAMES], webfetch: [...vscode.WEBFETCH_TOOL_NAMES] }, // D-HF-VSCODE-PROJECT-1, D-N7-VSCODE-TOOLS-1 execReadOnlyHint: false, eventMap: { ...CLAUDE_EVENTS, PreCompact: "PreCompact" }, compactDelivery: "pending-flag", compactSummary: "none", hookTimeoutMs: HOOK_TIMEOUT_MS, denyChannel: "deny-reason", hookChannel: { kind: "home-file", path: ".copilot/hooks/context-mode-vscode.json" }, skillChannel: { kind: "home-dir", path: ".agents/skills" }, // ADR-0020, D-HQ-COPILOT-NAMES-3: Copilot CLI owns ~/.copilot/skills decode: vscode.decode, encode: vscode.encode, }, { id: "kiro", installMode: "mcp-entry", projectSource: "arg:--agent+cwd", toolNamePrefix: kiro.TOOL_NAME_PREFIX, nativeTools: { shell: [...kiro.SHELL_TOOL_NAMES] }, execReadOnlyHint: false, // D-HF-KIRO-SHELL-1, D-N7-KIRO-1 eventMap: { SessionStart: "SessionStart", UserPromptSubmit: "UserPromptSubmit", PreToolUse: "PreToolUse", PostToolUse: "PostToolUse" }, compactDelivery: "none", compactSummary: "none", hookTimeoutMs: HOOK_TIMEOUT_MS, denyChannel: "hint-only", hookChannel: { kind: "home-file", path: ".kiro/hooks/context-mode.json" }, skillChannel: { kind: "home-dir", path: ".kiro/skills" }, // ADR-0020 decode: kiro.decode, encode: kiro.encode, }, { // toolNamePrefix is the documented ZCode name mcp__<server>__<tool> (D-N7-ZCODE-NAMES-1); nativeTools are Claude names. id: "zcode", installMode: "hooks+mcp", projectSource: "spawn-cwd", toolNamePrefix: zcode.TOOL_NAME_PREFIX, nativeTools: CLAUDE_TOOLS, execReadOnlyHint: false, eventMap: CLAUDE_EVENTS, compactDelivery: "sessionstart", compactSummary: "none", hookTimeoutMs: HOOK_TIMEOUT_MS, denyChannel: "deny-reason", hookChannel: { kind: "home-file", path: ".zcode/cli/config.json" }, skillChannel: { kind: "home-dir", path: ".zcode/skills" }, // ADR-0020 decode: zcode.decode, encode: zcode.encode, }, { id: "pi", installMode: "in-process", projectSource: "pi:ctx.cwd", toolNamePrefix: pi.TOOL_NAME_PREFIX, nativeTools: { shell: ["bash", "powershell"], read: ["read"] }, execReadOnlyHint: false, // D-R38-PI-PWSH-1: Pi on Windows names its shell tool "powershell" eventMap: { SessionStart: "session_start", UserPromptSubmit: "input", PreToolUse: "tool_call", PostToolUse: "tool_result" }, compactDelivery: "pi-flag", compactSummary: "none", hookTimeoutMs: IN_PROCESS_TIMEOUT_MS, denyChannel: "deny-reason", hookChannel: { kind: "in-process", path: "pi/index.js" }, skillChannel: { kind: "package", path: "pi/skills" }, // ADR-0020 decode: pi.decode, encode: pi.encode, checkPermission: pi.checkPermission, }, { id: "opencode", installMode: "in-process", projectSource: "spawn-cwd", toolNamePrefix: opencode.TOOL_NAME_PREFIX, nativeTools: { shell: [opencode.SHELL_TOOL_NAME], read: [opencode.READ_TOOL_NAME] }, execReadOnlyHint: false, // D-HF-OPENCODE-SHELL-1, D-R44-OC-READ-1 // Usage: step-finish cost row (DEVIATIONS D-M5-arch-2). eventMap: { SessionStart: "context", UserPromptSubmit: "prompt", PreToolUse: "execute.before", PostToolUse: "execute.after", PreCompact: "compaction", Usage: "step-finish" }, compactDelivery: "opencode-cache", compactSummary: "none", hookTimeoutMs: IN_PROCESS_TIMEOUT_MS, denyChannel: "deny-reason", hookChannel: { kind: "in-process", path: "opencode/plugin.js" }, skillChannel: { kind: "home-dir", path: ".config/opencode/skills" }, // ADR-0020 decode: opencode.decode, encode: opencode.encode, toCanonicalTool: opencode.toCanonicalTool, }, { // ADR-0026 (D-OMP-ROW-1): OMP runs the Pi extension API in-process, so the row reuses the Pi decode, encode and // permission check; tool names stay bare. Only the entry path and the skills folder are its own. id: "omp", installMode: "in-process", projectSource: "pi:ctx.cwd", toolNamePrefix: pi.TOOL_NAME_PREFIX, nativeTools: { shell: ["bash", "powershell"], read: ["read"] }, execReadOnlyHint: false, eventMap: { SessionStart: "session_start", UserPromptSubmit: "input", PreToolUse: "tool_call", PostToolUse: "tool_result" }, compactDelivery: "pi-flag", compactSummary: "none", hookTimeoutMs: IN_PROCESS_TIMEOUT_MS, denyChannel: "deny-reason", hookChannel: { kind: "in-process", path: "omp/index.js" }, skillChannel: { kind: "package", path: "skills" }, // D-OMP-SKILLS-1 decode: pi.decodeOmp, encode: pi.encode, checkPermission: pi.checkPermission, // D-OMP-FIRE-1: agent omp in rows }, ] satisfies Row[]); const BY_ID = new Map<AgentId, AdapterRow>(ADAPTERS.map((r) => [r.id, r])); // D-M7-RR-1 (DECISIONS-r10): rows whose encode writes a PostToolUse replace (claude-code updatedToolOutput, // pi tool_result rewrite). On these rows the main agent gets "run, then replace" and no Bash size-guess deny; // every other row keeps its one path (ADR-0001). // gemini: AfterTool decision deny + reason replaces the result (D-HA-GEMINI-REPLACE-1). // opencode: the plugin sets result.content (2.x) or output.output (1.19) in-process; both hosts read that object back // after the hook (D-R54-OC-REPLACE-1, #1347). Not in DUMP_REPLACE_ROWS: execute.before can deny a large cat first. const REPLACE_ROWS: ReadonlySet<AgentId> = new Set<AgentId>(["claude-code", "gemini", "copilot-cli", "pi", "opencode", "omp"]); // omp: the Pi tool_result rewrite (ADR-0026) export function hasReplace(row: AdapterRow): boolean { return REPLACE_ROWS.has(row.id); } // D-HA-GEMINI-DUMP-1: rows where a one-file shell dump over the cap runs and PostToolUse replaces it (D-M7-RR-1). // gemini is out: its BeforeTool deny stops the tool before it runs (gemini-cli docs/hooks/reference.md BeforeTool), // so a large `cat` is denied with the Read redirect, as on every other deny host. const DUMP_REPLACE_ROWS: ReadonlySet<AgentId> = new Set<AgentId>(["claude-code", "copilot-cli", "pi", "omp"]); export function dumpRunsThenReplaces(row: AdapterRow): boolean { return DUMP_REPLACE_ROWS.has(row.id) && hasReplace(row); } // DECISIONS-r11 (B): rows whose encode carries a UserPromptSubmit hint as additionalContext. Only these rows // get turn-boundary recall after a compaction; pi and opencode keep their one compact path (ADR-0001). const RECALL_ROWS: ReadonlySet<AgentId> = new Set<AgentId>(["claude-code", "codex", "gemini", "qwen", "copilot-cli", "vscode", "zcode", "kiro"]); // D-R33-KIRO-RECALL-1 export function hasRecall(row: AdapterRow): boolean { return RECALL_ROWS.has(row.id); } // impl/10 §1.2: AGENT_IDS (contracts) is exhaustive, every AgentId has exactly one row. export function getAdapter(id: AgentId): AdapterRow { return BY_ID.get(id) as AdapterRow; } - src/adapters/vscode.ts (9701 bytes)
// impl/10 §7 + shared decode/encode pseudocode; ADR-0016 VS Code row (case C: no replace channel). // VS Code hooks send the Claude-style snake_case payload; tool names are mcp_<server>_<tool> (TECH-SPEC §3.8). // PreCompact is the aux event that sets the pending flag (ADR-0009 §6, impl/09 §4.7, DEVIATIONS D-M3-A4-1). import type { CanonicalEventName, AuxEventName, CanonicalHookEvent, Decision, HookOutput, ToolResultInfo } from "../core/contracts/types.ts"; import { encodeClaudeShape } from "./claude-code.ts"; export const TOOL_NAME_PREFIX = "mcp_context-mode_"; // impl/10 §1.3, TECH-SPEC §3.8 VS Code row const VSCODE_EVENTS: readonly (CanonicalEventName | AuxEventName)[] = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PreCompact"]; const MCP_PREFIX = "mcp_"; const MCP_SEP = "_"; const SESSION_START_NEW = "new"; // impl/10 §7: SessionStart fires only with source "new" (first turn) // Own tool -> bare ctx_*; mcp_<server>_<tool> -> "mcp:<server>:<tool>", split at the first "_" after "mcp_" // (DEVIATIONS D-M3-A4-3); native names unchanged. // D-N7-VSCODE-TOOLS-1: one list of the documented tool names, used by the decoder and the table row. // Local harness ids (microsoft/vscode 1.145.0, vscode-copilot-chat 0.44.0 toolNames.ts): run_in_terminal, read_file, // fetch_webpage. Copilot harness runtime names (docs.github.com copilot/reference/hooks-reference, "Tool names for // hook matching"): bash, powershell, view, web_fetch. runTerminalCommand is in no source; the next.7 npm-package // test received it live, so it is mapped as observed. A PascalCase payload names Bash, Read, WebFetch (canonical). export const SHELL_TOOL_NAMES: readonly string[] = Object.freeze(["run_in_terminal", "runTerminalCommand", "bash", "powershell"]); export const READ_TOOL_NAMES: readonly string[] = Object.freeze(["read_file", "view"]); export const WEBFETCH_TOOL_NAMES: readonly string[] = Object.freeze(["fetch_webpage", "web_fetch"]); const NATIVE_TO_CANONICAL: Readonly<Record<string, string>> = Object.fromEntries([ ...SHELL_TOOL_NAMES.map((n) => [n, "Bash"]), ...READ_TOOL_NAMES.map((n) => [n, "Read"]), ...WEBFETCH_TOOL_NAMES.map((n) => [n, "WebFetch"]), ]); function canonicalName(name: string): string { if (name.startsWith(TOOL_NAME_PREFIX)) return name.slice(TOOL_NAME_PREFIX.length); if (Object.hasOwn(NATIVE_TO_CANONICAL, name)) return NATIVE_TO_CANONICAL[name]; if (!name.startsWith(MCP_PREFIX)) return name; const rest = name.slice(MCP_PREFIX.length); const sep = rest.indexOf(MCP_SEP); if (sep <= 0 || sep === rest.length - 1) return name; return "mcp:" + rest.slice(0, sep) + ":" + rest.slice(sep + MCP_SEP.length); } // The policy reads Claude keys (file_path, offset, limit, url). Each tool's documented keys are mapped once here: // read_file {filePath, startLine, endLine} (vscode-copilot-chat package.json copilot_readFile), view {path, view_range} // (Copilot runtime), fetch_webpage {urls[], query}. The first url is the one checked. Source keys are kept. const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v); function policyInput(name: string, canonical: string, input: Record<string, unknown>): Record<string, unknown> { if (canonical === "Read" && READ_TOOL_NAMES.includes(name)) { const out: Record<string, unknown> = { ...input }; if (name === "read_file") { if (typeof input.filePath === "string") out.file_path = input.filePath; if (isNum(input.startLine)) out.offset = input.startLine; if (isNum(input.startLine) && isNum(input.endLine) && input.endLine >= input.startLine) out.limit = input.endLine - input.startLine + 1; } else if (Array.isArray(input.view_range) && isNum(input.view_range[0])) { out.offset = input.view_range[0]; const end = input.view_range[1]; if (isNum(end) && end >= input.view_range[0]) out.limit = end - input.view_range[0] + 1; } return out; } if (canonical === "WebFetch" && name === "fetch_webpage" && Array.isArray(input.urls) && typeof input.urls[0] === "string") { return { ...input, url: input.urls[0] }; } return input; } function readResult(resp: unknown): ToolResultInfo { const text = resp === undefined ? "" : typeof resp === "string" ? resp : JSON.stringify(resp); const isError = typeof resp === "object" && resp !== null && (resp as { is_error?: unknown }).is_error === true; return { isError, bytes: Buffer.byteLength(text), text }; } // D-HF-VSCODE-DECODE-1: two documented payload shapes, one key set each, chosen by the event name's casing. // snake: Local harness and the PascalCase alias (code.visualstudio.com/docs/agents/reference/hooks-reference, // "Common input"): hook_event_name, session_id, tool_name, tool_input, tool_response. camel: Copilot harness // camelCase events (docs.github.com/en/copilot/reference/hooks-reference): sessionId, toolName, toolArgs, // toolResult {resultType, textResultForLlm}; the documented payload names no event, a live next.6 payload // carried hookEventName. No cross-reading of keys between the two. const CAMEL_EVENTS: Readonly<Record<string, CanonicalEventName | AuxEventName>> = { sessionStart: "SessionStart", userPromptSubmitted: "UserPromptSubmit", preToolUse: "PreToolUse", postToolUse: "PostToolUse", preCompact: "PreCompact", }; // A camelCase payload with no event name: each event has its own key (GitHub hooks reference payload types). const EVENT_BY_KEY: readonly (readonly [string, string])[] = [ ["toolResult", "postToolUse"], ["toolName", "preToolUse"], ["prompt", "userPromptSubmitted"], ["source", "sessionStart"], ["trigger", "preCompact"], ]; const SESSION_SOURCES: Readonly<Record<string, NonNullable<CanonicalHookEvent["source"]>>> = { new: "startup", startup: "startup", resume: "resume" }; const RESULT_SUCCESS = "success"; function isRecord(v: unknown): v is Record<string, unknown> { return typeof v === "object" && v !== null && !Array.isArray(v); } // toolArgs arrives as an object or as a JSON-encoded string; anything else is {} (same rule as copilot-cli). function readArgs(v: unknown): Record<string, unknown> { if (isRecord(v)) return v; if (typeof v !== "string") return {}; try { const parsed: unknown = JSON.parse(v); return isRecord(parsed) ? parsed : {}; } catch { return {}; } } function readCamelResult(v: unknown): ToolResultInfo { const r = isRecord(v) ? v : {}; const text = typeof r.textResultForLlm === "string" ? r.textResultForLlm : ""; return { isError: typeof r.resultType === "string" && r.resultType !== RESULT_SUCCESS, bytes: Buffer.byteLength(text), text }; } function decodeCamel(p: Record<string, unknown>, name: unknown): CanonicalHookEvent { const event = typeof name === "string" ? CAMEL_EVENTS[name] ?? VSCODE_EVENTS.find((e) => e === name) : undefined; if (event === undefined) throw new Error("vscode: unknown hook event " + String(name)); const ev: CanonicalHookEvent = { event, agent: "vscode", sessionId: String(p.sessionId ?? ""), cwd: String(p.cwd ?? "") }; if (event === "SessionStart" && typeof p.source === "string" && SESSION_SOURCES[p.source] !== undefined) ev.source = SESSION_SOURCES[p.source]; if (event === "UserPromptSubmit" && typeof p.prompt === "string") ev.prompt = p.prompt; if (event === "PreToolUse" || event === "PostToolUse") { const toolName = String(p.toolName ?? ""); const canonical = canonicalName(toolName); ev.tool = { name: toolName, canonicalName: canonical, input: policyInput(toolName, canonical, readArgs(p.toolArgs)) }; } if (event === "PostToolUse") ev.result = readCamelResult(p.toolResult); return ev; } export function decode(raw: unknown): CanonicalHookEvent { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("vscode: hook payload is not a JSON object"); const p = raw as Record<string, unknown>; if (p.hookEventName !== undefined) return decodeCamel(p, p.hookEventName); if (p.hook_event_name === undefined) { const byKey = EVENT_BY_KEY.find(([key]) => Object.hasOwn(p, key))?.[1]; if (byKey === undefined) throw new Error("vscode: missing required field hook_event_name"); // never a silent drop return decodeCamel(p, byKey); } const event = VSCODE_EVENTS.find((e) => e === p.hook_event_name); if (event === undefined) throw new Error("vscode: unknown hook event " + String(p.hook_event_name)); // session_id optional. cwd is the common input field (VS Code hooks reference, "Common input"); it is the // hook's one project channel (D-HF-VSCODE-PROJECT-1); the server's is --workspace-folder. No subagent field. const ev: CanonicalHookEvent = { event, agent: "vscode", sessionId: String(p.session_id ?? ""), cwd: String(p.cwd ?? "") }; if (event === "SessionStart" && p.source === SESSION_START_NEW) ev.source = "startup"; // DEVIATIONS D-M3-A4-2 if (event === "UserPromptSubmit" && typeof p.prompt === "string") ev.prompt = p.prompt; if (event === "PreToolUse" || event === "PostToolUse") { const name = String(p.tool_name ?? ""); const input = isRecord(p.tool_input) ? p.tool_input : {}; const canonical = canonicalName(name); ev.tool = { name, canonicalName: canonical, input: policyInput(name, canonical, input) }; } if (event === "PostToolUse") ev.result = readResult(p.tool_response); return ev; } // hint -> additionalContext; deny -> permissionDecision "deny" + reason (rewrite first, ADR-0016 case B); // replace -> silent no-op, VS Code has no output-replace field (ADR-0016 case C, impl/10 §7). export function encode(ev: CanonicalHookEvent, d: Decision, _extra?: string): HookOutput { return encodeClaudeShape(ev, d, false); } - src/adapters/zcode.ts (2662 bytes)
// impl/10 §9: ZCode uses the Claude hook shape with camelCase twins (spike-hooks-verified §2). // Own prefix is the documented ZCode MCP name mcp__<server>__<tool> (D-N7-ZCODE-NAMES-1); native names are Claude names. // Twins: decode reads snake_case first, then the camelCase twin, for the two rows impl/10 §9 names. // PostToolUseFailure decodes to canonical PostToolUse with isError (impl/10 §9 "+Failure", DEVIATIONS D-M3-A6-1). // No replace field is documented. import type { CanonicalHookEvent, Decision, HookOutput } from "../core/contracts/types.ts"; import { decodeClaudeShape, encodeClaudeShape } from "./claude-code.ts"; // zcode.z.ai/en/docs/subagents: "in the form `mcp__<server>__<tool>`"; ZCode core/src/mcp/name.ts keeps "-" in the server part. export const TOOL_NAME_PREFIX = "mcp__context-mode__"; // D-R44-ZCODE-NATIVE-1: a plugin MCP server is shown to the model as mcp__plugin_<plugin>_<server>__<tool> (ZCode // core/src/mcp/name.ts sanitizes "plugin:context-mode:context-mode"), so the native install names tools with this prefix. export const PLUGIN_TOOL_NAME_PREFIX = "mcp__plugin_context-mode_context-mode__"; type Source = NonNullable<CanonicalHookEvent["source"]>; const ZCODE_SOURCES: Readonly<Record<string, Source>> = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" }; // snake_case field -> its camelCase twin (impl/10 §9 rows "event name" and "sessionId"). const TWINS: Readonly<Record<string, string>> = { hook_event_name: "hookEventName", session_id: "sessionId" }; const FAILURE_EVENT = "PostToolUseFailure"; export function decode(raw: unknown): CanonicalHookEvent { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("zcode: hook payload is not a JSON object"); const p: Record<string, unknown> = { ...(raw as Record<string, unknown>) }; for (const [snake, camel] of Object.entries(TWINS)) if (p[snake] === undefined) p[snake] = p[camel]; const failure = p.hook_event_name === FAILURE_EVENT; if (failure) p.hook_event_name = "PostToolUse"; const toolName = typeof p.tool_name === "string" ? p.tool_name : ""; const prefix = toolName.startsWith(PLUGIN_TOOL_NAME_PREFIX) ? PLUGIN_TOOL_NAME_PREFIX : TOOL_NAME_PREFIX; const ev = decodeClaudeShape(p, "zcode", prefix, ZCODE_SOURCES); if (failure) { const text = typeof p.error === "string" ? p.error : p.error === undefined ? "" : JSON.stringify(p.error); ev.result = { isError: true, bytes: Buffer.byteLength(text), text }; } return ev; } export function encode(ev: CanonicalHookEvent, d: Decision, _extra?: string): HookOutput { return encodeClaudeShape(ev, d, false); } - src/cli/args.ts (8891 bytes)
// src/cli/args.ts: flags, help text and typo hints for setup, doctor and upgrade (ADR-0019 section 8, D7). // Pure module: no I/O, so the golden --help tests and the usage-error tests need no TTY. import { ADAPTERS } from "../adapters/table.ts"; import { SUPPORTED_AGENTS_LINE, UNSUPPORTED_SETUP_LINE } from "../core/ops/unsupported-host.ts"; import { unsupportedHostByName } from "../core/ops/unsupported-host.ts"; import type { AgentId } from "../core/contracts/agents.ts"; export type Command = "setup" | "doctor" | "upgrade"; export const COMMANDS: readonly Command[] = ["setup", "doctor", "upgrade"]; export const ALL_COMMANDS: readonly string[] = ["setup", "doctor", "upgrade", "server", "mcp", "hook", "help"]; export const AGENT_IDS: readonly AgentId[] = ADAPTERS.map((a) => a.id); export interface Flags { help: boolean; json: boolean; yes: boolean; noInput: boolean; dryRun: boolean; debug: boolean; quiet: boolean; verbose: boolean; noColor: boolean; list: boolean; remove: boolean; repair: boolean; agents?: AgentId[]; tag?: string; print?: AgentId; } const COMMON = ["--help", "-h", "--json", "--yes", "-y", "--no-input", "--debug", "--quiet", "-q", "--verbose", "--no-color", "--agents"]; const FLAGS: Readonly<Record<Command, readonly string[]>> = { setup: [...COMMON, "--dry-run", "--list", "--remove", "--repair", "--print"], doctor: COMMON, upgrade: [...COMMON, "--dry-run", "--tag"], }; const VALUE_FLAGS = new Set(["--agents", "--tag", "--print"]); const TAG_RE = /^[a-z0-9][a-z0-9.+-]*$/i; // npm dist-tag or semver; never reaches a shell unquoted export class UsageError extends Error {} /** D-UNSUPPORTED-HOSTS-1: a known unsupported host gets the positive line; any other name gets the supported list. */ function badAgent(name: string): UsageError { const h = unsupportedHostByName(name); if (h !== undefined) return new UsageError(UNSUPPORTED_SETUP_LINE(h.name)); return new UsageError(`unknown agent "${name}".${suggest(name, AGENT_IDS)} ${SUPPORTED_AGENTS_LINE} Run context-mode setup --list.`); } /** Levenshtein distance, small inputs only (commands, flags, agent ids). */ function distance(a: string, b: string): number { const row = Array.from({ length: b.length + 1 }, (_, i) => i); for (let i = 1; i <= a.length; i++) { let prev = row[0]++; for (let j = 1; j <= b.length; j++) { const cur = row[j]; row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1)); prev = cur; } } return row[b.length]; } /** ` Did you mean "x"?` for the closest candidate within reach, else "". */ export function suggest(word: string, candidates: readonly string[]): string { let best = ""; let bestD = Infinity; for (const c of candidates) { const d = distance(word, c); if (d < bestD) { best = c; bestD = d; } } return bestD <= Math.max(2, Math.floor(word.length / 3)) ? ` Did you mean "${best}"?` : ""; } export function parseFlags(cmd: Command, argv: readonly string[]): Flags { const f: Flags = { help: false, json: false, yes: false, noInput: false, dryRun: false, debug: false, quiet: false, verbose: false, noColor: false, list: false, remove: false, repair: false }; for (let i = 0; i < argv.length; i++) { const raw = argv[i]; const eq = raw.startsWith("--") ? raw.indexOf("=") : -1; const name = eq > 0 ? raw.slice(0, eq) : raw; if (!FLAGS[cmd].includes(name)) { const kind = name.startsWith("-") ? "option" : "argument"; throw new UsageError(`unknown ${kind} "${name}" for context-mode ${cmd}.${name.startsWith("-") ? suggest(name, FLAGS[cmd]) : ""}`); } let value: string | undefined; if (VALUE_FLAGS.has(name)) { value = eq > 0 ? raw.slice(eq + 1) : argv[++i]; if (value === undefined || value === "" || value.startsWith("-")) throw new UsageError(`${name} needs a value.`); } else if (eq > 0) throw new UsageError(`${name} takes no value.`); switch (name) { case "--help": case "-h": f.help = true; break; case "--json": f.json = true; break; case "--yes": case "-y": f.yes = true; break; case "--no-input": f.noInput = true; break; case "--dry-run": f.dryRun = true; break; case "--debug": f.debug = true; break; case "--quiet": case "-q": f.quiet = true; break; case "--verbose": f.verbose = true; break; case "--no-color": f.noColor = true; break; case "--list": f.list = true; break; case "--remove": f.remove = true; break; case "--repair": f.repair = true; break; case "--tag": if (!TAG_RE.test(value!)) throw new UsageError(`--tag "${value}" is not an npm dist-tag or version.`); f.tag = value!; break; case "--print": if (!(AGENT_IDS as readonly string[]).includes(value!)) throw badAgent(value!); f.print = value as AgentId; break; case "--agents": { const ids = value!.split(",").map((s) => s.trim()).filter(Boolean); for (const id of ids) { if (!(AGENT_IDS as readonly string[]).includes(id)) throw badAgent(id); } f.agents = [...new Set(ids)] as AgentId[]; break; } } } if (f.list && f.remove) throw new UsageError("--list and --remove cannot be used together."); if (f.print) { const mixed = ([["--remove", f.remove], ["--list", f.list], ["--dry-run", f.dryRun], ["--repair", f.repair], ["--agents", !!f.agents]] as const).find(([, on]) => on); if (mixed) throw new UsageError(`--print cannot be used with ${mixed[0]}.`); } return f; } const EXIT_CODES = `Exit codes: 0 success 1 a check or step failed 2 usage error (unknown command, option or agent; an answer is needed but there is no TTY) 130 stopped with Ctrl-C (the agent in progress is rolled back) `; export const HELP_MAIN = `Usage: context-mode <command> [options] Commands: setup Find your agents, show the plan, apply it, verify each agent doctor Check every agent; changes nothing upgrade Install the newest context-mode from npm, then repair each agent server [--agent <id>] Run the MCP server on stdio (alias: mcp) hook --agent <id> Run one hook call: JSON on stdin, answer on stdout hook <platform> <event> Old form of hook; still works, run context-mode setup to update it Options: -h, --help Show this help (context-mode <command> --help for a command) -v, --version Show the version ${EXIT_CODES} Examples: context-mode setup context-mode doctor --agents codex context-mode server --agent codex `; const COMMON_HELP = ` --agents <ids> Only these agents, comma-separated (ids: context-mode setup --list) -y, --yes Do not ask; apply --no-input Never prompt; exit 2 if an answer is needed --json Write only JSON to stdout -q, --quiet Results only; no progress lines --verbose Show every check --debug Print the full debug report on failure --no-color No colour (also NO_COLOR, TERM=dumb, or no TTY) -h, --help Show this help `; export const HELP: Readonly<Record<Command, string>> = { setup: `Usage: context-mode setup [options] Find your agents, show the plan, apply it, then verify each agent (MCP handshake, one hook call). A failed agent is rolled back byte for byte. Instruction files (CLAUDE.md, AGENTS.md, ...) are never touched. Options: --list Print every supported agent and its support level; change nothing --dry-run Show the plan; change nothing --remove Undo every setup run: put each touched file back --repair Apply again and verify (upgrade runs this) --print <id> Print the manual step for one agent, paths filled in; change nothing ${COMMON_HELP} ${EXIT_CODES} Examples: context-mode setup context-mode setup --yes --agents codex,claude-code context-mode setup --dry-run --json context-mode setup --print codex `, doctor: `Usage: context-mode doctor [options] Check each agent: config entry, old context-mode entries, MCP handshake, one hook call. Changes nothing. On a TTY, a failed agent gets one question: fix now (runs context-mode setup for that agent). Options: ${COMMON_HELP} ${EXIT_CODES} Examples: context-mode doctor context-mode doctor --agents codex --json context-mode doctor --no-input `, upgrade: `Usage: context-mode upgrade [options] Run npm i -g context-mode@<tag>, then the new version runs context-mode setup --repair. Options: --tag <tag> npm dist-tag or version to install (default: the dist-tag of this version) --dry-run Print the commands; run nothing ${COMMON_HELP} ${EXIT_CODES} Examples: context-mode upgrade context-mode upgrade --tag next --yes context-mode upgrade --dry-run `, }; - src/cli/commands.ts (20646 bytes)
// src/cli/commands.ts: context-mode setup, doctor and upgrade on top of the setup engine (ADR-0019 sections 4-8, // Owner decisions D5-D7). Results go to stdout, progress and errors to stderr. Prompts (@clack/prompts, bundled at // build time, D5) run only when stdin and stdout are a TTY and neither --yes, --no-input nor --json is set; every // other run takes the flag path and never waits for input (exit 2 when an answer is needed). import { spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync, mkdirSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { UNSUPPORTED_HOST_LINE } from "../core/ops/unsupported-host.ts"; import { unsupportedHostOf } from "../core/ops/unsupported-host.ts"; import * as clack from "@clack/prompts"; import { ADAPTERS } from "../adapters/table.ts"; import type { AgentId } from "../core/contracts/agents.ts"; import { dataRootOf, homeDirOf } from "../core/project/config-dir.ts"; import { formUrl } from "../core/ops/doctor-issue.ts"; import { formatError } from "../core/contracts/errors.ts"; import { nodeTooOld } from "../core/hooks/fallback.ts"; import { buildRegistry, detectAgents, printPlan, printText, runDoctor, runRemove, runSetup } from "../setup/index.ts"; import type { AgentResult, SetupContext, SetupResult } from "../setup/index.ts"; import { HELP, parseFlags, UsageError, type Command, type Flags } from "./args.ts"; export const EXIT_OK = 0; export const EXIT_FAIL = 1; export const EXIT_USAGE = 2; export const EXIT_SIGINT = 130; export const ISSUE_REPO = "mksglu/context-mode"; const REPORT_DIR = "reports"; const URL_BODY_MAX = 6000; // GitHub rejects very long prefilled URLs; the report file stays whole const NO_TTY = "an answer is needed and there is no TTY (or --no-input is set). Run again with --yes to apply, or with --dry-run to only see the plan."; export interface CliEnv { pkgDir: string; version: string; argv: readonly string[]; } type Clack = typeof clack; interface Ui { f: Flags; ctx: SetupContext; clack?: Clack; env: CliEnv; } // ---------- output ---------- const out = (s: string): void => { process.stdout.write(s.endsWith("\n") ? s : s + "\n"); }; const err = (s: string): void => { process.stderr.write(s.endsWith("\n") ? s : s + "\n"); }; function progress(ui: Ui, s: string): void { if (ui.f.quiet) return; if (ui.clack) ui.clack.log.step(s); else err(s); } const fixFor = (id: AgentId): string => `context-mode setup --agents ${id}`; /** D-INST-7: a PASS row names the checks that ran, so a user sees what was verified. */ function passDetail(a: AgentResult): string { if (a.status !== "PASS" || !a.checks.length) return ""; const warns = a.checks.filter((c) => c.warn).map((c) => `; WARN ${c.name}: ${c.detail}`).join(""); return `checked: ${a.checks.map((c) => c.name).join(", ")}${warns}`; } function table(agents: readonly AgentResult[]): string { // OPEN-ITEMS H8: the row names the host CLI file that ran, so a wrapper on PATH is visible. const rows = agents.map((a) => `${a.id.padEnd(13)} ${a.status.padEnd(7)} ${a.reason ?? passDetail(a)}${a.bin ? `; bin: ${a.bin}` : ""}${a.rolledBack ? " (rolled back)" : ""}`.trimEnd()); return [`${"AGENT".padEnd(13)} STATUS DETAIL`, ...rows].join("\n"); } function failLines(agents: readonly AgentResult[]): string[] { return agents.filter((a) => a.status === "FAIL").map((a) => `FAIL ${a.id}: ${a.reason ?? "failed"}. Fix: ${a.fix ?? fixFor(a.id)}`); } function verboseLines(agents: readonly AgentResult[]): string[] { return agents.flatMap((a) => a.checks.map((c) => ` ${a.id} ${c.warn ? "WARN" : c.ok ? "ok " : "FAIL"} ${c.name}${c.detail ? `: ${c.detail}` : ""}`)); } function planText(res: SetupResult): string { const lines: string[] = []; for (const a of res.agents) { lines.push(`${a.id}${a.status === "PASS" ? "" : ` ${a.status}: ${a.reason ?? ""}`}`); if (a.status === "PASS" && !a.changes.length) lines.push(" no change needed"); for (const c of a.changes) { if (c.command) lines.push(` run ${c.command.join(" ")}`); else lines.push(` edit ${c.file ?? ""}${c.path ? ` ${c.path}` : ""}`); } for (const v of a.v1) lines.push(` old ${v.file}${v.path ? ` ${v.path}` : ""}: ${v.reason}`); } return lines.length ? lines.join("\n") : "No agents found. Run context-mode setup --list."; } /** A tiny spinner on stderr for a TTY; no escape codes (\r and spaces only), so NO_COLOR has nothing to strip. */ function spinner(ui: Ui): { start(msg: string): void; stop(): void } { const live = !ui.f.quiet && !ui.f.json && !!process.stderr.isTTY; const frames = ["|", "/", "-", "\\"]; let t: ReturnType<typeof setInterval> | undefined; let width = 0; return { start(msg) { if (!live) return; let i = 0; t = setInterval(() => { const line = `${frames[i++ % frames.length]} ${msg}`; width = Math.max(width, line.length); process.stderr.write(`\r${line}`); }, 120); }, stop() { if (t) clearInterval(t); if (t && width) process.stderr.write(`\r${" ".repeat(width)}\r`); t = undefined; width = 0; }, }; } // ---------- D6 debug report ---------- export function redact(text: string, ctx: SetupContext): string { let s = text; for (const [from, to] of [[ctx.pkgDir, "<pkg>"], [ctx.home, "~"], [os.tmpdir(), "<tmp>"]] as const) { if (from && from.length > 1) s = s.split(from).join(to); } return s; } export function fingerprint(command: string, agents: readonly AgentResult[], ctx: SetupContext): string { const key = agents.filter((a) => a.status === "FAIL") .map((a) => `${a.id}:${redact(a.reason ?? "", ctx).replace(/[0-9]+/g, "N")}`).sort().join("\n"); return createHash("sha256").update(`${command}\n${key}`).digest("hex").slice(0, 12); } export function buildIssueReport(command: string, res: SetupResult, ui: Ui): { text: string; title: string } { const fp = fingerprint(command, res.agents, ui.ctx); const failed = res.agents.filter((a) => a.status === "FAIL").map((a) => a.id); const title = `${command} FAIL: ${failed.join(", ") || "run"} (${fp})`; const lines = [ `# context-mode ${command} report`, "", "<!-- For AI agents filing this issue: keep this report whole, add the exact command you ran and what you expected. -->", "", `fingerprint: ${fp}`, `version: ${ui.env.version}`, `node: ${process.version}`, `platform: ${process.platform}-${process.arch}`, `command: context-mode ${ui.env.argv.join(" ")}`, `tty: ${process.stdin.isTTY ? "yes" : "no"}`, ...(res.error ? [`error: ${res.error}`] : []), "", "## Agents", "", "| Agent | Status | Detail |", "|---|---|---|", ...res.agents.map((a) => `| ${a.id} | ${a.status}${a.rolledBack ? " (rolled back)" : ""} | ${a.reason ?? ""} |`), "", "## Checks", "", ...res.agents.flatMap((a) => a.checks.map((c) => `- ${a.id} ${c.warn ? "WARN" : c.ok ? "ok" : "FAIL"} ${c.name}${c.detail ? `: ${c.detail}` : ""}`)), "", "## Old entries", "", ...res.agents.flatMap((a) => a.v1.map((v) => `- ${a.id} ${v.file} ${v.path}: ${v.reason}`)), "", ]; return { text: redact(lines.join("\n"), ui.ctx), title }; } function ghReady(env: SetupContext["env"]): boolean { const r = spawnSync("gh", ["auth", "status"], { env, stdio: "ignore", timeout: 10_000, windowsHide: true }); return r.status === 0; } // D-DOCTOR-ISSUE-1: the same agent-report.yml form as ctx_doctor; the URL holds the title and summary only, the // report file stays whole (gh issue create --body-file). function issueUrl(title: string, summary: string): string { return formUrl(title, summary.length > URL_BODY_MAX ? summary.slice(0, URL_BODY_MAX) : summary); } /** D6: write the redacted report; on a TTY show it and ask once; never send without a keypress. */ async function report(ui: Ui, command: string, res: SetupResult, write: boolean): Promise<void> { const { text, title } = buildIssueReport(command, res, ui); let file = ""; if (write) { const dir = path.join(dataRootOf(ui.ctx.env, ui.ctx.home), REPORT_DIR); mkdirSync(dir, { recursive: true }); file = path.join(dir, `${command}-${new Date().toISOString().replace(/[:.]/g, "-")}.md`); writeFileSync(file, text); } const gh = `gh issue create --repo ${ISSUE_REPO} --title ${JSON.stringify(title)} --label bug --body-file ${JSON.stringify(file || "<report>")}`; const p = ui.clack; if (!p) { if (ui.f.debug) err(text); if (file) err(`Debug report (redacted): ${file}`); err(`To report it: ${gh}`); return; } p.note(text, "Debug report (redacted)"); const yes = await p.confirm({ message: `Open an issue on github.com/${ISSUE_REPO} with this report?`, initialValue: false }); if (p.isCancel(yes) || !yes) { p.log.info(`Not sent.${file ? ` Report: ${file}` : ""}`); return; } if (file && ghReady(ui.ctx.env)) { const r = spawnSync("gh", ["issue", "create", "--repo", ISSUE_REPO, "--title", title, "--label", "bug", "--body-file", file], { env: ui.ctx.env, encoding: "utf8", timeout: 60_000, windowsHide: true }); if (r.status === 0) { p.log.success(`Issue opened: ${`${r.stdout}`.trim()}`); return; } p.log.warn(`gh issue create failed: ${`${r.stderr}`.trim()}`); } p.log.info(`Open this URL to file the issue (paste the report file into the form):\n${issueUrl(title, title)}`); } // ---------- apply with live checklist and Ctrl-C rollback ---------- async function apply(ui: Ui, agents: AgentId[] | undefined, dryRun: boolean): Promise<SetupResult> { const ac = new AbortController(); const onSig = (): void => { ac.abort(); // the engine rolls back the agent in progress and releases the lock, synchronously err("\nStopped with Ctrl-C; the agent in progress was rolled back."); process.exit(EXIT_SIGINT); }; if (!dryRun) process.on("SIGINT", onSig); const spin = spinner(ui); try { return await runSetup({ ...ui.ctx, agents, dryRun, signal: ac.signal, onAgent: (id, phase, r) => { if (dryRun) return; if (phase === "start") { progress(ui, `${id}: apply and verify ...`); spin.start(`${id}: verifying`); return; } spin.stop(); const line = `${id}: ${r?.status}${r?.reason ? ` (${r.reason})` : ""}`; if (ui.f.quiet) return; if (!ui.clack) err(line); else if (r?.status === "FAIL") ui.clack.log.error(line); else if (r?.status === "PASS") ui.clack.log.success(line); else ui.clack.log.warn(line); }, }); } finally { spin.stop(); process.off("SIGINT", onSig); } } async function finish(ui: Ui, command: string, res: SetupResult, writeReport: boolean): Promise<number> { if (ui.f.json) out(JSON.stringify({ command, ...res })); else if (ui.clack) ui.clack.note(table(res.agents), "Summary"); else out(table(res.agents)); if (ui.f.verbose && !ui.f.json) for (const l of verboseLines(res.agents)) err(l); if (res.error) err(`FAIL ${command}: ${res.error}. Fix: context-mode ${command}${command === "setup" ? " --repair" : ""}`); for (const l of failLines(res.agents)) err(l); if (res.exitCode !== EXIT_OK) await report(ui, command, res, writeReport); return res.exitCode; } // ---------- commands ---------- function list(ui: Ui): number { const reg = buildRegistry(ui.ctx); const detected = new Set(detectAgents(reg, ui.ctx)); const rows = ADAPTERS.map((a) => ({ id: a.id, hooks: a.hookChannel.kind, // ADR-0020: every agent has a hook channel installMode: a.installMode, detected: detected.has(a.id), })); if (ui.f.json) { out(JSON.stringify({ agents: rows })); return EXIT_OK; } out(`${"AGENT".padEnd(13)} ${"HOOKS".padEnd(11)} ${"FOUND".padEnd(9)} INSTALL`); for (const r of rows) out(`${r.id.padEnd(13)} ${r.hooks.padEnd(11)} ${(r.detected ? "detected" : "-").padEnd(9)} ${r.installMode}`); return EXIT_OK; } async function remove(ui: Ui): Promise<number> { if (!ui.f.dryRun && !ui.f.yes) { if (!ui.clack) { err(`context-mode: ${NO_TTY}`); return EXIT_USAGE; } const ok = await ui.clack.confirm({ message: "Undo every setup run and put each touched file back?", initialValue: false }); if (ui.clack.isCancel(ok)) { ui.clack.cancel("Cancelled; nothing changed."); return EXIT_SIGINT; } if (!ok) { ui.clack.outro("Nothing changed."); return EXIT_OK; } } if (ui.f.dryRun) { out(`Would restore every file recorded under ${path.join(dataRootOf(ui.ctx.env, ui.ctx.home), "backups")}`); return EXIT_OK; } const r = runRemove({ home: ui.ctx.home, env: ui.ctx.env }); if (ui.f.json) out(JSON.stringify(r)); else out(`Restored ${r.restored} file(s).`); if (r.error) err(`FAIL remove: ${r.error}. Fix: context-mode setup --remove --yes`); return r.exitCode; } /** setup --print <id>: the manual step from the same registry row setup applies; writes nothing. */ function printManual(ui: Ui, id: AgentId): number { const row = buildRegistry(ui.ctx).find((r) => r.id === id)!; const p = printPlan(row, ui.ctx.env); if (ui.f.json) out(JSON.stringify({ command: "setup", print: p })); else out(printText(p)); return EXIT_OK; } async function setup(ui: Ui): Promise<number> { const { f } = ui; if (f.print) return printManual(ui, f.print); if (f.list) return list(ui); if (f.remove) return remove(ui); // #1328 D-NODE-OLD-1: Node first, before the agent prompt and any write; one line, no rollback, no report. if (nodeTooOld(process.version)) { err(`context-mode: ${formatError("NODE_TOO_OLD", { v: process.version })}`); return EXIT_FAIL; } if (f.dryRun) { const plan = await apply(ui, f.agents, true); if (f.json) out(JSON.stringify({ command: "setup", dryRun: true, ...plan })); else out(planText(plan)); if (plan.error) err(`FAIL setup: ${plan.error}`); return plan.exitCode; } const p = ui.clack; if (!f.yes && !p) { const plan = await apply(ui, f.agents, true); if (f.json) out(JSON.stringify({ command: "setup", dryRun: true, ...plan })); else out(planText(plan)); err(`context-mode: ${NO_TTY}`); return EXIT_USAGE; } let ids = f.agents; if (p) { p.intro(`context-mode ${ui.env.version} setup`); if (!ids) { const detected = detectAgents(buildRegistry(ui.ctx), ui.ctx); const sel = await p.multiselect({ message: "Select agents to set up (space toggles, enter confirms)", options: ADAPTERS.map((a) => ({ value: a.id, label: a.id, hint: detected.includes(a.id) ? "detected" : "not found" })), initialValues: detected, required: true, }); if (p.isCancel(sel)) { p.cancel("Cancelled; nothing changed."); return EXIT_SIGINT; } ids = sel as AgentId[]; } const plan = await apply(ui, ids, true); p.note(planText(plan), "Plan"); if (!f.yes) { const ok = await p.confirm({ message: "Apply this plan?" }); if (p.isCancel(ok)) { p.cancel("Ca - src/core/compaction/candidates.ts (7126 bytes)
// ADR-0009 §2, impl/06 §1, DECISIONS-r9 M1-M5/M9. DECISIONS-r11 (A) supersedes DECISIONS-r6 D3: decision rows // are now the "decisions" section of the anchored block (last row per key wins, ADR-0009 §8.2 update-beats-duplicate). // Pure over JournalRow[] (DEVIATIONS D-M4-arch-2): no DB handle here; callers pass readSessionEvents rows. // The per-section line formats (DECISIONS-r9 M4) live here, not in render.ts: render.ts imports this file, // so a format import back from render.ts would make an import cycle (DEVIATIONS D-M4-S1-3). import { MAX_CANDIDATES, MAX_CANDIDATES_TOTAL } from "../contracts/constants.ts"; import type { Candidate, CandidateSection, JournalRow } from "../contracts/types.ts"; /** A candidate plus the `more:` query it adds when render skips it (DECISIONS-r9 M11). */ export interface SectionCandidate extends Candidate { query: string | null; // key (open errors, indexed sources), path (changed files), null (prompts) } export interface ChangedFileCandidate extends SectionCandidate { editCount: number; // count of edit rows for this path (DECISIONS-r9 M3); equal to repeatCount } /** The five sections, each in seq ascending order (impl/06 §1 Output). */ export interface CandidateSet { lastRequest: SectionCandidate | null; openErrors: SectionCandidate[]; changedFiles: ChangedFileCandidate[]; decisions: SectionCandidate[]; earlierRequests: SectionCandidate[]; indexedSources: SectionCandidate[]; } /** * DECISIONS-r9 M4: one line of the body, CR folded to a space. #1400: the first line with text, so a body * that starts with blank lines still names the request; a body with no text gives "" (as before). */ function firstLine(body: string): string { const i = body.length - body.trimStart().length; // index of the first char with text (blank lines skipped) if (i === body.length) return ""; const start = i === 0 ? 0 : body.lastIndexOf("\n", i) + 1; const nl = body.indexOf("\n", i); return (start === 0 && nl < 0 ? body : body.slice(start, nl < 0 ? body.length : nl)).replaceAll("\r", " "); } function make(section: CandidateSection, row: JournalRow, text: string, repeatCount: number, query: string | null): SectionCandidate { const bytes = Buffer.byteLength(text, "utf8"); if (bytes < 1) throw new Error("compaction: empty candidate line (DECISIONS-r9 M9)."); return { section, seq: row.seq, turn: row.turn, text, bytes, repeatCount, pinned: section === "last_request", query }; } /** impl/06 §1 step 8: keep the MAX_CANDIDATES newest (list is seq ascending). */ function capSection<T>(list: T[]): T[] { return list.length > MAX_CANDIDATES ? list.slice(list.length - MAX_CANDIDATES) : list; } function emptySet(): CandidateSet { return { lastRequest: null, openErrors: [], changedFiles: [], decisions: [], earlierRequests: [], indexedSources: [] }; } export function buildCandidates(rows: readonly JournalRow[], sessionId: string): CandidateSet { if (!sessionId) return emptySet(); // ADR-0009 §2, DECISIONS-r9 M1 const own = rows.filter((r) => r.session_id === sessionId).sort((a, b) => a.seq - b.seq); // steps 2 and 5: last request (pinned) and earlier requests. const prompts = own.filter((r) => r.kind === "prompt"); const last = prompts.length > 0 ? prompts[prompts.length - 1] : undefined; const lastRequest = last === undefined ? null : make("last_request", last, "now: " + firstLine(last.body), 1, null); const earlierRequests = prompts .slice(0, prompts.length - 1) .map((r) => make("earlier_requests", r, "asked #" + r.seq + ": " + firstLine(r.body), 1, null)); // step 3 (DECISIONS-r9 M2, F2): latest failing cmd/toolerr row per key, open unless a later row of that // key succeeded. A row with no key cannot be resolved structurally and is not a candidate (D-M4-S1-2). const failures = new Map<string, { row: JournalRow; count: number }>(); const lastOk = new Map<string, number>(); for (const r of own) { if ((r.kind !== "cmd" && r.kind !== "toolerr") || r.key === null) continue; if (r.ok === 1) { lastOk.set(r.key, r.seq); continue; } failures.set(r.key, { row: r, count: (failures.get(r.key)?.count ?? 0) + 1 }); } const openErrors: SectionCandidate[] = []; for (const [key, f] of failures) { if ((lastOk.get(key) ?? 0) > f.row.seq) continue; openErrors.push(make("open_errors", f.row, "error #" + f.row.seq + " " + (f.row.tool ?? "") + ": " + key, f.count, key)); } openErrors.sort((a, b) => a.seq - b.seq); // step 4 (DECISIONS-r9 M3): last write wins per path, repeatCount = edit rows for that path. const edits = new Map<string, { row: JournalRow; count: number }>(); for (const r of own) { if (r.kind !== "edit" || r.path === null) continue; edits.set(r.path, { row: r, count: (edits.get(r.path)?.count ?? 0) + 1 }); } const changedFiles: ChangedFileCandidate[] = []; for (const [path, e] of edits) { const c = make("changed_files", e.row, "edited " + path + " x" + e.count, e.count, path); changedFiles.push({ ...c, editCount: e.count }); } changedFiles.sort((a, b) => a.seq - b.seq); // DECISIONS-r11 (A): one candidate per decision key, the latest row wins, repeatCount = rows of that key. // The line is the body's first line ("Q: ... → A: ..." or "A: <label>"); the key is the more: query. const decided = new Map<string, { row: JournalRow; count: number }>(); for (const r of own) { if (r.kind !== "decision" || r.body === "") continue; const key = r.key ?? r.body; decided.set(key, { row: r, count: (decided.get(key)?.count ?? 0) + 1 }); } const decisions: SectionCandidate[] = []; for (const [key, d] of decided) decisions.push(make("decisions", d.row, "decided #" + d.row.seq + ": " + firstLine(d.row.body), d.count, key)); decisions.sort((a, b) => a.seq - b.seq); // step 6: one candidate per index row. const indexedSources = own .filter((r) => r.kind === "index") .map((r) => make("indexed_sources", r, "indexed " + (r.key ?? ""), 1, r.key)); // step 8 (per section), then step 9 (total, DECISIONS-r9 M5); the pinned last request is never dropped. const set: CandidateSet = { lastRequest, openErrors: capSection(openErrors), changedFiles: capSection(changedFiles), decisions: capSection(decisions), earlierRequests: capSection(earlierRequests), indexedSources: capSection(indexedSources), }; const rest = [...set.openErrors, ...set.changedFiles, ...set.decisions, ...set.earlierRequests, ...set.indexedSources]; const total = rest.length + (lastRequest === null ? 0 : 1); if (total <= MAX_CANDIDATES_TOTAL) return set; const drop = new Set(rest.map((c) => c.seq).sort((a, b) => a - b).slice(0, total - MAX_CANDIDATES_TOTAL)); return { lastRequest, openErrors: set.openErrors.filter((c) => !drop.has(c.seq)), changedFiles: set.changedFiles.filter((c) => !drop.has(c.seq)), decisions: set.decisions.filter((c) => !drop.has(c.seq)), earlierRequests: set.earlierRequests.filter((c) => !drop.has(c.seq)), indexedSources: set.indexedSources.filter((c) => !drop.has(c.seq)), }; } - src/core/compaction/recall.ts (5098 bytes)
// DECISIONS-r11 (B) turn-boundary recall ("push, not pull"). After a compaction a model does not call a // tool for state it does not know it lost (0 of 50 clean T-CMP sessions), so the hook pushes the rows the // next prompt asks about. Pure over JournalRow[]: BM25 (rankTexts, the store's tokenizer) of each row's // text against the prompt; whole rows only, never cut; nothing when the top score is under RECALL_MIN_SCORE. import { MMR_REDUNDANCY_WEIGHT, MMR_RELEVANCE_WEIGHT, RECALL_BUDGET_BYTES, RECALL_CLOSE_TAG, RECALL_MIN_SCORE, RECALL_OPEN_TAG } from "../contracts/constants.ts"; import type { JournalRow, UnitCandidate } from "../contracts/types.ts"; import { rankTexts } from "../store/fts.ts"; import { wordTokens } from "../store/words.ts"; export interface Recall { text: string; // "" = inject nothing seqs: number[]; // rows injected, seq ascending units?: string[]; // r3-ledger: line units injected, "sourceId:ord" (absent when none) } export function unitKey(u: UnitCandidate): string { return u.sourceId + ":" + u.ord; } /** One whole unit: "@label line N:" then the unit (ancestors + line), never cut. */ export function unitLine(u: UnitCandidate): string { return "@" + u.label + " line " + (u.ord + 1) + ":\n" + u.body; } function wordsOf(s: string): Set<string> { return new Set(wordTokens(s.toLowerCase())); } function overlap(a: Set<string>, b: Set<string>): number { let n = 0; for (const w of a) if (b.has(w)) n++; return a.size + b.size - n === 0 ? 0 : n / (a.size + b.size - n); } /** * MMR (lambda 0.7) over ranked units: each step takes the unit with the best * 0.7 * score/top - 0.3 * max word overlap with the units already taken, whole units only, while it fits. */ export function pickUnits(cands: readonly UnitCandidate[], seen: ReadonlySet<string>, budget: number): UnitCandidate[] { const pool = cands.filter((u) => !seen.has(unitKey(u)) && u.score >= RECALL_MIN_SCORE); if (pool.length === 0) return []; const top = Math.max(...pool.map((u) => u.score)); const words = pool.map((u) => wordsOf(u.body)); const taken: number[] = []; const left = new Set(pool.map((_, i) => i)); let used = 0; while (left.size > 0) { let best = -1; let bestVal = -Infinity; for (const i of left) { let sim = 0; for (const j of taken) sim = Math.max(sim, overlap(words[i] as Set<string>, words[j] as Set<string>)); const val = MMR_RELEVANCE_WEIGHT * ((pool[i] as UnitCandidate).score / top) - MMR_REDUNDANCY_WEIGHT * sim; if (val > bestVal) { bestVal = val; best = i; } } left.delete(best); const cost = bytesOf(unitLine(pool[best] as UnitCandidate)) + 1; if (used + cost > budget) continue; // skip, a smaller unit may still fit used += cost; taken.push(best); } return taken.map((i) => pool[i] as UnitCandidate); } const NONE: Recall = { text: "", seqs: [] }; function bytesOf(s: string): number { return Buffer.byteLength(s, "utf8"); } /** The row's searchable text: key, path and body, as stored. */ function textOf(r: JournalRow): string { return [r.key ?? "", r.path ?? "", r.body].filter((t) => t !== "").join("\n"); } /** One whole row: "#seq kind tool: text". The text is never cut (a row that does not fit is skipped). */ export function recallLine(r: JournalRow): string { return "#" + r.seq + " " + r.kind + (r.tool === null ? "" : " " + r.tool) + ": " + textOf(r); } /** * rows: candidates (any order); prompt: this turn's text; seen: seqs already injected in this session. * The current prompt's own row (kind "prompt", same body) is never a candidate. */ export function pickRecall(rows: readonly JournalRow[], prompt: string, seen: ReadonlySet<number>, units: readonly UnitCandidate[] = [], seenUnits: ReadonlySet<string> = new Set()): Recall { if (prompt.trim() === "") return NONE; const pool = rows.filter((r) => !seen.has(r.seq) && r.kind !== "cost" && !(r.kind === "prompt" && r.body === prompt) && textOf(r) !== ""); const scores = pool.length === 0 ? [] : rankTexts(pool.map(textOf), prompt, "any"); const order = pool .map((r, i) => ({ r, score: scores[i] as number })) .filter((x) => x.score >= RECALL_MIN_SCORE) .sort((a, b) => b.score - a.score || b.r.seq - a.r.seq); let used = bytesOf(RECALL_OPEN_TAG) + 1 + bytesOf(RECALL_CLOSE_TAG); const taken: JournalRow[] = []; for (const { r } of order) { const cost = bytesOf(recallLine(r)) + 1; if (used + cost > RECALL_BUDGET_BYTES) continue; // skip, a smaller row may still fit used += cost; taken.push(r); } // r3-ledger: the rest of the budget goes to line units of large outputs (a row over budget is skipped above). const picked = pickUnits(units, seenUnits, RECALL_BUDGET_BYTES - used); if (taken.length === 0 && picked.length === 0) return NONE; taken.sort((a, b) => a.seq - b.seq); const lines = [...taken.map(recallLine), ...picked.map(unitLine)]; return { text: [RECALL_OPEN_TAG, ...lines, RECALL_CLOSE_TAG].join("\n"), seqs: taken.map((r) => r.seq), ...(picked.length > 0 ? { units: picked.map(unitKey) } : {}) }; } - src/core/compaction/render.ts (5789 bytes)
// ADR-0009 §4-§5, impl/06 §3, impl/00 §4 renderState(rows, turn) (DEVIATIONS D-M4-arch-2), DECISIONS-r6 D1, // DECISIONS-r9 M8/M10-M13/M25. Pure: same rows -> same bytes; result <= STATE_BUDGET UTF-8 bytes. // No line is ever cut: a line over POINTER_MIN becomes a ctx_resume(seq) pointer line. import { POINTER_MIN, RATIO_SECTION_DECAY, STATE_BUDGET, STATE_CLOSE_TAG } from "../contracts/constants.ts"; import type { CandidateSection, JournalRow } from "../contracts/types.ts"; import { buildCandidates, type SectionCandidate } from "./candidates.ts"; import { scoreCandidates } from "./score.ts"; import { pickUnits, unitLine } from "./recall.ts"; import type { UnitCandidate } from "../contracts/types.ts"; /** * D-CR3-RESUME-1: ctx_resume extras. `sources`: one line per stored source of the session, best first * ("source <short id>: <label> (<bytes> B)"); `units`: ranked line units for the session goal, labelled by * short id. Both take only the budget the journal lines leave, whole lines, before the more: line. */ export interface StateExtras { sources: readonly string[]; units: readonly UnitCandidate[] } type Scored = SectionCandidate & { score: number }; function bytesOf(s: string): number { return Buffer.byteLength(s, "utf8"); } /** ADR-0009 §4, DECISIONS-r9 M10. */ // D-HL-NAMES-1: `prefix` is the host's toolNamePrefix; tool names in the block are the names the host calls. function lineOf(c: SectionCandidate, prefix: string): string { return c.bytes > POINTER_MIN ? "#" + c.seq + " (" + c.bytes + " B) " + prefix + "ctx_resume(seq:" + c.seq + ")" : c.text; } function moreLine(queries: readonly string[], prefix: string): string { return "more: " + prefix + "ctx_search(queries:" + JSON.stringify(queries) + ', scope:"session")'; } /** * The session is the one of the newest row (highest seq); rows of any other session are ignored * (GP6 "no foreign session rows"). Callers pass readSessionEvents rows, so this is one session (D-M4-S1-1). */ export function renderState(rows: readonly JournalRow[], turn: number, extras?: StateExtras, prefix = ""): string { let newest: JournalRow | undefined; for (const r of rows) if (newest === undefined || r.seq > newest.seq) newest = r; const sessionId = newest === undefined ? "" : newest.session_id; const upto = newest === undefined || sessionId === "" ? 0 : newest.seq; const set = buildCandidates(rows, sessionId); // step 2 (DECISIONS-r9 M12): reserve the wrapper and an empty more: line before any item. const openTag = `<context_mode_state session="${sessionId}" upto="${upto}">`; const emptyMoreBytes = bytesOf(moreLine([], prefix)); const budget = STATE_BUDGET - (bytesOf(openTag) + 1 + emptyMoreBytes + 1 + bytesOf(STATE_CLOSE_TAG)); let used = 0; const pinnedLine = set.lastRequest === null ? null : lineOf(set.lastRequest, prefix); if (pinnedLine !== null) used += bytesOf(pinnedLine) + 1; // always taken first // steps 3-5: budgeted lazy greedy (ADR-0009 §4, DECISIONS-r6 D1). Each pick takes the best current // ratio = score * RATIO_SECTION_DECAY^k / bytes (k = lines already taken from that section); ties go to // the higher seq (M25). A line that does not fit is skipped; smaller ones may still fit (D-M4-S1-4). const remaining: Scored[] = scoreCandidates( [...set.openErrors, ...set.changedFiles, ...set.decisions, ...set.earlierRequests, ...set.indexedSources], turn, ); const k = new Map<CandidateSection, number>(); const taken: Scored[] = []; const skipped: Scored[] = []; while (remaining.length > 0) { let best = 0; let bestRatio = -Infinity; for (let i = 0; i < remaining.length; i++) { const c = remaining[i] as Scored; const ratio = (c.score * RATIO_SECTION_DECAY ** (k.get(c.section) ?? 0)) / c.bytes; if (ratio > bestRatio || (ratio === bestRatio && c.seq > (remaining[best] as Scored).seq)) { best = i; bestRatio = ratio; } } const c = remaining.splice(best, 1)[0] as Scored; const lineBytes = bytesOf(lineOf(c, prefix)) + 1; if (used + lineBytes <= budget) { used += lineBytes; taken.push(c); k.set(c.section, (k.get(c.section) ?? 0) + 1); } else { skipped.push(c); } } // step 6: fixed section order, seq ascending inside a section. DECISIONS-r11 (A): goal (now:), open errors, // edited files, decisions, then earlier requests and indexed sources. const lines: string[] = [openTag]; if (pinnedLine !== null) lines.push(pinnedLine); for (const section of ["open_errors", "changed_files", "decisions", "earlier_requests", "indexed_sources"] as const) { for (const c of taken.filter((t) => t.section === section).sort((a, b) => a.seq - b.seq)) lines.push(lineOf(c, prefix)); } // D-CR3-RESUME-1: sources by short id, then line units (pickUnits: MMR, whole units, the budget left). if (extras !== undefined) { for (const l of extras.sources) { const b = bytesOf(l) + 1; if (used + b > budget) continue; // skip, a shorter line may still fit used += b; lines.push(l); } for (const u of pickUnits(extras.units, new Set(), budget - used)) { const l = unitLine(u); used += bytesOf(l) + 1; lines.push(l); } } // step 7 (DECISIONS-r9 M11-M12): queries of skipped items, dedup, seq ascending, added while they fit. const queries: string[] = []; const seen = new Set<string>(); for (const c of skipped.sort((a, b) => a.seq - b.seq)) { if (c.query === null || seen.has(c.query)) continue; if (bytesOf(moreLine([...queries, c.query], prefix)) - emptyMoreBytes > budget - used) break; queries.push(c.query); seen.add(c.query); } lines.push(moreLine(queries, prefix), STATE_CLOSE_TAG); return lines.join("\n"); } - src/core/compaction/score.ts (2208 bytes)
// ADR-0009 §3, impl/06 §2, DECISIONS-r6 D1, DECISIONS-r9 M6/M7. Integers only: // score = Math.round(WEIGHT[w] * DECAY_X1000[min(age, 127)] * bonus / DECAY_SCALE), bonus = 1 + floor(log2(repeat)). import { DECAY_SCALE, DECAY_X1000, WEIGHT } from "../contracts/constants.ts"; import type { Candidate, CandidateSection } from "../contracts/types.ts"; export type WeightKey = keyof typeof WEIGHT; export interface ScoreInput { section: WeightKey; // the weight row: toolerr, decision, prompt, edit, index (cost has none; decision since DECISIONS-r11) currentTurn: number; itemTurn: number; repeatCount: number; } export function scoreCandidate(input: ScoreInput): number { if (!Object.hasOwn(WEIGHT, input.section)) { throw new Error(`compaction: "${String(input.section)}" has no weight; only toolerr, decision, prompt, edit and index rows are scored (ADR-0009 §3, DECISIONS-r11).`); } const age = Math.max(0, input.currentTurn - input.itemTurn); // impl/06 §2 step 2: a negative age clamps to 0 const decay = DECAY_X1000[Math.min(age, DECAY_X1000.length - 1)] as number; // DECISIONS-r9 M6 let bonus = 1; // 1 + floor(log2(repeatCount)), by halving: integer only for (let n = Math.max(1, input.repeatCount); n > 1; n >>= 1) bonus += 1; return Math.round((WEIGHT[input.section] * decay * bonus) / DECAY_SCALE); // DECISIONS-r9 M7: one round at the end } /** impl/06 §2 step 1: section -> weight row. */ function weightKey(section: CandidateSection): WeightKey { switch (section) { case "last_request": case "earlier_requests": return "prompt"; case "open_errors": return "toolerr"; case "changed_files": return "edit"; case "decisions": return "decision"; case "indexed_sources": return "index"; } } /** impl/06 §2 step 8: same order, score attached. Pinning is a selection rule (render.ts), not a score. */ export function scoreCandidates<T extends Candidate>(candidates: readonly T[], currentTurn: number): Array<T & { score: number }> { return candidates.map((c) => ({ ...c, score: scoreCandidate({ section: weightKey(c.section), currentTurn, itemTurn: c.turn, repeatCount: c.repeatCount }), })); } - src/core/contracts/agents.ts (365 bytes)
// impl/01 §1, impl/00 §3.1, docs/architecture/PRD.md §3 (agent table, top to bottom; omp 11th per ADR-0026). Data only. export const AGENT_IDS = ["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode","omp"] as const; // TECH-SPEC §2; omp is the 11th (ADR-0026, D-OMP-ROW-1) export type AgentId = typeof AGENT_IDS[number];
- src/core/contracts/client-map.ts (1822 bytes)
/** * contracts/client-map — MCP clientInfo.name → PlatformId mapping. * * Source: Apify MCP Client Capabilities Registry * https://github.com/apify/mcp-client-capabilities * * Only includes platforms we have adapters for. */ // Local string type: v2 does not import the v1 PlatformId (W0-client-map). // v1 src/adapters/detect.ts keeps its own copy of this table until W3. type PlatformId = string; export const CLIENT_NAME_TO_PLATFORM: Record<string, PlatformId> = { "claude-code": "claude-code", "gemini-cli-mcp-client": "gemini-cli", "antigravity-client": "antigravity", "antigravity-cli": "antigravity-cli", "agy": "antigravity-cli", "cursor-vscode": "cursor", "Visual-Studio-Code": "vscode-copilot", "copilot-cli": "copilot-cli", "GitHub Copilot CLI": "copilot-cli", "github-copilot-cli": "copilot-cli", "JetBrains Client": "jetbrains-copilot", "IntelliJ IDEA": "jetbrains-copilot", "PyCharm": "jetbrains-copilot", "Codex": "codex", "codex-mcp-client": "codex", "Kilo Code": "kilo", // #1276: OpenCode sends clientInfo.name = "opencode". v2 routing still takes the agent id // from --agent (ADR-0007 decision 4); this row is for detection/display only. "opencode": "opencode", "Kiro CLI": "kiro", "Pi CLI": "pi", "Pi Coding Agent": "pi", // Issue #542 — Pi rebranded to OMP. Upstream // refs/platforms/oh-my-pi/packages/coding-agent/src/mcp/client.ts:46-49 // ships clientInfo.name = "omp-coding-agent". Resolved to the OMP // adapter (~/.omp/, PI_CODING_AGENT_DIR). Legacy "Pi CLI" / // "Pi Coding Agent" entries above still resolve to the pi adapter. "omp-coding-agent": "omp", "Zed": "zed", "zed": "zed", "qwen-code": "qwen-code", "qwen-cli-mcp-client": "qwen-code", "kimi-code": "kimi", "kimi": "kimi", "Kimi Code": "kimi", }; - src/core/contracts/constants.ts (100870 bytes)
// impl/01 §3, impl/00 §3.2, TECH-SPEC §11, DECISIONS-r9. Every constant lives here; no other module writes these literals. import type { AgentId } from "./agents.js"; export const SERVER_KEY = "context-mode"; // TECH-SPEC §3.8 rule 3 export const TOOL_ORDER = Object.freeze(["ctx_execute","ctx_batch","ctx_index","ctx_search","ctx_resume","ctx_stats","ctx_doctor","ctx_upgrade","ctx_purge"] as const); // PRD §8, Q3b /** D-HL-NAMES-1: a fixed hook text with each own tool name as the host calls it (prefix + name), by split/join. */ export function prefixToolNames(text: string, prefix: string): string { if (prefix === "") return text; let out = text; for (const name of TOOL_ORDER) out = out.split(name).join(prefix + name); return out; } // Byte caps export const OUTPUT_CAP = 16384; // Q2, ADR-0008, ADR-0016: one cap for replies, replace path and Read deny threshold // D-EXEC-PREVIEW-1: a ctx_execute reply for output that does not fit OUTPUT_CAP is a preview of at most this many bytes; // the whole output is indexed and the reply ends with the ctx_search call that reaches the rest. export const EXEC_PREVIEW_BYTES = 4096; export const STATE_BUDGET = 2048; // ADR-0009 §4 export const RESUME_CAP = 2048; // ADR-0009, GP6 export const REPORT_CAP = 4096; // ADR-0014 export const POINTER_MIN = 640; // ADR-0009 §4 export const STATE_CLOSE_TAG = "</context_mode_state>"; // impl/06 §3 block close line export const INDEX_WRITE_CHUNK = 1048576; // PRD §4 export const SYNC_INDEX_MAX_BYTES = 65536; // DECISIONS-r9 F1 // D-M7-SV-1: the PostToolUse replace path has its own sizes, separate from OUTPUT_CAP (which stays the cap for // replies and the Read deny threshold). A result over REPLACE_TRIGGER_BYTES is indexed whole and the model gets // whole BM25-selected chunks of at most REPLACE_CHUNK_BYTES each, within REPLACE_RETURN_BYTES, plus the more line. // D-R48-TRIGGER-1 (#1326 coreycoburn): a documented setting, env CTX_REPLACE_TRIGGER_BYTES (a positive safe integer), // read once at process start; default 4096. Bench (bench/replay.mjs, 602 files, 28,390 calls, 37.9 MB): trigger 4096 // saves 41.99% (1,878 replaces), 6144 saves 30.89% (998), 8192 saves 23.34% (582): raising it costs a quarter to // half of the saving, so the default stays; a user who wants 2-6 KB outputs whole sets the env var. export const REPLACE_TRIGGER_BYTES_DEFAULT = 4096; export const REPLACE_TRIGGER_ENV = "CTX_REPLACE_TRIGGER_BYTES"; export function readReplaceTrigger(raw: string | undefined): number { if (raw === undefined || raw.trim() === "") return REPLACE_TRIGGER_BYTES_DEFAULT; const n = Number(raw); return Number.isSafeInteger(n) && n > 0 ? n : REPLACE_TRIGGER_BYTES_DEFAULT; } export const REPLACE_TRIGGER_BYTES = readReplaceTrigger(process.env[REPLACE_TRIGGER_ENV]); // D-R41-READ-OFFSET-1 (#1314): a read-like tool (canonical name) called with a range key is the user's own window: // PostToolUse lets it through whole. Claude Code, Pi, Gemini: offset/limit; VS Code read_file and Copilot view map to them. export const RANGE_READ_TOOLS = Object.freeze(["Read", "view"]); export const READ_RANGE_KEYS = Object.freeze(["offset", "limit", "view_range"]); // D-1404-SKILL-LOAD-1 (#1404): a skill-load tool (canonical name) returns a skill's instructions, which the model must // read whole: PostToolUse lets it through. Claude Code calls it Skill (its PostToolUse matcher leaves it out); OpenCode's // native `skill` maps to it. Every other tool output over the trigger keeps the replace. export const SKILL_LOAD_TOOLS = Object.freeze(["Skill"]); export const REPLACE_RETURN_BYTES = 96; // D-M7-SV-3: was 512 (D-M7-SV-2), 1024 before; sweeps in DEVIATIONS // D-M2-JSON-1: a parser-found shape digest (schema, counts, whole rows) has its own budget, independent of the handle line. export const SHAPE_RETURN_BYTES = 256; export const REPLACE_CHUNK_BYTES = 48; // D-M7-SV-3: was 256; two whole chunks fit in the return budget // D-CR3-HANDLE-1: the last line of every replacement (it replaces the more line and the D-CR2-HANDLE-1 line). // One short line: the exact call over the stored source by its short id, then the full size. // D-R4-HANDLE-LABEL-1: no label text; the short id is the only name the line carries. // D-HL-NAMES-1: the tool name carries the host's toolNamePrefix; the intent is never rewritten. // D-HA-GEMINI-HINT-1: `asked` (prompt words the output holds) is a second query; the intent query stays as is. export function REPLACE_HANDLE_LINE(intent: string, handle: string, bytes: number, prefix = "", asked = ""): string { const queries = asked === "" ? [intent] : [intent, asked]; return prefix + "ctx_search({queries:[" + queries.map((q) => JSON.stringify(q)).join(",") + "], source:" + JSON.stringify(handle) + "}) searches the whole output (" + bytes + " B)."; } // D-CC-POINTER-1 (#1342, ADR-0016 line 16): the handle line of a subagent replace in case B or C. It names no ctx // tool (the subagent cannot call one). It states the size and the short id; it names Read with offset and limit // only when the subagent has Read and the call was a read. export function SUBAGENT_HANDLE_LINE(handle: string, bytes: number, read: boolean): string { return "The full output (" + bytes + " B) is stored as " + handle + "; above is the best-matching part." + (read ? " Read the file with offset and limit for other lines." : ""); } // D-CC-POINTER-2 (#1358, #1342): the MCP-free twin of the search call, for a caller with a shell on the claude-code // row. search.mjs takes the short id and the project dir, so it works from any cwd and with no MCP server. // D-CC-POINTER-5: every word is a POSIX single-quoted word, so the shell runs no $( ), backtick or $VAR in it. export function SEARCH_TWIN_LINE(searchPath: string, handle: string, terms: string, projectDir: string): string { return " Or run: node " + shellWord(searchPath) + " " + handle + " " + shellWord(terms) + " " + shellWord(projectDir); } // D-CC-POINTER-6 (#1406): Claude Code kept the whole output in this file (D-M2-SHAPE-2) and the replace drops the host's // persistedOutputPath field, so the pointer names the file. A Read with offset and limit passes whole // (D-R41-READ-OFFSET-1), so the caller pages through the output in order. export function PERSISTED_FILE_LINE(file: string): string { return " The whole output is also in " + JSON.stringify(file) + "; Read it with offset and limit."; } // D-CC-POINTER-5: one POSIX shell word. Inside single quotes sh, bash and Git Bash expand nothing; a ' closes the // quote, adds an escaped ', and opens it again. export function shellWord(s: string): string { return "'" + s.split("'").join("'\\''") + "'"; } export const HANDLE_PROMPT_WORDS = 3; // D-HA-GEMINI-HINT-1: prompt words the handle-line query may add export const MAX_CHUNK_BYTES = 4096; // DECISIONS-r9 §C export const SEARCH_PAGE_SIZE = 20; // ADR-0009 §8.1 rule 3; DECISIONS-r9 M15 // D-UNIFIED-MEMORY-1, D-MEMORY-SOURCE-1: the prefix a memory file's label carries in a reply ("memory AGENTS.md #0"). export const MEMORY_LABEL_PREFIX = "memory "; export const SEARCH_REPLY_HITS = 5; // D-SEARCH-REPLY-1: hits in one ctx_search relevance reply; `More:` pages the rest (SEARCH_PAGE_SIZE stays the decision-list page) export const SNIPPET_MAX_BYTES = 800; // DECISIONS-r9 M21: under floor(OUTPUT_CAP / SEARCH_PAGE_SIZE) = 819 export const SNIPPET_CODE_MAX_BYTES = 2048; // D-SEARCH-7: a whole fenced block up to this; 7 fit one OUTPUT_CAP reply export const READ_MAX_LINES = 200; // DECISIONS-r8: hint text only, never enforced (READ_HINT_BYTES retired) // Prompt surface (chars) export const INSTRUCTIONS_CAP = 2048; // Q5 export const DESCRIPTION_CAP = 1024; // Q5 export const SURFACE_CAP = 8000; // Q5, Q13 // Compaction scoring (ADR-0009, DECISIONS-r6 D1, DECISIONS-r9 §C) export const MAX_CANDIDATES = 85; // per section, ADR-0009 §3 export const MAX_CANDIDATES_TOTAL = 340; // ADR-0009 §4 // DECISIONS-r11 (A): decision rows score (700: under an open error, over a prompt); they were never candidates before. export const WEIGHT: Readonly<Record<"toolerr" | "decision" | "prompt" | "edit" | "index", number>> = Object.freeze({ toolerr: 900, decision: 700, prompt: 500, edit: 400, index: 200 }); export const DECAY_HALF_LIFE_TURNS = 4; export const RATIO_SECTION_DECAY = 0.7; // r3-ledger pickUnits (recall.ts): MMR picks by relevance (0.7) minus redundancy (0.3), lambda 0.7. export const MMR_RELEVANCE_WEIGHT = 0.7; export const MMR_REDUNDANCY_WEIGHT = 0.3; // DECAY_X1000[age] = round(1000 * (0.25 + 0.75 * 2^(-age / DECAY_HALF_LIFE_TURNS))), ages 0..127. // DECISIONS-r9 M6 (later than impl/01 A-C1 "0-64, computed at load") wins: a literal, checked-in 128-entry // integer table; the unit test recomputes the formula; callers clamp age > 127 to entry 127. export const DECAY_X1000: readonly number[] = Object.freeze([ 1000,881,780,696,625,565,515,473,438,408,383,361,344,329,316,306, 297,289,283,278,273,270,267,264,262,260,258,257,256,255,254,253, 253,252,252,252,251,251,251,251,251,251,251,250,250,250,250,250, 250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250, 250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250, 250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250, 250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250, 250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250, ]); export const COMPACT_POINTER_LINE = 'context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").'; // DECISIONS-r6 D6; byte-stable export const RRF_K = 60; // ADR-0009 §8.3/§9, DECISIONS-r7 R1, DECISIONS-r9 M20 export const SEARCH_P95_MS = 30; // ADR-0009 §9, DECISIONS-r7 R5 // D-CR3-HANDLE-1: a source handle is SOURCE_ID_PREFIX plus at most this many base-36 digits (parseSourceHandle). export const SOURCE_HANDLE_MAX_DIGITS = 10; // Time budgets (ms) export const EXEC_TIMEOUT_MS = 600000; // S-TIMEOUT, Q8: default and max export const KILL_GRACE_MS = 1000; // GP4 // D-1337-EXIT-SETTLE-1 (#1337): after the child exits, runProcess waits this long for the pipes to end; each data chunk restarts it. export const PIPE_EOF_GRACE_MS = 250; // D-1337-EXIT-SETTLE-1: the most time the pipe drain may take after exit, so a survivor that keeps writing cannot hold the call. export const PIPE_DRAIN_MAX_MS = 2000; export const DB_TIMEOUT_MS = 5000; // ADR-0002, PRD §4 // D-1401-SPOOL-1 (#1401): a hook process waits at most this long for the write lock, then puts the write in the // project spool. The host kills a hook at HOOK_TIMEOUT_MS, so a hook never waits DB_TIMEOUT_MS. export const HOOK_BUSY_MS = 250; export const HOOK_SPOOL_DIR = "pending"; // D-1401-SPOOL-1: <projectDir>/pending, one JSON file per waiting write // D-1401-SPOOL-1: a claimed spool file older than this has no live drainer (the host killed it); another hook takes it. export const SPOOL_CLAIM_STALE_MS = 30000; // D-1401-SPOOL-1: the most time one hook spends writing spool files into the store; the rest waits for the next hook. export const SPOOL_DRAIN_MS = 1000; export const DB_WAL_SUFFIX = "-wal"; // impl/02 §6.1 step 4, DEVIATIONS D-M1-T5-1: WAL sibling of context.db export const DB_SHM_SUFFIX = "-shm"; // impl/02 §6.1 step 4, DEVIATIONS D-M1-T5-1: shared-memory sibling of context.db export const DB_TMP_SUFFIX = ".tmp"; // DEVIATIONS D-M2-CI-3: private build name of a new context.db before linkSync publishes it // DEVIATIONS D-1385-NOLINK-1: link() codes that mean "this file system has no hard links" (Android f2fs, some FUSE/SMB mounts). export const DB_LINK_DENIED_CODES: readonly string[] = ["EACCES", "EPERM", "ENOSYS", "ENOTSUP", "EOPNOTSUPP"]; export const DB_PUBLISH_CLAIM_SUFFIX = ".publish"; // D-1385-NOLINK-1: mkdir claim; its holder alone renames the temp DB into place // D-1385-NOLINK-2: Windows answers mkdir with EPERM while another process removes the same claim dir. export const DB_CLAIM_BUSY_CODES: readonly string[] = ["EEXIST", "EPERM"]; export const DB_PUBLISH_POLL_MS = 5; // D-1385-NOLINK-1: a creator that lost the claim checks for the published file this often export const SQLITE_PRIMARY_CODE_MASK = 255; // DEVIATIONS D-M1-T5-1: extended result code -> primary code (low byte) export const SQLITE_CORRUPT_CODE = 11; // impl/02 §6.1 error cases: SQLITE_CORRUPT -> DB_CORRUPT export const SQLITE_NOTADB_CODE = 26; // DEVIATIONS D-M1-T5-1: SQLITE_NOTADB (garbage file) -> DB_CORRUPT export const HOOK_P95_MS = 40; // GS6, DECISIONS-r9 V14: Claude Code wall export const HOOK_CPU_OVER_NODE_MS = 20; // GS6: command hooks, CPU over bare Node export const HOOK_COMBINED_P95_MS = 60; // GS6, A31: command hooks, wall export const HOOK_TIMEOUT_MS = 5000; // impl/10 A2: hookTimeoutMs for spawn-based agents export const EXIT_SIGTERM_MS = 2000; // GP9, #862 export const EXIT_SIGKILL_MS = 5000; // GP9, #862 export const GP9_EXIT_MS = 2000; // impl/14 harness lifecycle budget; TECH-SPEC GP9 "exit < 2 s" export const COLD_START_MS = 1000; // GP4 export const TOOLS_TTL_MS = 3600000; // ADR-0007 (A1) export const IN_PROCESS_TIMEOUT_MS = 0; // impl/10 §1.3: pi/opencode hookTimeoutMs "n/a (in-process, no spawn)" export const MS_PER_DAY = 86400000; // DEVIATIONS D-M1-3: day-to-ms factor for the retention cutoffs // Store (impl/02 §0; DEVIATIONS D-M1-3: impl/00 names NODE_MIN and INDEX_WRITE_CHUNK cover the rest) export const PROJECT_KEY_HEX_LEN = 16; // impl/00 A5: first 16 hex chars of sha256(git common dir realpath) export const SCHEMA_VERSION = 6; // ADR-0002 decision 2: PRAGMA user_version; 2 = cost dedup index (D-M5-arch-2); 3 = chunks title + porter (D-SEARCH-3); 4 = trigram table + vocab (D-SEARCH-4); 5 = line_units (r3-ledger); 6 = path labels with forward slashes (D-PATH-LABEL-1) export const RETENTION_IDLE_DAYS = 30; // impl/02 A-S1: row-level, age since last access export const RETENTION_SIZE_CAP_BYTES = 524288000; // impl/02 A-S2 (Q7b): 500 MB per project export const PROJECT_DEAD_IDLE_DAYS = 14; // DECISIONS-r9 V22 (#1024): project-level sweep, dead owner export const PROJECTS_DIR_NAME = "projects"; // PRD §4: <DATA_ROOT>/projects/<projectKey>/ export const DB_FILE_NAME = "context.db"; // PRD §4: one SQLite file per project export const OWNERS_DIR_NAME = "owners"; // impl/02 §7, DEVIATIONS D-M1-T6-1: <projectDir>/owners/<serverId>.pid export const OWNER_PID_EXT = ".pid"; // impl/02 §7, DEVIATIONS D-M1-T6-1: owner file extension export const GIT_DIR_NAME = ".git"; // DEVIATIONS D-M1-T3-3: containmentRoot of a non-bare repo export const GIT_WORKTREE_LINE_PREFIX = "worktree "; // DEVIATIONS D-M2-R7-1: `git worktree list --porcelain` path line export const GITDIR_FILE_PREFIX = "gitdir: "; // D-M3-F-4: a .git file (linked worktree, submodule) names its git dir export const GIT_COMMONDIR_FILE = "commondir"; // D-M3-F-4: <gitdir>/commondir of a linked worktree export const GIT_HEAD_FILE = "HEAD"; // D-M3-F-4: a git dir has a HEAD file export const WORKSPACE_FOLDER_FLAG = "--wor - src/core/contracts/errors.ts (3906 bytes)
// impl/01 §4, impl/00 §3.3. Every error is one line: "<cause>. Fix: <action>" (P1, PRD §13). export type ErrorCode = | "NODE_TOO_OLD" | "NO_SQLITE" | "DB_GONE" | "NO_PROJECT" | "UNKNOWN_FIELD" | "TIMEOUT" | "NO_RUNTIME" | "FETCH_FAILED" | "SSRF" | "OUTSIDE_ROOT" | "INVALID_ARGS" | "ONE_OF_INPUT" | "SPAWN_FAILED" | "DB_CORRUPT" | "SCHEMA_STALE" | "NO_GIT_DIR" | "NO_HOME" // store additions, DEVIATIONS D-M1-2 | "NO_GIT_BASH" | "PLUGIN_ROOT_MISSING" | "BUNDLE_HASH_MISMATCH" | "CONFIG_PARSE_FAILED"; // tools-ops additions, impl/07 A-T2 export const ERROR_TEXT: Readonly<Record<ErrorCode, string>> = Object.freeze({ NODE_TOO_OLD: "Context Mode needs Node 24.15.0 or newer; you have <v>. Fix: nvm install 24, or install it from https://nodejs.org.", // #1328 D-NODE-OLD-1 NO_SQLITE: "node:sqlite failed to load. Fix: run ctx_doctor.", DB_GONE: "context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.", // D-ORPHAN-WAL-1 NO_PROJECT: "Project source <kind> is missing. Fix: run ctx_doctor.", UNKNOWN_FIELD: 'Unknown field "<f>". Fix: use "queries".', TIMEOUT: "Timed out after <ms> ms. Fix: pass background: true.", NO_GIT_BASH: "Git Bash not found. Fix: install Git for Windows.", // D-VT-WINBASH-1 NO_RUNTIME: "No <lang> runtime on PATH. Fix: install it or pick another language.", FETCH_FAILED: "Fetch failed: <code>. Fix: check the URL or proxy.", SSRF: "Blocked private address <host>. Fix: use a public URL.", OUTSIDE_ROOT: "Path <p> is outside the project. Fix: use a path inside <root>.", INVALID_ARGS: "Invalid argument <field>. Fix: <action>.", ONE_OF_INPUT: "Pass exactly one of <names>. Fix: drop the extra field.", SPAWN_FAILED: "Failed to start the process: <detail>. Fix: check the command and PATH.", DB_CORRUPT: "context.db failed integrity_check. Fix: run ctx_doctor.", SCHEMA_STALE: "context.db schema is version <found>, expected <want>. Fix: run ctx_doctor.", NO_GIT_DIR: "No git repository at <path>. Fix: run context-mode inside a git repository.", NO_HOME: "Env var <name> is not set. Fix: set <name> to your home directory.", PLUGIN_ROOT_MISSING: "Plugin root for <agent> not found at <path>. Fix: run ctx_upgrade.", // impl/07 §1 Errors BUNDLE_HASH_MISMATCH: "Fetched bundle hash does not match SHA256SUMS. Fix: run ctx_upgrade again.", // impl/07 §6 Errors CONFIG_PARSE_FAILED: "<agent> config at <path> did not parse as <format>. Fix: fix the syntax error and re-run ctx_upgrade.", // impl/07 §2 Errors }); // impl/01 §4.3: one left-to-right scan for <name> tokens, no regex. export function formatError(code: ErrorCode, vars: Record<string, string | number>): string { const template = ERROR_TEXT[code]; let out = ""; let i = 0; while (i < template.length) { if (template[i] !== "<") { out += template[i]; i += 1; continue; } let j = i + 1; while (j < template.length && template[j] !== "<" && template[j] !== ">") j += 1; if (j >= template.length) { out += template.slice(i); // unterminated "<": literal text to the end (A-C5) break; } if (template[j] === "<") { out += "<"; // second "<" before any ">": the first one is literal (A-C5) i += 1; continue; } const name = template.slice(i + 1, j); const value = vars[name]; if (value === undefined) throw new Error("formatError: missing var " + name + " for " + code); // A-C3 out += String(value); i = j + 1; } return out; } export class CtxError extends Error { readonly code: ErrorCode; readonly vars: Record<string, string | number>; constructor(code: ErrorCode, vars?: Record<string, string | number>) { super(formatError(code, vars ?? {})); this.code = code; this.vars = vars ?? {}; } toLine(): string { return this.message; } } - src/core/contracts/types.ts (13817 bytes)
// impl/01 §2, impl/00 §3.1 verbatim. Pure types: no runtime code. import type { AgentId } from "./agents.js"; import type { DatabaseSync } from "node:sqlite"; export type { AgentId } from "./agents.js"; export type CanonicalEventName = "SessionStart" | "UserPromptSubmit" | "PreToolUse" | "PostToolUse"; // ADR-0001, PRD §10.1 export type AuxEventName = "PreCompact" | "Usage" | "Stop"; // PreCompact: pending_compact on gemini, copilot-cli, vscode (ADR-0009 §6); Usage: OpenCode step-finish cost row (D-M5-arch-2); Stop: Codex turn end, empty reply (D-1323-CODEX-STOP-1) export interface CanonicalHookEvent { event: CanonicalEventName | AuxEventName; agent: AgentId; sessionId: string; cwd: string; agentId?: string; // subagent marker; presence = subagent (Q23) agentType?: string; // selects tool-set row only agentTools?: string[]; // in-process hosts (OpenCode 2): the agent's tool set read at spawn time (ADR-0016 l.23, #1348) source?: "startup" | "resume" | "clear" | "compact"; // SessionStart prompt?: string; // UserPromptSubmit tool?: ToolCall; // Pre/PostToolUse result?: ToolResultInfo; // PostToolUse turn?: number; } export interface ToolCall { name: string; // host name as received, e.g. mcp__context-mode__ctx_execute canonicalName: string; // "Bash" | "Read" | "Grep" | "WebFetch" | "ctx_execute" | ... | "mcp:<server>:<tool>" input: Record<string, unknown>; callId?: string; } // persistedPath (D-M2-SHAPE-2): the host kept the whole output in this file and `text` is only its head. // blocks (D-M2-MCP-1): the host gave an MCP content-block array; a replace must be one text block. // keep: a block is not text (image, resource), so the original result stays. export interface ToolResultInfo { isError: boolean; bytes: number; text?: string; exitCode?: number; persistedPath?: string; blocks?: boolean; keep?: boolean; shape?: Record<string, unknown>; } // shape (D-M2-MCP-1, D-CC-SHAPE-1, D-R33-CC-SHELL-1): the native tool object (Bash, Read file, Grep, Glob, WebFetch) as the host gave it; a replace keeps its fields and swaps the text field. export type Decision = | { kind: "allow" } | { kind: "hint"; text: string; onceKey: string } | { kind: "deny"; reason: string; rewritten?: string } // ADR-0008: reason carries the rewrite; never allow+updatedInput (Q3) | { kind: "replace"; output: string }; // case C, PostToolUse updatedToolOutput (ADR-0016) // native shape produced by adapter.encode; stderr is set only by the kiro encode (exit 2 returns STDERR to the agent, // Kiro CLI 2.x reference; D-HF-KIRO-SHELL-1). export interface HookOutput { stdout: string; stderr?: string; exitCode: 0 | 2; } export type EventKind = "prompt" | "edit" | "cmd" | "toolerr" | "index" | "cost" | "decision"; // ADR-0009 §1 + GP10 + DECISIONS-r6 D3 export interface JournalRow { seq: number; session_id: string; worktree: string; agent: AgentId; kind: EventKind; tool: string | null; key: string | null; path: string | null; ok: 0 | 1; exit_code: number | null; bytes: number; body: string; turn: number; sandbox_bytes: number; returned_bytes: number; created_at: number; accessed_at: number; } export type NewJournalRow = Omit<JournalRow, "seq" | "created_at" | "accessed_at">; export interface ProjectContext { projectKey: string; // sha256(git common dir realpath) hex, first 16 chars projectDir: string; // ~/.context-mode/projects/<projectKey> dbPath: string; // <projectDir>/context.db worktree: string; // realpath of this worktree root containmentRoot: string; // git common dir parent; all worktrees inside (#954, #1294) agent: AgentId; source: ProjectSourceKind; } export type ProjectSourceKind = "env:CLAUDE_PROJECT_DIR" | "arg:--agent+cwd" | "arg:workspaceFolder" | "spawn-cwd" | "pi:ctx.cwd"; export interface ToolContext { project: ProjectContext; sessionId: string; turn: number; signal: AbortSignal; clientInfo?: { name: string; version: string }; protocolVersion: string; piCwd?: string; hostPermission?: HostPermission; } // piCwd: Pi ctx.cwd (D-R38-PI-D7-1); hostPermission: D-1331-OC-PERM-1 /** D-1331-OC-PERM-1: "wired" = the host permission check runs before each ctx_* tool; "missing" = the host build has no plugin permission API. */ export type HostPermission = "wired" | "missing"; // DEVIATIONS D-M2-2: the handler supplies the journal facts only it knows; the server stays the one // write path and uses the D-M1-T10-1 defaults when `journal` is absent. export interface JournalFacts { kind: EventKind; key: string | null; path: string | null; exit_code: number | null; } export interface ToolReply { text: string; isError: boolean; sandboxBytes: number; journal?: JournalFacts; } export interface ToolDef<I> { name: string; description: string; schema: import("zod").ZodType<I>; readOnly: boolean; alwaysLoad: boolean; handler(input: I, ctx: ToolContext): Promise<ToolReply>; } // ADR-0020: "package" = file inside the installed package dir; "home-file"/"home-dir" = path under HOME; // "in-process" = plugin entry the host loads from the package dir. export interface HookChannel { kind: "package" | "home-file" | "in-process"; path: string; } export interface SkillChannel { kind: "package" | "home-dir"; path: string; } export interface AdapterRow { id: AgentId; installMode: "marketplace" | "config-mcp" | "extension" | "plugin" | "mcp-entry" | "hooks+mcp" | "in-process"; projectSource: ProjectSourceKind; toolNamePrefix: string; // e.g. claude-code/vscode/kiro "mcp__context-mode__", codex "mcp__context_mode__" (underscore — DECISIONS-r9 R1), gemini "mcp_context-mode_", opencode "context-mode_" nativeTools: { shell: string[]; read?: string[]; grep?: string[]; webfetch?: string[]; edit?: string[] }; // DECISIONS-r9 R4; feeds the PreToolUse/PostToolUse matcher and in-body filters execReadOnlyHint: boolean; // DECISIONS-r9 R5; true only for codex, sets annotations.readOnlyHint on ctx_execute eventMap: Partial<Record<CanonicalEventName | AuxEventName, string>>; // canonical → native name compactDelivery: "sessionstart" | "pending-flag" | "pi-flag" | "opencode-cache" | "none"; compactSummary: "host" | "none"; // "host": host writes its own compact summary (verified by LV-COMPACT, M3); "none": inject the 2,048 B D1 block via the ADR-0009 §6 path. DECISIONS-r6 D6. hookTimeoutMs: number; denyChannel: "deny-reason" | "hint-only"; hookChannel: HookChannel; // ADR-0020: the one hook channel setup writes (required, no exception rows) skillChannel: SkillChannel; // ADR-0020: the one skill channel setup writes (required) decode(raw: unknown): CanonicalHookEvent; encode(ev: CanonicalHookEvent, d: Decision, extra?: string): HookOutput; } // Store handle (impl/02 §6; signatures per impl/00 §4, DEVIATIONS D-M1-1). export interface DbHandle { raw: DatabaseSync; projectKey: string; path: string; readOnly?: boolean; // D-CKPT-LAT-1: a read-only handle writes nothing, closeDb skips the checkpoint } // ContentStore types (impl/05 §0 verbatim). export type SourceKind = "path" | "content" | "url"; export interface SourceRow { id: number; projectKey: string; sessionId: string; worktree: string; agent: AgentId; kind: SourceKind; label: string; // label = path, "content", or final URL bytes: number; chunkCount: number; createdAt: number; } export interface Chunk { ord: number; text: string; bytes: number; title?: string; } export type SearchScope = "session" | "worktree" | "project"; export interface Hit { sourceId: number; label: string; ord: number; snippet: string; score: number; full?: boolean; } // ctx_search sort:"timeline" rows (ADR-0009 §8.1, DECISIONS-r9 M14-M18, DEVIATIONS D-M2-3). // One row shape for the three sources the timeline merges: ContentStore ("content"), SessionDB // ("session", journal rows) and the host's auto-memory files ("memory"). export type SearchSort = "relevance" | "timeline"; export type TimelineOrigin = "content" | "session" | "memory"; export interface TimelineRow { origin: TimelineOrigin; ts: number; // epoch ms UTC (M16: events created_at, sources created_at, memory file mtime) seq: number | null; // journal seq; null for content and memory rows (M17) sourceId: number | null; // content rows only; tie-break after seq (M17) path: string | null; // memory rows: file path; tie-break after seq (rule 5) label: string; // "<source>" field of the output line (rule 8) text: string; // row body; the reply shows its first line (rule 8) } // M2 tool inputs: the TS shapes of the zod schemas in src/core/tools/registry.ts // (impl/04 §2.1, §3.1; impl/05 §3, §6, DECISIONS-r9 V23). The schema is the runtime check. export interface ExecuteInput { language: string; // "shell" | "powershell" | "javascript" | "typescript" | "python" (EXEC_LANGUAGES) or any PATH runtime (A9) code: string; file?: string; intent?: string; timeoutMs?: number; // positive integer, at most EXEC_TIMEOUT_MS (Q8) background?: boolean; summary?: boolean; } export interface BatchInput { commands: string[]; queries: string[]; } export interface CtxIndexInput { path?: string; content?: string; url?: string; source?: string; } // exactly one of path/content/url (ONE_OF_INPUT) export interface CtxSearchInput { queries: string[]; scope?: SearchScope; source?: string; offset?: number; // relevance only; with "timeline" -> INVALID_ARGS (M23) sort?: SearchSort; after?: number; // timeline only, epoch-ms cursor (M18); with "relevance" -> INVALID_ARGS (M23) } // M3 enforcement parser types (impl/08 §1.1, §2.1, §2.2, §2.3 step 2a, §3.1, §6.2). // "op": && || ; | ( ) "io": > >> < 2> 2>&1 &> << <<- // "unhandled": a span the lexer does not read as a command: [[ ]] (( )) $( ) ` ` and a heredoc body. export type TokenKind = "word" | "op" | "io" | "unhandled"; export interface Token { kind: TokenKind; text: string; start: number; end: number; } export interface SimpleCommand { argv0: string; // first word, quote characters stripped args: string[]; redirectsToFile: boolean; // > / >> to a real file, curl -o / wget -O to a real file endsInBoundedSink: boolean; // last pipeline segment is head -c N, wc, grep -c, or a whitelisted jq raw: string; // original substring for this segment pipesOut?: true; // D-CDX-CAT-1: stdout feeds the next pipeline command (set only when true) insideConstruct?: string; // DECISIONS-r9 P1: "case", or the function's name wrappedBy?: string[]; // impl/08 §3.1: unwrapped wrappers, outermost first } // DECISIONS-r9 P2: the only six ParseError codes. export type ParseErrorConstruct = | "process-substitution" | "unterminated-quote" | "unterminated-heredoc" | "coproc" | "select" | "nesting-too-deep"; export type ParseResult = | { ok: true; commands: SimpleCommand[] } // one per pipeline segment, chain-split | { ok: false; construct: ParseErrorConstruct }; export type DenyKind = "curl" | "http" | "build" | "webfetch"; // impl/08 §6.2 denyMessage kind // M4 tools-session (impl/06 "Shared types"; DEVIATIONS D-M4-arch-2: compaction reads JournalRow, so no EventRow). export type CandidateSection = | "last_request" | "open_errors" | "changed_files" | "decisions" | "earlier_requests" | "indexed_sources"; export interface Candidate { section: CandidateSection; seq: number; turn: number; text: string; // whole line, never pre-cut bytes: number; // UTF-8 byte length of `text` repeatCount: number; // how many journal rows this candidate folds (same key) pinned: boolean; // true only for the single "last_request" row } export interface ScoredCandidate extends Candidate { score: number; // integer } // M4 tool inputs (impl/06 §4-§6; zod schemas in src/core/tools/registry.ts). Handlers take (input, ctx: ToolContext), D-M4-arch-3. export interface CtxResumeInput { session?: string; seq?: number; } export interface CtxStatsInput {} // no fields; any key is STATS_UNKNOWN_FIELD_LINE export interface CtxPurgeInput { session?: string; source?: string; project?: boolean; } // exactly one (impl/06 §6 step 1) // tools-ops (impl/07 §0, A-T1; ADR-0010, ADR-0011) export type DoctorCheckId = "D1" | "D2" | "D3" | "D4" | "D5" | "D5b" | "D6" | "D7" | "D8" | "D9" | "D10" | "D11"; export interface DoctorRow { id: DoctorCheckId; label: string; // e.g. "version", "context.db" status: "PASS" | "WARN" | "FAIL" | "UNKNOWN"; detail: string; // the <cause>, plain English, one line fixCommand?: string; // the <command>; omitted when status is PASS } export interface V1Finding { file: string; path: string; reason: string; } // ADR-0011 §"v1 cleanup" export type UpgradeMode = "upgrade" | "uninstall"; export interface UpgradeChangeRow { area: string; before: string; after: string; } export interface HostConfigEdit { path: string; before: unknown; after: unknown; } // one key changed // impl/07 §2 and §5-§6 exports, named here so ops/ and tools/ share one shape (DEVIATIONS D-M5-C2-2). export type HostConfigFormat = "json" | "jsonc" | "toml"; export interface HostConfigResult { text: string; format: HostConfigFormat; edits: HostConfigEdit[]; } export interface CtxUpgradeInput { mode?: UpgradeMode; confirmDelete?: boolean; } // A-T4 export interface CtxDoctorInput {} // A-T3: no fields; any key is UNKNOWN_FIELD /** r3-ledger: one line unit of a stored output, as queryUnits returns it; the MMR pool of recall. */ export interface UnitCandidate { sourceId: number; ord: number; label: string; body: string; score: number } - src/core/hooks/decision.ts (4584 bytes)
// ADR-0009 §8.2, DECISIONS-r6 D3, impl/00 §5.3, DEVIATIONS D-M4-arch-5, D-M4-H1-1. // Pure rules for the `decision` journal row: no DB, no I/O, no regex, no word list. The caller // (dispatch.ts) appends the row and indexes its body under DECISION_SOURCE. // Rule 1: PostToolUse of AskUserQuestion with a JSON tool_response.answers -> "Q: <question> → A: <label>". // Rule 2: the user's prompt, trimmed and case-folded, equals one option label -> "A: <label>\nref: #<seq>". // Anything else gives no row (fail-safe): a missed tag costs nothing, a wrong tag caused #856. import { DECISION_ANSWERS_KEY, DECISION_LABEL_JOIN, DECISION_OPTION_KEY } from "../contracts/constants.ts"; export interface DecisionPart { key: string; // journal key: the question text (rule 1) or DECISION_OPTION_KEY (rule 2) body: string; // journal body, also the one chunk indexed under DECISION_SOURCE } function isObject(v: unknown): v is Record<string, unknown> { return typeof v === "object" && v !== null && !Array.isArray(v); } // A single-select label is a string; a multi-select label is a string[] joined with " | ". // Empty strings and non-string items are skipped, never stringified (v1 #586 "[object Object]"). function labelText(v: unknown): string { if (typeof v === "string") return v; if (!Array.isArray(v)) return ""; return v.filter((x): x is string => typeof x === "string" && x !== "").join(DECISION_LABEL_JOIN); } // answers is a map { "<question>": label } (Claude Code, v1 #586) or a list [{ question, label }] // (the GP6 fixture shape). Both give (question, label) pairs in order; any other shape gives none. function answerPairs(answers: unknown): Array<[string, unknown]> { if (Array.isArray(answers)) { return answers.filter(isObject).filter((a) => typeof a.question === "string").map((a) => [a.question as string, a.label]); } return isObject(answers) ? Object.entries(answers) : []; } /** Rule 1. `responseText` is the PostToolUse tool_response text. Non-JSON or no answers -> []. */ export function answerDecisions(responseText: string): DecisionPart[] { let parsed: unknown; try { parsed = JSON.parse(responseText); } catch { return []; // non-JSON response writes no row (ADR-0009 §8.2 rule 1) } if (!isObject(parsed)) return []; const out: DecisionPart[] = []; for (const [question, value] of answerPairs(parsed[DECISION_ANSWERS_KEY])) { const label = labelText(value); if (question === "" || label === "") continue; out.push({ key: question, body: "Q: " + question + " → A: " + label }); } return out; } /** Option labels of an AskUserQuestion call: tool_input.questions[].options[].label. */ export function askOptionLabels(toolInput: Record<string, unknown>): string[] { const questions = toolInput.questions; if (!Array.isArray(questions)) return []; const out: string[] = []; for (const q of questions) { if (!isObject(q) || !Array.isArray(q.options)) continue; for (const o of q.options) if (isObject(o) && typeof o.label === "string" && o.label !== "") out.push(o.label); } return out; } function isDigit(c: string): boolean { return c >= "0" && c <= "9"; } function isAsciiLetter(c: string): boolean { return (c >= "a" && c <= "z") || (c >= "A" && c <= "Z"); } // One line: a marker at column 0 (digits, or one ASCII letter), then "." or ")", then a space, // then a non-empty label. Returns the trimmed label, or "" when the line is not an option. function lineLabel(line: string): string { let i = 0; while (i < line.length && isDigit(line[i])) i++; if (i === 0 && line.length > 0 && isAsciiLetter(line[0])) i = 1; if (i === 0) return ""; if (line[i] !== "." && line[i] !== ")") return ""; const rest = line.slice(i + 1); if (!rest.startsWith(" ")) return ""; return rest.trim(); } /** Option labels of a numbered/lettered list (`1.`, `2.`, `A)`, `B)` at line start) in an assistant turn. */ export function listOptionLabels(text: string): string[] { return text.split("\n").map(lineLabel).filter((l) => l !== ""); } function fold(s: string): string { return s.trim().toLowerCase(); } /** Rule 2. `refSeq` is the journal seq of the turn that offered the options. Plain string compare. */ export function optionEchoDecision(prompt: string, labels: readonly string[], refSeq: number): DecisionPart | null { const p = fold(prompt); if (p === "") return null; const label = labels.find((l) => fold(l) === p); if (label === undefined) return null; return { key: DECISION_OPTION_KEY, body: "A: " + label + "\nref: #" + refSeq }; } - src/core/hooks/detached.ts (880 bytes)
// impl/09 §3 (appendDetached), A21; 00 rule "Journal writes from hooks are detached" (GP3, A32); // DEVIATIONS D-M3-H1-3, D-1401-SPOOL-1. import type { NewJournalRow, ProjectContext } from "../contracts/types.ts"; import { writeDetached } from "./spool.ts"; /** * Fire-and-forget journal append. Returns before the row is written; never throws, never rejects. * `sessionId` is the session the row belongs to; the row itself carries it in `session_id`. * D-1401-SPOOL-1: the write waits at most HOOK_BUSY_MS for the lock; a busy lock puts the row in the project * spool with the time the hook took it, and the next hook write that gets the lock applies it. No closeDb (A21). */ export function appendDetached(project: ProjectContext, sessionId: string, row: NewJournalRow): void { void sessionId; writeDetached(project, { t: "row", row, at: Date.now() }, "journal"); } - src/core/hooks/dispatch.ts (43951 bytes)
// impl/09 §4 (handleHook), ADR-0009 §1, §6 and §8.2, ADR-0016; DEVIATIONS D-M3-arch-3 (case-B wrapper // next to the hook bundle), D-M3-H2-1..7, D-M4-arch-5 and D-M4-H2-1..3 (compact "none" branches, decision rows). // One path per event. Every failure fails open: allow, one stderr line. Never block the host. // D-CI-PERF-7: node:fs through getBuiltinModule; a static ESM import of node:fs also loads fs/promises, readline and streams. const { lstatSync, readFileSync } = process.getBuiltinModule("node:fs") as typeof import("node:fs"); import { dirname, join, relative, resolve, sep } from "node:path"; import { AGENT_IDS, type AgentId } from "../contracts/agents.ts"; import { COMPACTED_META_PREFIX, COMPACT_POINTER_LINE, COMPACT_STATE_KEY, DECISION_OPTION_KEY, DECISION_SOURCE, DECISION_TOOL, EDIT_PATH_KEYS, EDIT_TOOLS, EXIT_CODE_LINE_PREFIX, OWN_TOOL_PREFIX, MCP_SERVER_TOOL_PREFIX, PLUGIN_CALL_ID_PREFIX, prefixToolNames, MAX_CHUNK_BYTES, REPLACE_CHUNK_BYTES, REPLACE_HANDLE_LINE, REPLACE_RETURN_BYTES, REPLACE_TRIGGER_BYTES, RANGE_READ_TOOLS, READ_PATH_KEYS, SKILL_LOAD_TOOLS, READ_RANGE_KEYS, SHAPE_RETURN_BYTES, PARSE_ERROR_DENY_LINE, PENDING_COMPACT_FLAG, PENDING_COMPACT_KEY, PENDING_COMPACT_META_PREFIX, POLICY_UNREADABLE_LINE, RECALL_KEY, RECALL_MAX_ROWS, RECALL_SEEN_META_PREFIX, RECALL_UNIT_CANDIDATES, RECALL_UNITS_SEEN_META_PREFIX, RESUME_HINT, RESUME_HINT_KEY, RUN_WRAPPER_FILE, RUN_WRAPPER_AGENT, RUN_WRAPPER_NODE, PERSISTED_FILE_LINE, SEARCH_TWIN_LINE, SEARCH_WRAPPER_FILE, SUBAGENT_HANDLE_LINE, ECHO_MAX_BYTES, SHELL_TOOL, SOURCE_LABEL_MAX_CHARS, SUBAGENT_SOURCE_PREFIX, SYNC_INDEX_MAX_BYTES, TOOL_PREFIX_SLOT, USER_DENY_REASON_PREFIX, SUBAGENT_RUN_DENY, WORKSPACE_FOLDER_FLAG, PROJECTS_DIR_NAME, CLAUDE_TOOL_RESULTS_DIR_NAME, PERSISTED_OUTPUT_MAX_BYTES, } from "../contracts/constants.ts"; import type { AdapterRow, CanonicalHookEvent, Chunk, Decision, DbHandle, EventKind, HookOutput, ProjectContext, ToolCall, ToolResultInfo, } from "../contracts/types.ts"; import { getAdapter, hasRecall, hasReplace } from "../../adapters/table.ts"; import { decide } from "../policy/decide.ts"; import { isOwnFile } from "../policy/own-file.ts"; import { isSubagentCall, pickSubagentCase, toolSetForAgentType, type ToolSetSources } from "../policy/subagent.ts"; import { readUserDeny } from "../policy/user-deny.ts"; import { resolveProject } from "../project/resolve.ts"; import { claudeDirOf, homeDirOf } from "../project/config-dir.ts"; import { isInside } from "../project/contain.ts"; import { metaGet, metaSet, metaTake } from "../store/db.ts"; import { canonicalKey } from "../journal/append.ts"; import { hasAgentRows, hasSessionRows, lastSessionSeq, readLastPrompt, readMaxSeq, readRecallRows, readSessionEvents } from "../journal/read.ts"; import { queryUnits, readMaxSourceId, recallQueryText, reserveSource, sourceHandle, type SourceDraft } from "../store/fts.ts"; import { renderState } from "../compaction/render.ts"; import { pickRecall } from "../compaction/recall.ts"; import { chunkText } from "../index/chunk.ts"; import { moreLine, selectChunksInMemory } from "../index/select.ts"; import { shapeDigest } from "../index/shape.ts"; import { appendDetached } from "./detached.ts"; import { hookDb, isBusy, spool, writeDetached, writeOrSpool, type SpoolOp } from "./spool.ts"; import { askedWords } from "./handle-query.ts"; import { answerDecisions, askOptionLabels, optionEchoDecision, type DecisionPart } from "./decision.ts"; import { shouldHint } from "./throttle.ts"; import { CtxError } from "../contracts/errors.ts"; import { allowOutput, failureOutput, fault, logHookError, nodeTooOld } from "./fallback.ts"; export { failureOutput, logHookError } from "./fallback.ts"; // D-HNE-GUARD-1: the entry's last-resort catch export { readStdin, writeOut } from "./io.ts"; // D-M7-HP-1: entry I/O without process.stdin/stdout streams const ALLOW: Decision = { kind: "allow" }; const EMPTY: HookOutput = { stdout: "", exitCode: 0 }; const DIGIT_0 = 48; function isAgentId(s: string): s is AgentId { return (AGENT_IDS as readonly string[]).includes(s); } function message(err: unknown): string { return err instanceof Error ? err.message : String(err); } function str(v: unknown): string { return typeof v === "string" ? v : ""; } /** impl/09 §4.2. Never throws: decode, project and dispatch failures all end in this agent's allow shape. */ export async function handleHook(agent: AgentId, raw: unknown, env: NodeJS.ProcessEnv): Promise<HookOutput> { if (!isAgentId(agent)) { process.stderr.write("hooks: unknown agent " + JSON.stringify(agent) + "\n"); // step 1, A22, D-FU-PS-1 return EMPTY; } const row = getAdapter(agent); // D-HNE-GUARD-1: every failure below ends in failureOutput (exit 0, this host's shape, tool table only) and a log line. const report = (stage: string, err: unknown, line?: string): void => { logHookError(env, agent, stage, err); process.stderr.write(line ?? "hooks: " + stage + " failed: " + message(err) + "\n"); }; const fail = (stage: string, err: unknown, line?: string): HookOutput => { report(stage, err, line); return failureOutput(agent, raw, err); }; if (nodeTooOld(process.version)) { // D-1370-OLDNODE-ALLOW-1 (#1370): the MCP server runs on this same node and is degraded (PRD §13: ctx_doctor only), so a // redirect to ctx_execute would block the host. Allow, and keep the stderr and log lines (D5). An in-process host // (Pi, OMP, OpenCode) registers its ctx_* tools itself, so its redirect target exists and the D-HNE-GUARD-1 deny stays. const err = new CtxError("NODE_TOO_OLD", { v: process.version }); if (row.installMode === "in-process") return fail("node", err); report("node", err); return allowOutput(agent); } let ev: CanonicalHookEvent; try { fault(env, "decode"); ev = row.decode(raw); } catch (err) { return fail("decode", err); // step 2 } // D-1323-CODEX-STOP-1: Stop has no project or store work; it gets this agent's allow reply before the project step. if (ev.event === "Stop") return row.encode(ev, ALLOW); let project: ProjectContext; try { fault(env, "project"); // D-HA-PI-PROJECT-1: on pi the entry puts ctx.cwd into the payload, so ev.cwd is the pi:ctx.cwd source. // D-HF-VSCODE-PROJECT-1: a VS Code hook has no launch args; its workspace folder is the payload cwd. const argv = agent === "vscode" ? [WORKSPACE_FOLDER_FLAG, ev.cwd] : process.argv; project = resolveProject(agent, { env, argv, cwd: ev.cwd, piCwd: getAdapter(agent).projectSource === "pi:ctx.cwd" ? ev.cwd : undefined }); // step 3 (pi, omp: ADR-0026) } catch (err) { // D-FU-PS-1 keeps its one stderr line (code first); the decision part is new. return fail("project", err, "hooks: no project: " + String((err as { code?: unknown }).code ?? "ERROR") + " " + message(err) + "\n"); // D-HNE-GUARD-1 supersedes D-FU-PS-1: a flooding call is denied, the rest allowed } let decision: Decision; const settle: Settle = {}; try { fault(env, "policy"); decision = await dispatch(ev, row, project, env, settle); // step 4 } catch (err) { return fail("store", err); } try { fault(env, "encode"); const out = row.encode(ev, decision); // step 6 settle.run?.(true); return out; } catch (err) { settle.run?.(false); // D-STATS-RET-3: the host gets the failure output, the whole tool output return fail("encode", err); } } /** D-STATS-RET-3: PostToolUse leaves its journal write here; handleHook runs it once the encode stage is known. */ interface Settle { run?: (encoded: boolean) => void } function dispatch(ev: CanonicalHookEvent, row: AdapterRow, project: ProjectContext, env: NodeJS.ProcessEnv, settle: Settle): Promise<Decision> { switch (ev.event) { case "SessionStart": return sessionStart(ev, row, project); case "UserPromptSubmit": return userPromptSubmit(ev, row, project); case "PreToolUse": return preToolUse(ev, row, project, env); case "PostToolUse": return postToolUse(ev, row, project, env, settle); case "PreCompact": return preCompact(ev, row, project); case "Usage": return usage(ev, project); } return Promise.resolve(ALLOW); // step 4 defensive default } function withPrefix(template: string, row: AdapterRow): string { return template.split(TOOL_PREFIX_SLOT).join(row.toolNamePrefix); } // ---------- §4.3 SessionStart ---------- // D6: "host" sends the fixed pointer line only; "none" sends the full renderState block (§4.3 step 1.3, // §4.4 step 2.4). Rows are this session's journal, read once per compact delivery. function compactText(db: DbHandle, ev: CanonicalHookEvent, row: AdapterRow): string { if (row.compactSummary === "host") return prefixToolNames(COMPACT_POINTER_LINE, row.toolNamePrefix); return renderState(readSessionEvents(db, ev.sessionId), ev.turn ?? 0, undefined, row.toolNamePrefix); } async function sessionStart(ev: CanonicalHookEvent, row: AdapterRow, project: ProjectContext): Promise<Decision> { if (ev.source === "compact" && hasRecall(row)) markCompacted(await hookDb(project), ev.sessionId); if (ev.source === "compact" && row.compactDelivery === "sessionstart") { const db = await hookDb(project); // A23, #1396: the host sends one SessionStart(compact) per compaction with the same session id. The // marker key carries the newest journal seq, so each compaction gets its state block and a duplicate // delivery of the same compaction (no new row in between) stays silent. const onceKey = COMPACT_STATE_KEY + ":" + lastSessionSeq(db, ev.sessionId); if (!shouldHint(db, ev.sessionId, onceKey)) return ALLOW; return { kind: "hint", text: compactText(db, ev, row), onceKey }; } const db = await hookDb(project); // impl/12 §4.6 step 2, D-M5-P2-4: the OpenCode plugin's one `context` call per session reads and clears // the pending-compact marker here (handleHook is the one DB path); its stdout is the cache-stable payload. if (row.compactDelivery === "opencode-cache" && metaTake(db, PENDING_COMPACT_META_PREFIX + ev.sessionId) !== null) { return { kind: "hint", text: compactText(db, ev, row), onceKey: PENDING_COMPACT_KEY }; } if (!shouldHint(db, ev.sessionId, RESUME_HINT_KEY)) return ALLOW; return { kind: "hint", text: withPrefix(RESUME_HINT, row), onceKey: RESUME_HINT_KEY }; // D-M3-H2-2 } // ---------- §4.4 UserPromptSubmit ---------- async function userPromptSubmit(ev: CanonicalHookEvent, row: AdapterRow, project: ProjectContext): Promise<Decision> { const body = ev.prompt ?? ""; // D-FU-GCH-2: decided before this turn's own prompt row is queued, so that row never counts as "something to resume". const resume = await firstTurnResume(ev, row, project); appendDetached(project, ev.sessionId, { session_id: ev.sessionId, worktree: project.worktree, agent: ev.agent, kind: "prompt", tool: null, key: null, path: null, ok: 1, exit_code: null, bytes: Buffer.byteLength(body), body, turn: ev.turn ?? 0, sandbox_bytes: 0, returned_bytes: 0, }); echoDetached(ev, project, body); if (row.compactDelivery === "pending-flag") { const db = await hookDb(project); // §4.4 step 2.2: DELETE ... RETURNING inside BEGIN IMMEDIATE, so the delivery fires once. if (metaTake(db, PENDING_COMPACT_META_PREFIX + ev.sessionId) !== null) { return { kind: "hint", text: compactText(db, ev, row), onceKey: PENDING_COMPACT_KEY }; } } if (resume !== null) return resume; return recall(ev, row, project, body); } // D-FU-GCH-2: a row with no SessionStart hook (Gemini: hooks/hooks.json drops it, D-FU-GCH-1) gets the // resume hint on the first UserPromptSubmit of a session instead. First turn = the payload session id has // no journal row yet (a host-resumed session keeps its id and its rows, and the host replays that history // itself). The marker is the SessionStart one (RESUME_HINT_KEY, same session id), so the hint fires at most // once per session. It fires only when this worktree already holds a journal row of this agent. async function firstTurnResume(ev: CanonicalHookEvent, row: AdapterRow, project: ProjectContext): Promise<Decision | null> { if (row.eventMap.SessionStart !== undefined || ev.sessionId === "") return null; const db = await hookDb(project); if (hasSessionRows(db, ev.sessionId)) return null; if (!shouldHint(db, ev.sessionId, RESUME_HINT_KEY)) return null; if (!hasAgentRows(db, project.worktree, ev.agent)) return null; return { kind: "hint", text: withPrefix(RESUME_HINT, row), onceKey: RESUME_HINT_KEY }; } // ---------- DECISIONS-r11 (B) turn-boundary recall ---------- // #1394: the value is the boundary of the latest compaction, {"seq": newest journal seq, "source": newest // sources id}. Rows and outputs written after it are still in the model's live context, so recall skips them. function markCompacted(db: DbHandle, sessionId: string): void { if (sessionId === "") return; metaSet(db, COMPACTED_META_PREFIX + sessionId, JSON.stringify({ seq: readMaxSeq(db), source: readMaxSourceId(db) })); } // A value from before #1394 ("1") carries no boundary: every row stays a candidate, as before. function compactBoundary(value: string): { seq: number; source: number } { const all = { seq: Number.MAX_SAFE_INTEGER, source: Number.MAX_SAFE_INTEGER }; try { const v = JSON.parse(value) as unknown; if (typeof v !== "object" || v === null) return all; const { seq, source } = v as { seq?: unknown; source?: unknown }; return { seq: typeof seq === "number" ? seq : all.seq, source: typeof source === "number" ? source : all.source, }; } catch { return all; } } function seenSeqs(value: string | null): number[] { if (value === null) return []; try { const v = JSON.parse(value) as unknown; return Array.isArray(v) ? v.filter((n): n is number => typeof n === "number") : []; } catch { return []; } } function seenUnitKeys(value: string | null): string[] { if (value === null) return []; try { const v = JSON.parse(value) as unknown; return Array.isArray(v) ? v.filter((k): k is string => typeof k === "string") : []; } catch { return []; } } // No compaction in this session (or a row without UserPromptSubmit additionalContext): ALLOW, zero added // bytes. After one: BM25 of this session's rows and the same worktree's prior-session rows against the // prompt; whole rows over RECALL_MIN_SCORE, within RECALL_BUDGET_BYTES; a row goes out once per session. async function recall(ev: CanonicalHookEvent, row: AdapterRow, project: ProjectContext, prompt: string): Promise<Decision> { if (!hasRecall(row) || ev.sessionId === "") return ALLOW; const db = await hookDb(project); const compacted = metaGet(db, COMPACTED_META_PREFIX + ev.sessionId); if (compacted === null) return ALLOW; const boundary = compactBoundary(compacted); const seenKey = RECALL_SEEN_META_ - src/core/hooks/fallback.ts (9195 bytes)
// D-HNE-GUARD-1 (owner decision 2026-10-29): a hook never errors. On any internal failure the hook still exits 0 with a // valid decision for its host, built from the tool-name table alone: no project, no store, no policy module. // - own ctx_* tools and tools that cannot flood the context: allowed (ctx_doctor and the sandbox stay reachable); // - shell, large Read, grep and fetch tools: denied with the usual redirect plus one line naming the error. // D-1370-OLDNODE-ALLOW-1: on Node below NODE_MIN the server hosts get allowOutput instead (the server is degraded too). // The error and its stack go to <data root>/hook-errors.log (append only, never cut), never only to stderr. // Imports: contracts and the adapter table only. Nothing here throws. const fs = process.getBuiltinModule("node:fs") as typeof import("node:fs"); import { join, resolve } from "node:path"; import type { AgentId } from "../contracts/agents.ts"; import { dataRootOf } from "../project/config-dir.ts"; import { DATA_DIR_ENV, HOOK_ERROR_LOG_FILE, HOOK_FAULT_ENV, HOOK_FAULT_STAGES, NODE_MIN, HOOK_FAIL_CWD_KEYS, HOOK_FAIL_EVENT_KEYS, HOOK_FAIL_INPUT_KEYS, HOOK_FAIL_LINE, HOOK_FAIL_PRE_EVENTS, HOOK_FAIL_REDIRECT, HOOK_FAIL_TOOLS, HOOK_FAIL_TOOL_KEYS, HOOK_LOG_TAIL_BYTES, OUTPUT_CAP, OWN_TOOL_PREFIX, prefixToolNames, READ_PATH_KEYS, READ_PATH_LIST_KEY, } from "../contracts/constants.ts"; import type { AdapterRow, HookOutput } from "../contracts/types.ts"; import { getAdapter } from "../../adapters/table.ts"; import { isMediaRead } from "../policy/read-media.ts"; import { isOwnFile } from "../policy/own-file.ts"; type Rec = Record<string, unknown>; type Kind = "shell" | "read" | "grep" | "fetch"; function isRec(v: unknown): v is Rec { return typeof v === "object" && v !== null && !Array.isArray(v); } function firstString(o: Rec, keys: readonly string[]): string { for (const k of keys) if (typeof o[k] === "string") return o[k] as string; return ""; } /** The tool input as an object: a JSON string (Copilot toolArgs) is parsed, anything else unreadable gives {}. */ function inputOf(o: Rec): Rec { for (const k of HOOK_FAIL_INPUT_KEYS) { let v = o[k]; if (typeof v === "string") { try { v = JSON.parse(v); } catch { v = undefined; } } if (isRec(v)) return v; } return {}; } function homeOf(env: NodeJS.ProcessEnv): string { return env.HOME ?? env.USERPROFILE ?? ""; } /** <data root>/hook-errors.log ($CONTEXT_MODE_DATA_DIR or <home>/.context-mode, #1318), or "" when neither is known. */ export function hookLogPath(env: NodeJS.ProcessEnv): string { const dir = env[DATA_DIR_ENV]; if (dir !== undefined && dir !== "") return join(dataRootOf(env, ""), HOOK_ERROR_LOG_FILE); const home = homeOf(env); return home === "" ? "" : join(dataRootOf(env, home), HOOK_ERROR_LOG_FILE); } /** A short, stable label: the CtxError code, else the error name. */ export function errorLabel(err: unknown): string { const code = isRec(err) ? err.code : undefined; if (typeof code === "string" && code !== "") return code; return err instanceof Error ? err.name : "Error"; } /** Append one JSON line (time, agent, stage, label, message, stack). Never throws. */ export function logHookError(env: NodeJS.ProcessEnv, agent: string, stage: string, err: unknown): void { try { const file = hookLogPath(env); if (file === "") return; fs.mkdirSync(join(file, ".."), { recursive: true }); const line = JSON.stringify({ ts: new Date().toISOString(), agent, stage, label: errorLabel(err), message: err instanceof Error ? err.message : String(err), stack: err instanceof Error ? err.stack ?? "" : "", }); fs.appendFileSync(file, line + "\n"); } catch { process.stderr.write("hooks: " + stage + " failed: " + (err instanceof Error ? err.message : String(err)) + "\n"); // no log possible } } /** The last logged hook error as {ts, stage, label}, read from the tail of the log; null when none. Never throws. */ export function lastHookError(env: NodeJS.ProcessEnv): { ts: string; stage: string; label: string } | null { try { const file = hookLogPath(env); if (file === "" || !fs.existsSync(file)) return null; const fd = fs.openSync(file, "r"); try { const size = fs.fstatSync(fd).size; const start = Math.max(0, size - HOOK_LOG_TAIL_BYTES); const buf = Buffer.alloc(size - start); fs.readSync(fd, buf, 0, buf.length, start); const lines = buf.toString("utf8").split("\n"); for (let i = lines.length - 1; i >= 0; i--) { try { const j = JSON.parse(lines[i] ?? "") as Rec; if (typeof j.ts === "string" && typeof j.stage === "string" && typeof j.label === "string") return { ts: j.ts, stage: j.stage, label: j.label }; } catch { /* partial first line of the tail, or a foreign line */ } } return null; } finally { fs.closeSync(fd); } } catch { return null; } } let fired = false; /** Test seam (HOOK_FAULT_ENV): throws once when `stage` is the named one. A no-op in production. */ export function fault(env: NodeJS.ProcessEnv, stage: (typeof HOOK_FAULT_STAGES)[number]): void { if (fired || env[HOOK_FAULT_ENV] !== stage) return; fired = true; throw new Error("injected fault at " + stage); } /** True when `version` (e.g. "v22.1.0") is below NODE_MIN. Numeric parts only; an unparsable part counts as 0. */ export function nodeTooOld(version: string): boolean { const a = (version.startsWith("v") ? version.slice(1) : version).split("."); const b = NODE_MIN.split("."); for (let i = 0; i < b.length; i++) { const x = Number(a[i] ?? 0) || 0; const y = Number(b[i]); if (x !== y) return x < y; } return false; } function has(list: readonly string[] | undefined, name: string): boolean { return list !== undefined && list.some((n) => n.toLowerCase() === name); } function kindOf(row: AdapterRow, name: string): Kind | null { const n = name.toLowerCase(); if (has(row.nativeTools.shell, n) || has(HOOK_FAIL_TOOLS.shell, n)) return "shell"; if (has(row.nativeTools.read, n) || has(HOOK_FAIL_TOOLS.read, n)) return "read"; if (has(row.nativeTools.grep, n) || has(HOOK_FAIL_TOOLS.grep, n)) return "grep"; if (has(row.nativeTools.webfetch, n) || has(HOOK_FAIL_TOOLS.fetch, n)) return "fetch"; return null; } function isPreTool(row: AdapterRow, event: string): boolean { const e = event.toLowerCase(); return HOOK_FAIL_PRE_EVENTS.includes(e) || (row.eventMap.PreToolUse ?? "").toLowerCase() === e; } function bigFile(abs: string): boolean { try { const st = fs.statSync(abs); return st.isFile() && st.size > OUTPUT_CAP; } catch { return false; } } /** True when the Read target is a whole file over the output cap. An unreadable, unnamed or ranged target is not denied. */ function bigRead(agent: AgentId, input: Rec, cwd: string): boolean { if ((input.offset ?? null) !== null || (input.limit ?? null) !== null) return false; // a ranged Read is never denied (same as decide) const many = Array.isArray(input[READ_PATH_LIST_KEY]) ? (input[READ_PATH_LIST_KEY] as unknown[]).filter((x): x is string => typeof x === "string") : []; // D-R47-READ-MEDIA-1: an image or PDF the host shows as a block is not denied (same as decide). // D-R48-OWN-FILE-1 (#1326): the agent's own skill and rule files are not denied (same as decide). return [firstString(input, READ_PATH_KEYS), ...many].some((p) => p !== "" && bigFile(resolve(cwd, p)) && !isMediaRead(agent, resolve(cwd, p)) && !isOwnFile(agent, cwd, p)); } /** This host's allow reply, in its own shape (a valid document for every host). Never throws. */ export function allowOutput(agent: AgentId): HookOutput { try { return getAdapter(agent).encode({ event: "PreToolUse", agent, sessionId: "", cwd: "", turn: 0 }, { kind: "allow" }); } catch { return { stdout: "", exitCode: 0 }; } } /** * The host-shaped answer to a hook that failed. `raw` is the parsed stdin (any shape). Never throws. * A PreToolUse call that could flood the context is denied; everything else is this host's allow shape. */ export function failureOutput(agent: AgentId, raw: unknown, err: unknown, cwdFallback = ""): HookOutput { const row = getAdapter(agent); try { if (!isRec(raw)) return allowOutput(agent); if (!isPreTool(row, firstString(raw, HOOK_FAIL_EVENT_KEYS))) return allowOutput(agent); const name = firstString(raw, HOOK_FAIL_TOOL_KEYS); if (name === "" || name.includes(OWN_TOOL_PREFIX)) return allowOutput(agent); const kind = kindOf(row, name); if (kind === null) return allowOutput(agent); const cwd = firstString(raw, HOOK_FAIL_CWD_KEYS) || cwdFallback; if (kind === "read" && !bigRead(agent, inputOf(raw), cwd)) return allowOutput(agent); const redirect = kind === "read" ? HOOK_FAIL_REDIRECT.read : HOOK_FAIL_REDIRECT[kind]; const reason = prefixToolNames(redirect, row.toolNamePrefix) + "\n" + HOOK_FAIL_LINE(errorLabel(err), row.toolNamePrefix); return row.encode({ event: "PreToolUse", agent, sessionId: "", cwd, turn: 0 }, { kind: "deny", reason }); } catch { return { stdout: "", exitCode: 0 }; } } - src/core/hooks/handle-query.ts (1165 bytes)
// D-HA-GEMINI-HINT-1: the query of the replace handle line. A bare command (`cat logs/app.log`) shares no word with // the output, so the handle call listed the first chunks by position (D-HL-H9-1) and missed the line the user asked // for. The second query is the words of the last user prompt that the output holds, fewest occurrences // first, at most HANDLE_PROMPT_WORDS. No prompt or no shared word -> "" (the handle line is unchanged). import { HANDLE_PROMPT_WORDS } from "../contracts/constants.ts"; import { wordTokens } from "../store/words.ts"; export function askedWords(intent: string, prompt: string, text: string): string { const want = new Set(wordTokens(prompt.toLowerCase())); for (const w of wordTokens(intent.toLowerCase())) want.delete(w); if (want.size === 0) return ""; const counts = new Map<string, number>(); for (const w of wordTokens(text.toLowerCase())) { if (want.has(w)) counts.set(w, (counts.get(w) ?? 0) + 1); } const picked = [...counts.entries()] .sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)) .slice(0, HANDLE_PROMPT_WORDS) .map((e) => e[0]); return picked.join(" "); } - src/core/hooks/io.ts (2169 bytes)
// impl/09 §5.2 hook entry I/O, DEVIATIONS D-M7-HP-1 (GS6). Re-exported by dispatch.ts so the entry keeps // its import rule (contracts + dispatch only, D-M3-H2-9). // D-CI-PERF-3: node:fs through getBuiltinModule; a static ESM import of node:fs also loads fs/promises, readline and streams. const { read, writeSync } = process.getBuiltinModule("node:fs") as typeof import("node:fs"); // D-CI-PERF-6: stdin is read with async fs.read on fd 0 (libuv thread pool), not the process.stdin stream: the // stream builds net, stream and pipe_wrap (28 internal modules, about 3.5 ms per call on Node 24 and 26). It is not // a sync read, so the event loop never blocks in read(0) (the D-M7-HP-1 hang was a sync readFileSync(0)). Any error // other than EOF (EAGAIN on a non-blocking pipe, EISDIR, ...) falls back to the stream and keeps the bytes read so far. const CHUNK = 65536; function readFd0(parts: Buffer[]): Promise<boolean> { const buf = Buffer.allocUnsafe(CHUNK); return new Promise((resolve) => { const step = (): void => { read(0, buf, 0, CHUNK, null, (err, n) => { if (err) return resolve((err as NodeJS.ErrnoException).code === "EOF"); // Windows pipe end = EOF error if (n === 0) return resolve(true); parts.push(Buffer.from(buf.subarray(0, n))); step(); }); }; step(); }); } export async function readStdin(): Promise<string> { const parts: Buffer[] = []; if (!(await readFd0(parts))) for await (const c of process.stdin) parts.push(c as Buffer); return Buffer.concat(parts).toString("utf8"); } // GS6 (D-M7-HP-1): stdout is written with writeSync to fd 1, so the hook never builds the // process.stdout stream. Loop until every byte is out; EAGAIN (non-blocking pipe) // falls back to process.stdout, which queues the rest and flushes before the process ends. export function writeOut(text: string): void { const buf = Buffer.from(text, "utf8"); let off = 0; try { while (off < buf.length) off += writeSync(1, buf, off, buf.length - off); } catch (err) { if ((err as NodeJS.ErrnoException).code !== "EAGAIN") throw err; process.stdout.write(buf.subarray(off)); } } - src/core/hooks/spool.ts (8237 bytes)
// D-1401-SPOOL-1 (#1401): hook writes under another process's write lock. A hook process waits at most // HOOK_BUSY_MS for the project write lock (not DB_TIMEOUT_MS: the host kills a hook at HOOK_TIMEOUT_MS). When the // lock stays busy, the write goes to <projectDir>/pending as one JSON file, and the next hook write in the project // that gets the lock applies the pending files first, oldest first. No journal row and no indexed output is dropped. // D-CI-PERF-7: node:fs through getBuiltinModule; a static ESM import of node:fs also loads fs/promises, readline and streams. const { mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, utimesSync, writeFileSync } = process.getBuiltinModule("node:fs") as typeof import("node:fs"); import { join } from "node:path"; import { HOOK_BUSY_MS, HOOK_SPOOL_DIR, SPOOL_CLAIM_STALE_MS, SPOOL_DRAIN_MS, SQLITE_BUSY_CODE, SQLITE_PRIMARY_CODE_MASK, } from "../contracts/constants.ts"; import type { Chunk, DbHandle, NewJournalRow, ProjectContext } from "../contracts/types.ts"; import { openDb, withWrite } from "../store/db.ts"; import { appendEvent } from "../journal/append.ts"; import { deleteChunkRows, insertChunks, insertUnits, reserveSource, type SourceDraft } from "../store/fts.ts"; import { chunkText } from "../index/chunk.ts"; import { buildUnits } from "../index/units.ts"; /** One hook write. "row": a journal row and the time the hook took it. "src": a text to index as one source; id is * the reserved source row (null: not written yet), max the chunk size, units whether line units are written too. */ export type SpoolOp = | { t: "row"; row: NewJournalRow; at: number } | { t: "src"; id: number | null; src: SourceDraft; text: string; max: number; units: boolean }; const OP_SUFFIX = ".json"; const CLAIM_SUFFIX = ".claim"; const TMP_SUFFIX = ".tmp"; const BAD_SUFFIX = ".bad"; const NAME_TIME_DIGITS = 15; const NAME_SEQ_DIGITS = 6; let nameSeq = 0; export function isBusy(err: unknown): boolean { const code = (err as { errcode?: unknown } | null)?.errcode; return typeof code === "number" && (code & SQLITE_PRIMARY_CODE_MASK) === SQLITE_BUSY_CODE; } function message(err: unknown): string { return err instanceof Error ? err.message : String(err); } /** The project store with the hook's short lock wait. */ export async function hookDb(project: ProjectContext): Promise<DbHandle> { const db = await openDb(project); db.raw.exec("PRAGMA busy_timeout = " + String(HOOK_BUSY_MS)); return db; } function spoolDir(project: ProjectContext): string { return join(project.projectDir, HOOK_SPOOL_DIR); } /** Write `op` to the spool: a private .tmp name first, then one rename, so a reader never sees half a file. */ export function spool(project: ProjectContext, op: SpoolOp): void { const dir = spoolDir(project); mkdirSync(dir, { recursive: true }); const name = String(Date.now()).padStart(NAME_TIME_DIGITS, "0") + "-" + String(process.pid) + "-" + String(nameSeq++).padStart(NAME_SEQ_DIGITS, "0"); const tmp = join(dir, name + TMP_SUFFIX); writeFileSync(tmp, JSON.stringify(op)); renameSync(tmp, join(dir, name + OP_SUFFIX)); } // Apply one op. cur.op follows the work: once the source row is reserved, cur.op carries its id, so a busy // lock after that spools the rest under the same id (the handle the model got stays valid). function runOp(db: DbHandle, op: SpoolOp, chunks: Chunk[] | undefined, cur: { op: SpoolOp }): number | null { if (op.t === "row") { appendEvent(db, op.row, op.at); return null; } const c = chunks ?? chunkText(op.text, "text", op.max); let id = op.id; if (id === null) { id = reserveSource(db, op.src, c); cur.op = { ...op, id }; } else if (chunks === undefined) { // A spooled finish: the source may hold part of its chunks from the busy try, and a purge may have removed it. const sid = id; const gone = withWrite(db, (h) => { if (h.raw.prepare("SELECT 1 AS x FROM sources WHERE id = ?").get(sid) === undefined) return true; deleteChunkRows(h.raw, { sourceId: sid }); return false; }); if (gone) return null; } try { insertChunks(db, id, op.src, c); if (op.units) insertUnits(db, id, op.src.sessionId, buildUnits(op.text)); } catch (err) { // A busy lock keeps the reserved row: the spooled finish clears its partial chunks and writes them again. if (isBusy(err)) throw err; const sid = id; withWrite(db, (h) => { // D-R4-RESERVE-1: no 0-chunk orphan; this removes what landed deleteChunkRows(h.raw, { sourceId: sid }); h.raw.prepare("DELETE FROM sources WHERE id = ?").run(sid); }); throw err; } return id; } /** Apply `op` now; on a busy lock, spool what is left. Returns the source id of a "src" op when it is known. */ export function writeOrSpool(project: ProjectContext, db: DbHandle, op: SpoolOp, chunks?: Chunk[]): number | null { const cur = { op }; try { return runOp(db, op, chunks, cur); } catch (err) { if (!isBusy(err)) throw err; spool(project, cur.op); return cur.op.t === "src" ? cur.op.id : null; } } /** Fire-and-forget hook write: drain the spool, then apply `op` (or spool it). Never throws, never rejects. */ export function writeDetached(project: ProjectContext, op: SpoolOp, what: string, chunks?: Chunk[]): void { void (async () => { try { const db = await hookDb(project); if (drain(project, db)) spool(project, op); // the lock is busy: the row waits behind the older ones else writeOrSpool(project, db, op, chunks); } catch (err) { try { if (!isBusy(err)) throw err; spool(project, op); } catch (e) { process.stderr.write("hooks: " + what + " write failed: " + message(e) + "\n"); } } })(); } // Take one spool file for this process: one rename, so two drainers never apply the same file. A claim older than // SPOOL_CLAIM_STALE_MS belongs to a hook the host killed; it goes back to the queue first. function claim(dir: string, name: string): string | null { let base = name; if (name.endsWith(OP_SUFFIX + CLAIM_SUFFIX)) { const path = join(dir, name); try { if (Date.now() - statSync(path).mtimeMs < SPOOL_CLAIM_STALE_MS) return null; base = name.slice(0, -CLAIM_SUFFIX.length); renameSync(path, join(dir, base)); } catch { return null; } } else if (!name.endsWith(OP_SUFFIX)) { return null; } const claimed = join(dir, base + CLAIM_SUFFIX); try { renameSync(join(dir, base), claimed); const now = new Date(); utimesSync(claimed, now, now); return claimed; } catch { return null; } } /** * Apply the pending spool files, oldest first, for at most SPOOL_DRAIN_MS. Returns true when the lock is busy * (the file goes back to the queue and the drain stops), false otherwise. */ export function drain(project: ProjectContext, db: DbHandle): boolean { const dir = spoolDir(project); let names: string[]; try { names = readdirSync(dir); } catch { return false; // no spool dir: nothing waits } const start = Date.now(); for (const name of names.sort()) { if (Date.now() - start > SPOOL_DRAIN_MS) return false; const claimed = claim(dir, name); if (claimed === null) continue; const base = claimed.slice(0, -CLAIM_SUFFIX.length); let op: SpoolOp; try { op = JSON.parse(readFileSync(claimed, "utf8")) as SpoolOp; } catch (err) { process.stderr.write("hooks: pending write unreadable: " + message(err) + "\n"); renameSync(claimed, base + BAD_SUFFIX); // kept on disk, never applied twice continue; } const cur = { op }; try { runOp(db, op, undefined, cur); } catch (err) { if (isBusy(err)) { if (cur.op === op) { renameSync(claimed, base); } else { writeFileSync(base + TMP_SUFFIX, JSON.stringify(cur.op)); renameSync(base + TMP_SUFFIX, base); unlinkSync(claimed); } return true; } process.stderr.write("hooks: pending write failed: " + message(err) + "\n"); renameSync(claimed, base + BAD_SUFFIX); continue; } unlinkSync(claimed); } return false; } - src/core/hooks/throttle.ts (1954 bytes)
// impl/09 §2 (shouldHint), A20, A24; DECISIONS-r9 E5; impl/08 §6.1 step 8 (everyN for the mcp key family); // DEVIATIONS D-M3-H1-1..3. // The marker is one meta row "hint:" + sessionId + ":" + onceKey. Keyed by session id only: no ppid, // no "latest session" guess. A PreToolUse call may touch meta (A24), never the journal. import { metaGet, metaSet, withWrite } from "../store/db.ts"; import type { DbHandle } from "../contracts/types.ts"; function markerKey(sessionId: string, onceKey: string): string { return "hint:" + sessionId + ":" + onceKey; } // §2.2 step 3: a plain once-per-session key fires only when its row does not exist yet. function takeOnce(db: DbHandle, key: string): boolean { if (metaGet(db, key) !== null) return false; metaSet(db, key, "1"); return true; } // §2.2 step 2: count-based key; fires on calls 1, 1+N, 1+2N, ... (D-M3-H1-2). function takeEvery(db: DbHandle, key: string, everyN: number): boolean { const stored = metaGet(db, key); const count = (stored === null ? 0 : Number.parseInt(stored, 10)) + 1; metaSet(db, key, String(count)); return (count - 1) % everyN === 0; } /** * True when the hint for (sessionId, onceKey) fires on this call. Without everyN the key fires once * per session; with everyN (the mcp family, MCP_HINT_EVERY) it re-fires every everyN calls. * Joins the caller's open write transaction (§2.2 step 4); otherwise runs its own BEGIN IMMEDIATE so * the read and the write of the marker are one step across processes. * An empty session id returns false and writes nothing (E5, D-M3-H1-1). */ export function shouldHint(db: DbHandle, sessionId: string, onceKey: string, everyN?: number): boolean { if (sessionId === "") return false; const key = markerKey(sessionId, onceKey); const decide = (h: DbHandle): boolean => (everyN === undefined ? takeOnce(h, key) : takeEvery(h, key, everyN)); return db.raw.isTransaction ? decide(db) : withWrite(db, decide); } - src/core/index/auto-memory.ts (4934 bytes)
// DEVIATIONS D-M2-3, D-M2-T9-1, D-UNIFIED-MEMORY-1; DECISIONS-r9 M14 (auto-memory = the host's own memory files for this // project), M16 (timestamp = file mtime), M17 (no seq). // Returns the rows ftsQueryTimeline merges as its `memory` argument and the chunks a relevance query ranks // (memoryHits); the store never sees a host path and user memory files are never written to context.db. import { readdirSync, readFileSync, statSync } from "node:fs"; import { join } from "node:path"; import type { Hit, ProjectContext, TimelineRow } from "../contracts/types.ts"; import { isInside } from "../project/contain.ts"; import { rankTexts, highlight } from "../store/fts.ts"; import { MEMORY_LABEL_PREFIX, SNIPPET_MAX_BYTES } from "../contracts/constants.ts"; import { chunkText } from "./chunk.ts"; // Project memory / instruction files per host, relative to the worktree root (format facts of the hosts, not // tunables; same rule as `.gitignore` in walk.ts, D-M2-T6-2). Every agent reads all of them (owner, D-UNIFIED-MEMORY-1). // Sources: CLAUDE.md, CLAUDE.local.md, .claude/CLAUDE.md = Claude Code; AGENTS.md = Codex, OpenCode, Pi; // GEMINI.md = Gemini CLI; QWEN.md = Qwen Code (src/setup/registry.ts INSTRUCTION_FILES); // .github/copilot-instructions.md = Copilot CLI, VS Code (docs/architecture/PRD-setup.md prompt-file list); // .kiro/steering/*.md = Kiro (src/core/contracts/constants.ts V1_REASON.kiroSteering). Order = the order rows are returned. const MEMORY_FILES: readonly (readonly string[])[] = Object.freeze([ Object.freeze(["CLAUDE.md"]), Object.freeze(["CLAUDE.local.md"]), Object.freeze([".claude", "CLAUDE.md"]), Object.freeze(["AGENTS.md"]), Object.freeze(["GEMINI.md"]), Object.freeze(["QWEN.md"]), Object.freeze([".github", "copilot-instructions.md"]), ]); const KIRO_STEERING: readonly string[] = Object.freeze([".kiro", "steering"]); const MD = ".md"; function steeringFiles(worktree: string): (readonly string[])[] { try { return readdirSync(join(worktree, ...KIRO_STEERING)) .filter((n) => n.endsWith(MD)) .sort() .map((n) => [...KIRO_STEERING, n]); } catch { return []; } } /** * One row per memory file inside this worktree, for every agent (D-UNIFIED-MEMORY-1). * A file that is missing, unreadable, or whose realpath leaves the worktree gives no row; this * function never throws. */ export function readAutoMemory(project: Pick<ProjectContext, "agent" | "worktree">): TimelineRow[] { const rows: TimelineRow[] = []; for (const segs of [...MEMORY_FILES, ...steeringFiles(project.worktree)]) { const path = join(project.worktree, ...segs); // isInside is false for a missing path and for a symlink that points out of the worktree. if (!isInside(project.worktree, path)) continue; try { const st = statSync(path); if (!st.isFile()) continue; rows.push({ origin: "memory", ts: Math.trunc(st.mtimeMs), seq: null, sourceId: null, path, label: segs.join("/"), text: readFileSync(path, "utf8"), }); } catch { // Unreadable (permissions, removed between stat and read): no row for this file. } } return rows; } /** * D-MEMORY-SOURCE-1: the memory file a `source` value names: its label (either slash form) or the label as a hit shows * it ("memory AGENTS.md"). No such file -> null. */ export function memoryFileNamed(rows: readonly TimelineRow[], value: string): TimelineRow | null { const v = value.split("\\").join("/"); return rows.find((r) => r.label === v || MEMORY_LABEL_PREFIX + r.label === v) ?? null; } /** A memory chunk, ready to rank. */ export interface MemoryChunk { fileNo: number; label: string; ord: number; text: string } export function memoryChunks(rows: readonly TimelineRow[]): MemoryChunk[] { const out: MemoryChunk[] = []; rows.forEach((r, i) => { for (const c of chunkText(r.text, "md")) out.push({ fileNo: i + 1, label: r.label, ord: c.ord, text: c.text }); }); return out; } /** * D-UNIFIED-MEMORY-1: memory chunks that match `q`, best first, scored by the store's BM25 in a private in-memory * FTS. `full` = the chunk holds every query word. Memory hits have sourceId = -fileNo (never a content row id). */ export function memoryHits(chunks: readonly MemoryChunk[], q: string, limit: number): Hit[] { if (chunks.length === 0) return []; const texts = chunks.map((c) => c.text); const any = rankTexts(texts, q, "any"); const all = rankTexts(texts, q, "all"); return chunks .map((c, i) => ({ c, s: any[i], full: all[i] > 0 })) .filter((e) => e.s > 0) .sort((a, b) => Number(b.full) - Number(a.full) || b.s - a.s || a.c.fileNo - b.c.fileNo || a.c.ord - b.c.ord) .slice(0, limit) .map((e) => ({ sourceId: -e.c.fileNo, label: MEMORY_LABEL_PREFIX + e.c.label, ord: e.c.ord, snippet: highlight(e.c.text, q, SNIPPET_MAX_BYTES), score: e.s, full: e.full })); } - src/core/index/chunk.ts (15442 bytes)
// impl/05 §2, Assumption A2 (MAX_CHUNK_BYTES), TECH-SPEC GP5 (rowless tables, nested fences, byte caps), // impl/00 rule 4 (no regex: every scan below is character by character), DEVIATIONS D-M2-T6-1. // Chunks are spans of the normalized input: block text is never rewritten, and the only cut is the // code-point-safe split of a single block over MAX_CHUNK_BYTES, whose remainder starts the next chunk. import { MAX_CHUNK_BYTES } from "../contracts/constants.ts"; import type { Chunk } from "../contracts/types.ts"; interface Heading { level: number; text: string; } // openEnd: index of the "\n" ending the opener line; closeStart: start of the closer line, -1 when unclosed. interface FenceInfo { fence: string; openEnd: number; closeStart: number; } interface Span { start: number; end: number; heading?: Heading; fence?: FenceInfo; } // HTML grammar (not tunables): elements that never close, and elements whose body is raw text. const VOID_TAGS: ReadonlySet<string> = new Set([ "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", ]); const RAW_TAGS: ReadonlySet<string> = new Set(["script", "style"]); const encoder = new TextEncoder(); // maxBytes (D-M7-SV-1): a smaller chunk cap for the PostToolUse replace path; clamped to MAX_CHUNK_BYTES. // Under a smaller cap an over-long block is cut after its last whole line that fits (the chunk keeps that // newline); a single line over the small cap is its own whole chunk, and only a line over MAX_CHUNK_BYTES is // cut by code point (D-HQ-PI-LINE-1). // The default call is unchanged. export function chunkText(text: string, kind: "md" | "html" | "text", maxBytes: number = MAX_CHUNK_BYTES): Chunk[] { const src = normalize(text); if (src.length === 0) return []; const cap = Math.max(4, Math.min(MAX_CHUNK_BYTES, Math.floor(maxBytes))); if (kind === "md") return mdChunks(src, cap, cap < MAX_CHUNK_BYTES); const blocks = kind === "html" ? htmlBlocks(src) : lineBlocks(src, false); return merge(src, blocks, kind !== "text", cap, cap < MAX_CHUNK_BYTES); } // Search layer 1 (DEVIATIONS D-SEARCH-1): "md" chunks never cross a heading and carry the heading path // ("A > B > C") as `title`. Blocks of one section merge greedily up to the cap, so a fenced block that // fits the cap is never split. A fenced block over the cap is split on its blank lines into pieces // that each repeat the opener and closer lines, so every piece is a valid fenced block. function mdChunks(src: string, cap: number, lineCut: boolean): Chunk[] { const out: Chunk[] = []; const stack: Heading[] = []; let title = ""; let run: Span[] = []; const push = (text: string, bytes: number): void => { out.push({ ord: out.length, text, bytes, title }); }; const flush = (): void => { if (run.length === 0) return; for (const c of merge(src, run, true, cap, lineCut)) push(c.text, c.bytes); run = []; }; for (const b of lineBlocks(src, true)) { if (b.heading !== undefined) { flush(); while (stack.length > 0 && stack[stack.length - 1].level >= b.heading.level) stack.pop(); stack.push(b.heading); title = stack.map((h) => h.text).join(" > "); } if (b.fence !== undefined && utf8Bytes(src.slice(b.start, b.end)) > cap) { const pieces = fencePieces(src, b, b.fence, cap); if (pieces !== undefined) { flush(); for (const p of pieces) push(p, utf8Bytes(p)); continue; } } run.push(b); } flush(); return out; } // Opener line + "\n" + a run of the fence body's blank-line blocks + "\n" + closer line, each piece at // most `cap` bytes. undefined when the fence lines alone leave no room (the block is then cut as text). function fencePieces(src: string, b: Span, f: FenceInfo, cap: number): string[] | undefined { const opener = src.slice(b.start, f.openEnd); const closer = f.closeStart >= 0 ? src.slice(f.closeStart, b.end) : f.fence; const innerEnd = f.closeStart >= 0 ? Math.max(f.openEnd + 1, f.closeStart - 1) : b.end; const inner = src.slice(Math.min(f.openEnd + 1, innerEnd), innerEnd); const room = cap - utf8Bytes(opener) - utf8Bytes(closer) - 2; if (room < 16 || inner.length === 0) return undefined; return merge(inner, lineBlocks(inner, false), true, room, true).map((c) => opener + "\n" + c.text + "\n" + closer); } // Step 1: "\r\n" -> "\n", leading BOM removed. function normalize(text: string): string { const lf = text.split("\r\n").join("\n"); return lf.startsWith("") ? lf.slice(1) : lf; } // Step 2, "text" and "md": a block is a run of non-empty lines. In "md", a blank line inside a fence // is not a split point, a run of table lines (each containing "|") is its own block, an ATX heading // line is its own block, and a fenced block is its own block (opener line to closer line). function lineBlocks(src: string, md: boolean): Span[] { const out: Span[] = []; let start = -1; let end = -1; let inTable = false; let fence = ""; let heading: Heading | undefined; let fenceInfo: FenceInfo | undefined; const close = (): void => { if (start >= 0) { const span: Span = { start, end }; if (heading !== undefined) span.heading = heading; if (fenceInfo !== undefined) span.fence = fenceInfo; out.push(span); } start = -1; heading = undefined; fenceInfo = undefined; }; const add = (from: number, to: number, table: boolean): void => { if (start < 0) start = from; end = to; inTable = table; }; let pos = 0; while (pos <= src.length) { const nl = src.indexOf("\n", pos); const eol = nl < 0 ? src.length : nl; const line = src.slice(pos, eol); if (fence !== "") { add(pos, eol, false); if (closesFence(line, fence)) { fence = ""; if (md && fenceInfo !== undefined) { fenceInfo.closeStart = pos; close(); } } } else if (line.length === 0) { close(); } else { const opener = md ? fenceOf(line) : ""; const head = md && opener === "" ? headingOf(line) : undefined; const table = md && opener === "" && head === undefined && line.includes("|"); if (md && start >= 0 && (table !== inTable || opener !== "" || head !== undefined)) close(); add(pos, eol, table); fence = opener; if (opener !== "") fenceInfo = { fence: opener, openEnd: eol, closeStart: -1 }; if (head !== undefined) { heading = head; close(); } } pos = eol + 1; } close(); return out; } /** D-SEARCH-1: true when some line of `text` is an ATX heading or opens a code fence (inline content is then chunked as "md"). */ export function hasMdStructure(text: string): boolean { let pos = 0; while (pos <= text.length) { const nl = text.indexOf("\n", pos); const eol = nl < 0 ? text.length : nl; const line = text.slice(pos, eol).replace("\r", ""); if (fenceOf(line) !== "" || headingOf(line) !== undefined) return true; pos = eol + 1; } return false; } // An ATX heading: up to 3 spaces, 1-6 "#", then a space, a tab or the end of the line. The text drops // a closing run of "#" that follows a space. function headingOf(line: string): Heading | undefined { let i = 0; while (i < line.length && i < 4 && line[i] === " ") i += 1; if (i > 3) return undefined; let level = 0; while (i + level < line.length && line[i + level] === "#") level += 1; if (level < 1 || level > 6) return undefined; const after = line[i + level]; if (after !== undefined && after !== " " && after !== "\t") return undefined; let text = line.slice(i + level).trim(); let k = text.length; while (k > 0 && text[k - 1] === "#") k -= 1; if (k === 0) text = ""; else if (k < text.length && (text[k - 1] === " " || text[k - 1] === "\t")) text = text.slice(0, k).trim(); return { level, text }; } // The fence string a line opens: the full run of "`" or "~" (three or more) after leading spaces. function fenceOf(line: string): string { const t = line.trimStart(); if (!t.startsWith("```") && !t.startsWith("~~~")) return ""; let n = 0; while (n < t.length && t[n] === t[0]) n += 1; return t.slice(0, n); } // A fence closes on a line made only of the same fence character, at least as long as the opener. function closesFence(line: string, fence: string): boolean { const t = line.trim(); if (t.length < fence.length) return false; for (let i = 0; i < t.length; i += 1) if (t[i] !== fence[0]) return false; return true; } // Step 2, "html": split after a closing tag that brings the open-element depth back to 0. // Depth is the sum of per-name counters; a stray close tag (counter 0) is ignored. Comments and // <script>/<style> bodies are skipped whole, so no split lands inside them. function htmlBlocks(src: string): Span[] { const out: Span[] = []; const open = new Map<string, number>(); let depth = 0; let blockStart = 0; let i = 0; const split = (at: number): void => { pushTrimmed(out, src, blockStart, at); blockStart = at; }; while (i < src.length) { if (src[i] !== "<") { i += 1; continue; } if (src.startsWith("<!--", i)) { const e = src.indexOf("-->", i + "<!--".length); i = e < 0 ? src.length : e + "-->".length; continue; } const tag = readTag(src, i); if (tag === undefined) { i += 1; continue; } i = tag.end; if (tag.close) { const n = open.get(tag.name) ?? 0; if (n === 0) continue; open.set(tag.name, n - 1); depth -= 1; if (depth === 0) split(i); continue; } if (tag.selfClose || VOID_TAGS.has(tag.name)) continue; if (RAW_TAGS.has(tag.name)) { i = rawEnd(src, i, tag.name); if (depth === 0) split(i); continue; } open.set(tag.name, (open.get(tag.name) ?? 0) + 1); depth += 1; } pushTrimmed(out, src, blockStart, src.length); return out; } interface Tag { name: string; close: boolean; selfClose: boolean; end: number; } function isLetter(c: string): boolean { return (c >= "a" && c <= "z") || (c >= "A" && c <= "Z"); } function isNameChar(c: string): boolean { return isLetter(c) || (c >= "0" && c <= "9") || c === "-" || c === ":"; } // Reads "<name ...>" or "</name ...>" at i. Quoted attribute values may hold ">". Anything else // (no letter after "<", or no closing ">") is text, not a tag. function readTag(src: string, i: number): Tag | undefined { let j = i + 1; const close = src[j] === "/"; if (close) j += 1; if (j >= src.length || !isLetter(src[j])) return undefined; const nameStart = j; while (j < src.length && isNameChar(src[j])) j += 1; const name = src.slice(nameStart, j).toLowerCase(); let quote = ""; while (j < src.length) { const c = src[j]; if (quote !== "") { if (c === quote) quote = ""; } else if (c === "\"" || c === "'") { quote = c; } else if (c === ">") { break; } j += 1; } if (j >= src.length) return undefined; return { name, close, selfClose: src[j - 1] === "/", end: j + 1 }; } // End of a raw-text element body: just past the ">" of its "</name" close tag, or end of input. function rawEnd(src: string, from: number, name: string): number { let k = src.indexOf("</", from); while (k >= 0) { const after = k + "</".length + name.length; const named = src.slice(k + "</".length, after).toLowerCase() === name; if (named && (after >= src.length || !isNameChar(src[after]))) { const gt = src.indexOf(">", after); return gt < 0 ? src.length : gt + 1; } k = src.indexOf("</", k + "</".length); } return src.length; } function isSpace(c: string): boolean { return c === " " || c === "\n" || c === "\t" || c === "\f" || c === "\r"; } function pushTrimmed(out: Span[], src: string, start: number, end: number): void { let s = start; let e = end; while (s < e && isSpace(src[s])) s += 1; while (e > s && isSpace(src[e - 1])) e -= 1; if (s < e) out.push({ start: s, end: e }); } function utf8Bytes(s: string): number { return Buffer.byteLength(s, "utf8"); } // Step 4: the longest prefix of src[start, end) that fits MAX_CHUNK_BYTES, ending on a code point. // TextEncoder.encodeInto never writes part of a code point; the slice end is moved back one unit // when it would split a surrogate pair. function cutPoint(src: string, start: number, end: number, scratch: Uint8Array): { end: number; written: number } { let limit = Math.min(end, start + scratch.length); if (limit < end && [...src.slice(limit - 1, limit + 1)].length === 1) limit -= 1; const r = encoder.encodeInto(src.slice(start, limit), scratch); return { end: start + r.read, written: r.written }; } // Steps 3-5: greedy merge of blocks into chunks of at most MAX_CHUNK_BYTES. A merged chunk is the // input span from its first block to its last, so the text between blocks stays as written. // "text" blocks are not merged: each blank-line block is its own chunk (DEVIATIONS D-M2-T6-1). function merge(src: string, blocks: Span[], join: boolean, cap: number, lineCut: boolean): Chunk[] { const out: Chunk[] = []; const scratch = new Uint8Array(cap); let wide: Uint8Array | undefined; let cur: Span | undefined; let curBytes = 0; const emit = (start: number, end: number, bytes: number): void => { out.push({ ord: out.length, text: src.slice(start, end), bytes }); }; for (const b of blocks) { if (cur !== undefined && !join) { emit(cur.start, cur.end, curBytes); cur = undefined; } if (cur !== undefined) { const add = utf8Bytes(src.slice(cur.end, b.end)); if (curBytes + add <= cap) { cur.end = b.end; curBytes += add; continue; } emit(cur.start, cur.end, curBytes); cur = undefined; } let start = b.start; let bytes = utf8Bytes(src.slice(b.start, b.end)); while (bytes > cap) { const cut = cutPoint(src, start, b.end, scratch); const nl = lineCut ? src.lastIndexOf("\n", cut.end - 1) : -1; if (nl > start) { // whole lines: the chunk keeps its last newline, so no byte of the text is dropped const w = utf8Bytes(src.slice(start, nl + 1)); emit(start, nl + 1, w); start = nl + 1; bytes -= w; continue; } if (lineCut) { // D-HQ-PI-LINE-1: one line over the small cap is its own chunk, whole, up to MAX_CHUNK_BYTES; only a // line over MAX_CHUNK_BYTES is cut by code point. A search hit then holds the whole line. const eol = src.indexOf("\n", start); const lineEnd = eol < 0 || eol >= b.end ? b.end : eol + 1; const w = utf8Bytes(src.slice(start, lineEnd)); if (w <= MAX_CHUNK_BYTES) { emit(start, lineEnd, w); start = lineEnd; bytes -= w; continue; } wide ??= new Uint8Array(MAX_CHUNK_BYTES); const big = cutPoint(src, start, lineEnd, wid - src/core/index/html-text.ts (15144 bytes)
// D-HTML-READABLE-1: HTML to markdown-like readable text, before chunking. Kept apart from text.ts and chunk.ts so the // hook bundles never load the parser (GS6 hook budget); only tools/index.ts (ctx_index) imports this file. // The parser is htmlparser2 (a real HTML tokenizer and tree builder, bundled by esbuild; devDependency only, the // published package stays dependency-free). No regex: the walk is over the parsed tree. import { DomUtils, parseDocument } from "htmlparser2"; import type { ChildNode, Element, Text } from "domhandler"; // Node guards on the parser's own `type` field (domhandler is a transitive dependency, so its helpers are not imported). function isText(n: ChildNode): n is Text { return n.type === "text"; } function isTag(n: ChildNode): n is Element { return n.type === "tag" || n.type === "script" || n.type === "style"; } export interface Readable { /** Markdown-like text: headings, paragraphs, lists, tables, fenced code with language, links as [text](url). */ text: string; /** The <title> text, "" when the page has none. */ title: string; /** Words of body text (the synthetic title line is not counted); 0 means the page has no readable text. */ words: number; /** True when the page is a client-rendered shell: almost no text next to a lot of markup. */ sparse: boolean; } // Elements whose content is not page text: code that runs, styles, hidden templates, vector art, form controls, // embedded documents, and page chrome. `head` is dropped too; the title is read from it before the walk. const DROP = new Set([ "script", "style", "noscript", "template", "svg", "math", "iframe", "canvas", "object", "embed", "head", "title", "nav", "footer", "button", "select", "option", "textarea", "input", "dialog", "audio", "video", "picture", "img", ]); const DROP_ROLES = new Set(["navigation", "banner", "contentinfo", "search", "dialog", "tooltip"]); // One line break around these, a blank line around the PARA set. const LINE = new Set(["div", "section", "article", "main", "header", "aside", "figure", "figcaption", "details", "summary", "address", "dl", "dt", "dd", "fieldset", "form", "center", "li", "tr", "body", "html", "caption"]); const PARA = new Set(["p", "blockquote", "hr", "table", "ul", "ol", "pre", "h1", "h2", "h3", "h4", "h5", "h6"]); // Code-block line wrappers: a syntax highlighter puts each source line in one of these (react.dev/Sandpack: div). const PRE_LINE = new Set(["div", "p", "li", "tr"]); const LANG_PREFIXES = ["language-", "lang-", "highlight-source-", "highlight-text-"]; const BLOCK_INSIDE_LINK = new Set(["h1", "h2", "h3", "h4", "h5", "h6", "p", "div", "pre", "ul", "ol", "table", "blockquote", "section", "article"]); function isSpace(c: string): boolean { return c === " " || c === "\t" || c === "\n" || c === "\r" || c === "\f" || c === " "; } function isInvisible(c: string): boolean { return c === "" || c === "" || c === ""; } /** Runs of white space become one space; zero-width characters go. */ function collapse(s: string): string { let out = ""; let gap = false; for (const c of s) { if (isInvisible(c)) continue; if (isSpace(c)) { gap = true; continue; } if (gap) { out += " "; gap = false; } out += c; } return gap ? out + " " : out; } function hidden(el: Element): boolean { const a = el.attribs; if (a.hidden !== undefined || a["aria-hidden"] === "true") return true; if (a.role !== undefined && DROP_ROLES.has(a.role.toLowerCase())) return true; if (a.style !== undefined) { let s = ""; for (const c of a.style.toLowerCase()) if (!isSpace(c)) s += c; if (s.includes("display:none")) return true; } return false; } function dropped(el: Element): boolean { return DROP.has(el.name) || hidden(el); } /** The text content of a node on one line: no markup, links and code shown as their text. */ function plainText(node: ChildNode): string { let out = ""; const visit = (n: ChildNode): void => { if (isText(n)) { out += n.data; return; } if (!isTag(n) || dropped(n)) return; if (n.name === "br") { out += " "; return; } const block = LINE.has(n.name) || PARA.has(n.name); if (block) out += " "; for (const c of n.children) visit(c); if (block) out += " "; }; visit(node); return collapse(out).trim(); } /** The text of a code block, line breaks kept: <br> is a break, a line wrapper (div, p, li, tr) ends a line. */ function preText(node: Element): string { const buf: string[] = []; let last = "\n"; const put = (s: string): void => { if (s === "") return; buf.push(s); last = s[s.length - 1]; }; const visit = (n: ChildNode): void => { if (isText(n)) { let s = ""; for (const c of n.data) { if (isInvisible(c)) continue; s += c === " " ? " " : c; } put(s); return; } if (!isTag(n) || dropped(n)) return; if (n.name === "br") { put("\n"); return; } for (const c of n.children) visit(c); if (PRE_LINE.has(n.name) && last !== "\n") put("\n"); }; for (const c of node.children) visit(c); let code = ""; for (const s of buf) code += s; const lines = code.split("\r\n").join("\n").split("\n"); while (lines.length > 0 && lines[0].trim() === "") lines.shift(); while (lines.length > 0 && lines[lines.length - 1].trim() === "") lines.pop(); return lines.join("\n"); } function langFrom(classes: string | undefined): string { if (classes === undefined) return ""; for (const token of classes.split(" ")) { for (const p of LANG_PREFIXES) { if (token.startsWith(p) && token.length > p.length) return token.slice(p.length); } } return ""; } /** The code language: a language-x class on the <pre>, its <code>, or two ancestors, or a data-language attribute. */ function langOf(pre: Element): string { const code = DomUtils.findOne((e) => e.name === "code", pre.children, true); const chain: Element[] = [pre]; if (code !== null) chain.push(code); let up: Element | null = pre.parent as Element | null; for (let i = 0; i < 2 && up !== null && isTag(up); i += 1) { chain.push(up); up = up.parent as Element | null; } for (const el of chain) { const l = langFrom(el.attribs.class) || el.attribs["data-language"] || el.attribs["data-lang"] || ""; if (l !== "") return safeLang(l); } return ""; } function safeLang(l: string): string { let out = ""; for (const c of l.toLowerCase()) { const ok = (c >= "a" && c <= "z") || (c >= "0" && c <= "9") || c === "+" || c === "-" || c === "#" || c === "_" || c === "."; if (!ok) return out; out += c; } return out; } interface Level { first: string; rest: string; used: boolean; } /** Output builder: owed line breaks, line prefixes for lists and quotes, one space between words. */ class Writer { private parts: string[] = []; private pending = 0; private fresh = true; private endsSpace = false; private stack: Level[] = []; depth(): number { return this.stack.length; } push(first: string, rest: string): void { this.stack.push({ first, rest, used: false }); } pop(): void { this.stack.pop(); } line(): void { if (this.pending < 1) this.pending = 1; } block(): void { this.pending = 2; } private prefix(): string { let p = ""; for (const l of this.stack) { p += l.used ? l.rest : l.first; l.used = true; } return p; } private flush(): void { if (this.parts.length > 0 && this.pending > 0) { const i = this.parts.length - 1; let end = this.parts[i].length; while (end > 0 && this.parts[i][end - 1] === " ") end -= 1; this.parts[i] = this.parts[i].slice(0, end); this.parts.push("\n".repeat(this.pending)); this.fresh = true; this.endsSpace = false; } this.pending = 0; if (this.fresh) { this.parts.push(this.prefix()); this.fresh = false; } } text(raw: string): void { let s = raw; if ((this.fresh || this.pending > 0 || this.endsSpace) && s.startsWith(" ")) s = s.slice(1); if (s === "") return; this.flush(); this.parts.push(s); this.endsSpace = s.endsWith(" "); } /** One whole line, white space kept (a code line, a table row). */ emitLine(s: string): void { this.line(); this.flush(); this.parts.push(s); this.endsSpace = false; this.line(); } code(lang: string, code: string): void { let run = 0; let most = 0; for (const c of code) { run = c === "`" ? run + 1 : 0; if (run > most) most = run; } const fence = "`".repeat(Math.max(3, most + 1)); this.block(); this.emitLine(fence + lang); for (const l of code.split("\n")) this.emitLine(l); this.emitLine(fence); this.block(); } result(): string { let s = ""; for (const p of this.parts) s += p; return s.trimEnd(); } } interface Walk { w: Writer; base: URL | undefined; sawH1: boolean; } function resolveHref(href: string | undefined, base: URL | undefined): string | undefined { if (href === undefined) return undefined; const h = href.trim(); if (h === "" || h.startsWith("#")) return undefined; try { const u = base !== undefined ? new URL(h, base) : new URL(h); return u.protocol === "http:" || u.protocol === "https:" ? u.href : undefined; } catch { return base === undefined && !h.includes(":") ? h : undefined; } } function hasBlock(el: Element): boolean { return DomUtils.findOne((e) => BLOCK_INSIDE_LINK.has(e.name), el.children, true) !== null; } function inlineCode(text: string): string { let run = 0; let most = 0; for (const c of text) { run = c === "`" ? run + 1 : 0; if (run > most) most = run; } const tick = "`".repeat(most === 0 ? 1 : most + 1); const pad = text.startsWith("`") || text.endsWith("`") ? " " : ""; return tick + pad + text + pad + tick; } function cell(el: Element): string { const t = plainText(el); let out = ""; for (const c of t) out += c === "|" ? "\\|" : c; return out; } function table(st: Walk, el: Element): void { const rows = DomUtils.findAll((e) => e.name === "tr", el.children).map((tr) => tr.children.filter((c): c is Element => isTag(c) && (c.name === "td" || c.name === "th")).map(cell)); const cols = rows.reduce((m, r) => Math.max(m, r.length), 0); if (cols === 0) return; st.w.block(); rows.forEach((r, i) => { const padded = r.concat(Array.from({ length: cols - r.length }, () => "")); st.w.emitLine("| " + padded.join(" | ") + " |"); if (i === 0) st.w.emitLine("|" + " --- |".repeat(cols)); }); st.w.block(); } function list(st: Walk, el: Element): void { const ordered = el.name === "ol"; const start = Number.parseInt(el.attribs.start ?? "1", 10); let n = Number.isFinite(start) ? start : 1; if (st.w.depth() === 0) st.w.block(); else st.w.line(); for (const c of el.children) { if (isTag(c) && c.name === "li" && !dropped(c)) { const marker = ordered ? String(n) + ". " : "- "; n += 1; st.w.line(); st.w.push(marker, " ".repeat(marker.length)); for (const k of c.children) walk(st, k); st.w.pop(); st.w.line(); } else { walk(st, c); } } if (st.w.depth() === 0) st.w.block(); else st.w.line(); } function walk(st: Walk, node: ChildNode): void { if (isText(node)) { st.w.text(collapse(node.data)); return; } if (!isTag(node) || dropped(node)) return; const name = node.name; if (name.length === 2 && name[0] === "h" && name[1] >= "1" && name[1] <= "6") { const t = plainText(node); if (t === "") return; if (name === "h1") st.sawH1 = true; st.w.block(); st.w.text("#".repeat(Number(name[1])) + " " + t); st.w.block(); return; } switch (name) { case "pre": { const code = preText(node); if (code !== "") st.w.code(langOf(node), code); return; } case "ul": case "ol": list(st, node); return; case "table": table(st, node); return; case "br": st.w.line(); return; case "hr": st.w.block(); st.w.text("---"); st.w.block(); return; case "blockquote": st.w.block(); st.w.push("> ", "> "); for (const c of node.children) walk(st, c); st.w.pop(); st.w.block(); return; case "code": { const t = plainText(node); if (t !== "") st.w.text(inlineCode(t)); return; } case "a": { if (hasBlock(node)) break; const t = plainText(node); if (t === "") return; const href = resolveHref(node.attribs.href, st.base); st.w.text(href === undefined ? t : "[" + t + "](" + href + ")"); return; } default: } const para = PARA.has(name); const line = LINE.has(name); if (para) st.w.block(); else if (line) st.w.line(); for (const c of node.children) walk(st, c); if (para) st.w.block(); else if (line) st.w.line(); } function isWordChar(c: string): boolean { return c.toLowerCase() !== c.toUpperCase() || (c >= "0" && c <= "9"); } /** Words that hold a letter or a digit: heading marks, bullets and rules do not count. */ function wordCount(text: string): number { let n = 0; for (const w of text.split(" ").join("\n").split("\n")) { for (const c of w) if (isWordChar(c)) { n += 1; break; } } return n; } // D-HTML-READABLE-1: a page is "nearly empty" (client-rendered shell) when it has fewer than SPARSE_MAX_WORDS words // and its markup is more than SPARSE_RATIO times the size of its readable text. A tiny page that is all text is kept. const SPARSE_MAX_WORDS = 20; const SPARSE_RATIO = 20; // The page's own content root: <main>, else the only <article>, else <body>, else the whole document. function contentRoot(children: ChildNode[]): ChildNode[] { const main = DomUtils.findOne((e) => e.name === "main", children, true); if (main !== null) return [main]; const articles = DomUtils.findAll((e) => e.name === "article", children); if (articles.length === 1) return articles; const body = DomUtils.findOne((e) => e.name === "body", children, true); return body !== null ? [body] : children; } /** * Convert an HTML page to readable text. `baseUrl` (the final URL of a fetched page) resolves relative links. * Throws only on a failure of the parser or a tree too deep for the stack; the caller then indexes the raw text. */ export function htmlToReadable(html: string, baseUrl?: string): Readable { const doc = parseDocument(html); const titleEl = DomUtils.findOne((e) => e.name === "title", doc.children, true); const title = titleEl === null ? "" : collapse(titleEl.children.map((c) => (isText(c) ? c.data : "")).join("")).trim(); let base: URL | undefined; try { base = baseUrl === undefined ? undefined : new URL(baseUrl); } catch { base = undefined; } const st: Walk = { w: new Writer(), base, sawH1: false }; for (const n of contentRoot(doc.children)) walk(st, n); const body = st.w.result(); const words = wordCount(body); const text = !st.sawH1 && title !== "" && words > 0 ? "# " + title + "\n\n" + body : body; const sparse = words < SPARSE_MAX_WO - src/core/index/select.ts (3688 bytes)
// impl/05 §5, DECISIONS-r9 F1 (in-memory form), ADR-0016 (whole chunks, budgeted greedy, equal score // -> newest first), ADR-0009 §4 (an item that does not fit is skipped; smaller ones may still fit), // DEVIATIONS D-M2-6, D-M2-T3-1 (rankTexts), D-M2-T8-1. // Reduction is selection of whole chunks; nothing is cut. The full text stays indexed and `more` // names the search that reaches every chunk that was not selected. import { ECHO_MAX_BYTES } from "../contracts/constants.ts"; import type { Chunk, DbHandle } from "../contracts/types.ts"; import { rankTexts } from "../store/fts.ts"; export interface Selection { text: string; more: string | null; } const READ_CHUNKS = "SELECT ord, body FROM chunks WHERE source_id = ?"; const READ_LABEL = "SELECT label FROM sources WHERE id = ?"; // Selected chunks are joined by one newline; its byte is charged to the budget. const SEP = "\n"; const SEP_BYTES = 1; /** DB form: the chunks of one stored source, selected against `intent` within `budget` bytes. */ export function selectChunks(db: DbHandle, sourceId: number, intent: string, budget: number): Selection { const rows = db.raw.prepare(READ_CHUNKS).all(sourceId) as unknown as Array<{ ord: number; body: string }>; if (rows.length === 0) return { text: "", more: null }; const chunks: Chunk[] = rows.map((r) => ({ ord: Number(r.ord), text: r.body, bytes: Buffer.byteLength(r.body, "utf8") })); const row = db.raw.prepare(READ_LABEL).get(sourceId) as { label: string } | undefined; return select(chunks, intent, budget, row?.label); } /** * In-memory form (DECISIONS-r9 F1): same scoring, selection, `more` rule and shape, no DB access. * `source` is the label the caller will store the chunks under; it goes into the `more` line. */ // `rankQuery` (D-M7-SV-5): when given, chunks rank by any word of it instead of all words of `intent`; // the `more` line still names `intent`. export function selectChunksInMemory(chunks: Chunk[], intent: string, budget: number, source?: string, rankQuery?: string): Selection { return select(chunks, intent, budget, source, rankQuery); } function select(chunks: Chunk[], intent: string, budget: number, label: string | undefined, rankQuery?: string): Selection { if (chunks.length === 0) return { text: "", more: null }; // Step 2: one BM25 for both forms, the store's own (same tokenizer as the chunks table). const texts = chunks.map((c) => c.text); const scores = rankQuery === undefined ? rankTexts(texts, intent) : rankTexts(texts, rankQuery, "any"); // Step 3: score descending; equal score -> later chunk first (ADR-0016 "newest first"). const order = chunks.map((_, i) => i).sort((a, b) => scores[b] - scores[a] || chunks[b].ord - chunks[a].ord); const picked: Chunk[] = []; let used = 0; let skipped = false; for (const i of order) { const cost = chunks[i].bytes + (picked.length > 0 ? SEP_BYTES : 0); if (used + cost > budget) { skipped = true; continue; } picked.push(chunks[i]); used += cost; } // Step 5: reading order, not score order. picked.sort((a, b) => a.ord - b.ord); const text = picked.map((c) => c.text).join(SEP); // Step 4. return { text, more: skipped ? moreLine(intent, label) : null }; } export function moreLine(intent: string, label: string | undefined): string { const source = label === undefined ? "" : ", source:" + JSON.stringify(label); // D-NO-LOSSY-CUT-2: a long intent is not echoed (the caller holds it), the same `[...]` as the ctx_batch footer. const query = Buffer.byteLength(intent, "utf8") > ECHO_MAX_BYTES ? "..." : JSON.stringify(intent); return "ctx_search({queries:[" + query + "]" + source + "})"; } - src/core/index/shape.ts (14228 bytes)
// D-M2-SHAPE-1: shape by content type. A replaced tool output whose structure a parser finds is reduced to // its rare units: the rows or lines that break the structure every other row or line follows. The rare units // the query names (BM25, any word) are returned whole, within the replace budget, with a one-line count of // the structure; the caller adds the retrieval handle. No shape, no rare unit, or no rare unit the query // names -> null, and the caller keeps the BM25 chunk path unchanged. Detectors are parsers and statistics // over the content (JSON.parse, token clusters), never a pattern match on the content. Nothing is cut // mid-unit: a line is whole; a JSON row keeps whole fields (key and value), the full row stays indexed. // // JSON: an array of SHAPE_MIN_ROWS+ objects. Per key with scalar values, the values of all rows are counted // (an absent key is its own value). A key is skewed when one value holds >= SHAPE_DOMINANT of the rows and // the other values hold at most SHAPE_RARE_MAX rows; the rows with those other values are rare. // // Lines: a Drain-style template miner. A token with a digit is a variable (<*>). Lines are grouped by token // count and first token; in a group a line joins the first cluster whose template matches at least // SHAPE_SIMILARITY of its positions (a <*> matches any token), and positions that differ become <*>. More // than SHAPE_MAX_CLUSTERS clusters, or a common cluster with no literal token -> not a log (null). A // cluster of at most SHAPE_RARE_MAX lines is rare, and so is a line whose token at a skewed position of its // cluster (the JSON rule, per position) is a rare token. import { rankTexts } from "../store/fts.ts"; const SHAPE_MIN_ROWS = 20; // fewer rows or lines: no statistics to stand on const SHAPE_RARE_MAX = 2; // a value, token or template seen in at most 2 rows is rare const SHAPE_RARE_UNITS_MAX = 9; // more rare units than this: the structure is not a strong one const SHAPE_CATEGORICAL_MAX = 8; // a key or position with at most this many distinct values is categorical (D-M2-MCP-2) const SHAPE_DOMINANT = 0.9; // the common value of a skewed key or position holds 90% of the rows const SHAPE_SIMILARITY = 0.5; // Drain similarity threshold const SHAPE_MAX_CLUSTERS = 64; // more templates than this: free text or code, not a log const SHAPE_EXTREME_KEYS = 2; // D-M2-JSON-2: a query that names more numeric keys than this is not asking for one extreme const SHAPE_COMMON_MAX = 4; // more common templates than this: not a uniform log const SEP = "\n"; const ABSENT = "(absent)"; interface Unit { pos: number; rank: string; render: (budget: number) => string | null } // direct (D-M2-JSON-2): the units were chosen by a statistic over the rows, not by the query; every one is kept. interface Shape { header: string; units: Unit[]; direct?: boolean } const bytes = (s: string): number => Buffer.byteLength(s, "utf8"); /** The digest of `text` within `budget` bytes, or null when no shape or no rare unit the query names. */ export function shapeDigest(text: string, query: string, budget: number): string | null { const shape = jsonShape(text, query) ?? jsonExtremes(text, query) ?? lineShape(text); if (shape === null || query.trim() === "") return null; const scores = shape.direct === true ? shape.units.map(() => 1) : rankTexts(shape.units.map((u) => u.rank), query, "any"); const order = shape.units.map((_, i) => i).filter((i) => scores[i] > 0).sort((a, b) => scores[b] - scores[a] || shape.units[a].pos - shape.units[b].pos); const picked: Array<{ pos: number; text: string }> = []; let used = 0; for (const i of order) { const sep = picked.length > 0 ? bytes(SEP) : 0; const r = shape.units[i].render(budget - used - sep); if (r === null || used + sep + bytes(r) > budget) continue; // skipped; a smaller one may still fit picked.push({ pos: shape.units[i].pos, text: r }); used += sep + bytes(r); } if (picked.length === 0) return null; picked.sort((a, b) => a.pos - b.pos); const body = picked.map((p) => p.text); if (used + bytes(SEP) + bytes(shape.header) <= budget) body.unshift(shape.header); return body.join(SEP); } // ---------- JSON ---------- function firstNonSpace(s: string): string { for (let i = 0; i < s.length; i++) { const c = s[i]; if (c !== " " && c !== "\n" && c !== "\r" && c !== "\t") return c; } return ""; } function isPlainObject(v: unknown): v is Record<string, unknown> { return typeof v === "object" && v !== null && !Array.isArray(v); } // Skewed-value outliers, shared by JSON keys and log token positions: the rows of the non-dominant values. function rareOfSkewed(n: number, counts: Map<string, number[]>, totals: Map<string, number>): number[] { if (totals.size < 2 || totals.size > SHAPE_CATEGORICAL_MAX) return []; const sorted = [...totals.entries()].sort((a, b) => b[1] - a[1]); if (totals.size <= SHAPE_RARE_MAX + 1) { if (sorted[0][1] < SHAPE_DOMINANT * n || n - sorted[0][1] > SHAPE_RARE_MAX) return []; return sorted.slice(1).flatMap(([v]) => counts.get(v) ?? []); } // D-M2-MCP-2: a categorical key with no dominant value: the values seen in at most SHAPE_RARE_MAX rows are // rare when the other values (each common) hold the rest and there are at least two of them. const common = sorted.filter(([, c]) => c > SHAPE_RARE_MAX); const oneOff = sorted.filter(([, c]) => c <= SHAPE_RARE_MAX); if (common.length < 2 || oneOff.length === 0) return []; return oneOff.flatMap(([v]) => counts.get(v) ?? []); } /** The rows of a JSON array of SHAPE_MIN_ROWS+ objects, with every key in first-seen order; else null. */ export function jsonRows(text: string): { objs: Record<string, unknown>[]; keys: string[] } | null { if (firstNonSpace(text) !== "[") return null; let rows: unknown; try { rows = JSON.parse(text); } catch { return null; } if (!Array.isArray(rows) || rows.length < SHAPE_MIN_ROWS || !rows.every(isPlainObject)) return null; const objs = rows as Record<string, unknown>[]; const keys: string[] = []; const seen = new Set<string>(); for (const o of objs) for (const k of Object.keys(o)) if (!seen.has(k)) { seen.add(k); keys.push(k); } return { objs, keys }; } const schemaOf = (n: number, keys: string[]): string => n + " objects {" + keys.join(",") + "}"; export function jsonShape(text: string, query: string): Shape | null { const parsedRows = jsonRows(text); if (parsedRows === null) return null; const { objs, keys } = parsedRows; const outliers = new Map<number, string[]>(); // row index -> skewed keys it breaks for (const k of keys) { const counts = new Map<string, number[]>(); const totals = new Map<string, number>(); let scalar = true; for (let i = 0; i < objs.length && scalar; i++) { const v = k in objs[i] ? objs[i][k] : undefined; if (typeof v === "object" && v !== null) { scalar = false; break; } const s = v === undefined ? ABSENT : JSON.stringify(v); totals.set(s, (totals.get(s) ?? 0) + 1); const at = counts.get(s) ?? []; if (at.length <= SHAPE_RARE_MAX) at.push(i); counts.set(s, at); if (totals.size > SHAPE_CATEGORICAL_MAX) break; // many values: not categorical } if (!scalar) continue; for (const i of rareOfSkewed(objs.length, counts, totals)) outliers.set(i, [...(outliers.get(i) ?? []), k]); } if (outliers.size === 0 || outliers.size > SHAPE_RARE_UNITS_MAX) return null; // Field order for a row that does not fit whole: the skewed keys, then keys the query names, then the // other scalar fields, then the rest; whole fields, shown in the row's own key order. const keyScore = rankTexts(keys, query, "any"); const named = new Set(keys.filter((_, i) => keyScore[i] > 0)); const units: Unit[] = [...outliers.entries()].map(([i, skewed]) => ({ pos: i, rank: JSON.stringify(objs[i]), render: (budget: number) => renderRow(i, objs[i], skewed, named, budget), })); return { header: schemaOf(objs.length, keys) + ", " + outliers.size + " rare:", units }; } function renderRow(i: number, row: Record<string, unknown>, skewed: string[], named: Set<string>, budget: number): string | null { const prefix = "[" + i + "] "; const body = fitRow(row, skewed, named, budget - bytes(prefix)); return body === null ? null : prefix + body; } /** One row as JSON within `budget` bytes: whole, else whole fields (skewed keys, keys the query names, scalars). */ export function fitRow(row: Record<string, unknown>, skewed: string[], named: Set<string>, budget: number): string | null { const whole = JSON.stringify(row); if (bytes(whole) <= budget) return whole; const own = Object.keys(row); const tier = (k: string): number => (skewed.includes(k) ? 0 : named.has(k) ? 1 : typeof row[k] !== "object" || row[k] === null ? 2 : 3); const order = [...own].sort((a, b) => tier(a) - tier(b) || own.indexOf(a) - own.indexOf(b)); const field = (k: string): string => JSON.stringify(k) + ":" + JSON.stringify(row[k]); const chosen = new Set<string>(); let used = 2; // "{" + "}" for (const k of order) { const cost = bytes(field(k)) + (chosen.size > 0 ? 1 : 0); if (used + cost > budget) continue; chosen.add(k); used += cost; } if (!skewed.every((k) => chosen.has(k))) return null; // the field that makes the row rare must show return "{" + own.filter((k) => chosen.has(k)).map(field).join(",") + "}"; } /** Keys of `keys` the query names (BM25, any word). */ export function namedKeys(keys: string[], query: string): Set<string> { const score = rankTexts(keys, query, "any"); return new Set(keys.filter((_, i) => score[i] > 0)); } // D-M2-JSON-2: no skewed key, but the query names a key whose value is a number in every row ("the highest // score"): the rows at its extremes (largest and smallest), whole. The statistic is the order of the values; // the query only names the key. Up to SHAPE_EXTREME_KEYS named keys; a constant key has no extremes. export function jsonExtremes(text: string, query: string): Shape | null { const parsedRows = jsonRows(text); if (parsedRows === null) return null; const { objs, keys } = parsedRows; const named = namedKeys(keys, query); const picks = new Map<number, string>(); let used = 0; for (const k of keys) { if (!named.has(k) || used >= SHAPE_EXTREME_KEYS) continue; if (!objs.every((o) => typeof o[k] === "number" && Number.isFinite(o[k] as number))) continue; let hi = 0, lo = 0; for (let i = 1; i < objs.length; i++) { if ((objs[i][k] as number) > (objs[hi][k] as number)) hi = i; if ((objs[i][k] as number) < (objs[lo][k] as number)) lo = i; } if (hi === lo) continue; used++; picks.set(hi, k); picks.set(lo, k); } if (picks.size === 0) return null; const units: Unit[] = [...picks.entries()].map(([i, k]) => ({ pos: i, rank: "", render: (budget: number) => renderRow(i, objs[i], [k], named, budget), })); return { header: schemaOf(objs.length, keys) + ", extremes of " + [...new Set(picks.values())].join(",") + ":", units, direct: true }; } // ---------- lines (Drain-style) ---------- interface Cluster { tpl: string[]; count: number; lines: number[]; pos: Array<{ counts: Map<string, number[]>; totals: Map<string, number> } | null> } function hasDigit(t: string): boolean { for (let i = 0; i < t.length; i++) if (t[i] >= "0" && t[i] <= "9") return true; return false; } function similarity(tpl: string[], toks: string[]): number { let same = 0; for (let i = 0; i < tpl.length; i++) if (tpl[i] === toks[i] || tpl[i] === "<*>" || toks[i] === "<*>") same++; return same / tpl.length; } export function lineShape(text: string): Shape | null { const all = text.split("\n"); if (all.length > 0 && all[all.length - 1] === "") all.pop(); if (all.length < SHAPE_MIN_ROWS) return null; const groups = new Map<string, Cluster[]>(); const clusters: Cluster[] = []; for (let n = 0; n < all.length; n++) { const raw = all[n].split(" ").filter((t) => t !== ""); const toks = raw.map((t) => (hasDigit(t) ? "<*>" : t)); const key = toks.length + " " + (toks[0] ?? ""); const group = groups.get(key) ?? []; let hit: Cluster | undefined; for (const c of group) if (similarity(c.tpl, toks) >= SHAPE_SIMILARITY) { hit = c; break; } if (hit === undefined) { hit = { tpl: [...toks], count: 0, lines: [], pos: raw.map(() => ({ counts: new Map(), totals: new Map() })) }; group.push(hit); groups.set(key, group); clusters.push(hit); if (clusters.length > SHAPE_MAX_CLUSTERS) return null; } else { for (let i = 0; i < hit.tpl.length; i++) if (hit.tpl[i] !== toks[i]) hit.tpl[i] = "<*>"; } hit.count++; if (hit.lines.length <= SHAPE_RARE_MAX) hit.lines.push(n); for (let i = 0; i < hit.pos.length; i++) { const p = hit.pos[i]; if (p === null) continue; p.totals.set(raw[i], (p.totals.get(raw[i]) ?? 0) + 1); const at = p.counts.get(raw[i]) ?? []; if (at.length <= SHAPE_RARE_MAX) at.push(n); p.counts.set(raw[i], at); if (p.totals.size > SHAPE_RARE_MAX + 1) hit.pos[i] = null; // a free field, not a skewed one } } const common = clusters.filter((c) => c.count > SHAPE_RARE_MAX); if (common.length === 0 || common.length > SHAPE_COMMON_MAX) return null; if (common.some((c) => c.tpl.every((t) => t === "<*>"))) return null; // no literal token: data, not a log const rare = new Set(clusters.filter((c) => c.count <= SHAPE_RARE_MAX).flatMap((c) => c.lines)); for (const c of common) for (const p of c.pos) if (p !== null) for (const n of rareOfSkewed(c.count, p.counts, p.totals)) rare.add(n); if (rare.size === 0 || rare.size > SHAPE_RARE_UNITS_MAX) return null; // Counts only: the templates stay in the index (the more line reaches them); the budget goes to rare lines. const header = all.length + " lines, " + rare.size + " rare:"; const units: Unit[] = [...rare].sort((a, b) => a - b).map((n) => { const line = n + 1 + ": " + all[n]; return { pos: n, rank: all[n], render: (budget: number) => (bytes(line) <= budget ? line : null) }; }); return { header, units }; } - src/prompt/instructions.md (509 bytes)
context-mode keeps large output out of the conversation. When a step counts, sums, filters or finds something in over about 20 lines of data (logs, test or build output, big JSON or CSV, long files, web pages), use ctx_execute and print only the answer, not a raw Bash or Read result. A large tool result is indexed and cut to its best-matching parts; ctx_search finds the rest. A large file's Read is denied: use offset and limit, or ctx_execute with file set. Use normal tools for small output and edits.
- stats.json (75 bytes)
{ "npm_downloads": 891959, "stars": 34343, "read_at": "2026-11-21" } - tsconfig.json (470 bytes)
{ "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "noEmit": true, "allowImportingTsExtensions": true, "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "isolatedModules": true }, "include": ["src/core", "src/prompt", "src/entries", "src/cli", "src/setup", "src/adapters", "build/**/*.ts"] }