context-doctor 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +33 -21
  2. package/dist/antigravity.d.ts +44 -0
  3. package/dist/antigravity.js +80 -0
  4. package/dist/autoclear.d.ts +11 -4
  5. package/dist/autoclear.js +52 -6
  6. package/dist/autopilot.d.ts +24 -0
  7. package/dist/autopilot.js +111 -2
  8. package/dist/cachemisses.d.ts +154 -3
  9. package/dist/cachemisses.js +359 -14
  10. package/dist/cachettl.d.ts +127 -0
  11. package/dist/cachettl.js +364 -0
  12. package/dist/claudedir.d.ts +17 -0
  13. package/dist/claudedir.js +32 -0
  14. package/dist/cli.js +378 -24
  15. package/dist/coldresume.js +2 -1
  16. package/dist/compactquality.js +2 -2
  17. package/dist/compactwindow.d.ts +15 -6
  18. package/dist/compactwindow.js +39 -35
  19. package/dist/doctor.d.ts +6 -0
  20. package/dist/doctor.js +118 -7
  21. package/dist/effective.d.ts +55 -0
  22. package/dist/effective.js +163 -0
  23. package/dist/experiment.js +2 -2
  24. package/dist/extract.js +4 -1
  25. package/dist/fanout.d.ts +131 -0
  26. package/dist/fanout.js +317 -0
  27. package/dist/fix.d.ts +176 -0
  28. package/dist/fix.js +569 -0
  29. package/dist/handoff.js +10 -0
  30. package/dist/hook.js +17 -2
  31. package/dist/install.d.ts +17 -1
  32. package/dist/install.js +176 -35
  33. package/dist/ledger.js +2 -2
  34. package/dist/lens.d.ts +56 -0
  35. package/dist/lens.js +213 -0
  36. package/dist/limits.d.ts +229 -0
  37. package/dist/limits.js +869 -0
  38. package/dist/mcp.d.ts +1 -0
  39. package/dist/mcp.js +64 -57
  40. package/dist/mcpclient.js +28 -28
  41. package/dist/mcpschema.d.ts +41 -1
  42. package/dist/mcpschema.js +105 -31
  43. package/dist/missledger.d.ts +61 -0
  44. package/dist/missledger.js +198 -0
  45. package/dist/overhead.js +21 -10
  46. package/dist/precompact.js +8 -7
  47. package/dist/pricing.d.ts +29 -2
  48. package/dist/pricing.js +46 -8
  49. package/dist/proxy.d.ts +5 -3
  50. package/dist/proxy.js +12 -7
  51. package/dist/prune.d.ts +116 -0
  52. package/dist/prune.js +429 -0
  53. package/dist/reads.js +2 -2
  54. package/dist/recall.d.ts +104 -0
  55. package/dist/recall.js +394 -0
  56. package/dist/savings.d.ts +3 -3
  57. package/dist/savings.js +23 -9
  58. package/dist/session.d.ts +4 -0
  59. package/dist/session.js +14 -16
  60. package/dist/settingsedit.d.ts +44 -0
  61. package/dist/settingsedit.js +282 -0
  62. package/dist/statusline.d.ts +43 -1
  63. package/dist/statusline.js +71 -2
  64. package/dist/subagentpay.d.ts +11 -0
  65. package/dist/subagentpay.js +3 -3
  66. package/dist/tasks.js +2 -2
  67. package/package.json +2 -2
  68. package/skills/context-doctor/SKILL.md +1 -0
package/README.md CHANGED
@@ -4,10 +4,11 @@
4
4
 
5
5
  **See where your AI agent's tokens go, and stop paying for the ones that do nothing.**
6
6
 
7
- AI agents re-send their whole context on every message: old tool output, pasted files, long instructions. A 500k-token session pays for all of it again each time, and at full price after a coffee break, when the prompt cache has expired. context-doctor measures that waste on your own sessions, in dollars, and removes it at the moments it pays: before it enters the context, while it sits there, and on every request. It runs on your machine, needs no API key, sends no telemetry, and works with **Claude Code, Claude Desktop, Cursor, Codex, Gemini CLI**, any app on the **Anthropic, OpenAI or Gemini API**, and **CI**. MIT licensed, Node 20+, macOS, Linux and Windows.
7
+ AI agents re-send their whole context on every message: old tool output, pasted files, long instructions. A 500k-token session pays for all of it again each time, and at full price after a coffee break, when the prompt cache has expired. context-doctor measures that waste on your own sessions, in dollars, and removes it at the moments it pays: before it enters the context, while it sits there, and on every request. It runs on your machine, needs no API key, sends no telemetry, and works with **Claude Code** (terminal, IDE, desktop app), **Claude Desktop, ChatGPT, Codex, Cursor, Gemini CLI, GitHub Copilot**, any app on the **Anthropic, OpenAI or Gemini API**, and **CI**. MIT licensed, Node 20+, macOS, Linux and Windows.
8
8
 
9
9
  ```bash
10
10
  npx context-doctor savings # what your recent sessions cost, and what each fix would have saved
11
+ npx context-doctor fix # the fixes ranked by dollars; applies only the ones you say yes to
11
12
  ```
12
13
 
13
14
  <img src="https://raw.githubusercontent.com/KushalP1/context-doctor/main/assets/savings.svg" alt="npx context-doctor savings: input billed, what /compact at cold resumes, autopilot and an earlier auto-compact window would have saved" width="640">
@@ -20,13 +21,13 @@ Pick where you work. Each takes about a minute and is fully reversible.
20
21
 
21
22
  | You use | Do this |
22
23
  |---|---|
23
- | **Claude Code** (terminal, IDE, desktop app) | Inside Claude Code: `/plugin marketplace add KushalP1/context-doctor`, then `/plugin install context-doctor@context-doctor`. You get the every-prompt check, the compaction hook, the MCP tools and `/context-doctor:savings`, `:checkup`, `:overhead`, `:pack`, `:autopilot`, `:compact-window` |
24
- | **Everything on this machine at once** | `npm install -g context-doctor && context-doctor install` wires Claude Code, Claude Desktop, Cursor, Codex, Gemini CLI and GitHub Copilot: MCP server, skill and hooks ([what it writes](./docs/install.md)). `context-doctor doctor` checks it; `context-doctor uninstall` removes it. Then, for Claude Code in a terminal or IDE, `context-doctor autopilot on` |
24
+ | **Claude Code** (terminal, IDE, desktop app) | Inside Claude Code: `/plugin marketplace add KushalP1/context-doctor`, then `/plugin install context-doctor@context-doctor`. You get the every-prompt check, the compaction hook, the MCP tools and `/context-doctor:fix`, `:savings`, `:checkup`, `:overhead`, `:pack`, `:autopilot`, `:compact-window` |
25
+ | **Everything on this machine at once** | `npm install -g context-doctor && context-doctor install` wires Claude Code, Claude Desktop, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot: MCP server, skill and hooks ([what it writes](./docs/install.md)). `context-doctor doctor` checks it; `context-doctor uninstall` removes it. Then, for Claude Code in a terminal or IDE, `context-doctor autopilot on` |
25
26
  | **Claude Desktop, Cursor or any MCP client** | Add the server to the client's MCP config (or install the one-click `.mcpb` from the [latest release](https://github.com/KushalP1/context-doctor/releases/latest) in Claude Desktop):<br>`{"mcpServers": {"context-doctor": {"command": "npx", "args": ["-y", "context-doctor", "mcp"]}}}` |
26
27
  | **claude.ai, ChatGPT, phone apps** | `npx context-doctor instructions --copy`, then paste into the app's personal preferences (it tells you where). ChatGPT can also reach the MCP server at a URL ([how](./docs/chat-apps.md#chatgpt)) |
27
- | **Your own app on an LLM API** | Run `npx context-doctor proxy --autopilot` and point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL` (add `/v1`) or `GOOGLE_GEMINI_BASE_URL` at `http://localhost:8787`. No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` ([library](./docs/library.md)) |
28
+ | **Your own app on an LLM API** | Run `npx context-doctor proxy --autopilot` and point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL` (add `/v1`) or `GOOGLE_GEMINI_BASE_URL` at the proxy on `127.0.0.1:8787`, plain HTTP ([exact values](./docs/proxy.md)). No proxy possible? Wrap the SDK client: `withContextDoctor(new Anthropic())` ([library](./docs/library.md)) |
28
29
  | **Python / RAG pipelines** | `pip install "git+https://github.com/KushalP1/context-doctor#subdirectory=python"` (PyPI release coming), then `pack_documents(retrieved_docs, question, budget=4000)` trims LangChain or LlamaIndex results to the chunks that matter. [Python README](./python/README.md) |
29
- | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.32.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
30
+ | **GitHub pull requests** | `uses: KushalP1/context-doctor@v0.38.0` comments how much a PR grows CLAUDE.md, AGENTS.md and rules, and can fail over a budget ([setup](./docs/ci.md)) |
30
31
 
31
32
  ## What it does
32
33
 
@@ -35,19 +36,23 @@ Pick where you work. Each takes about a minute and is fully reversible.
35
36
  - `overhead`: what every request re-reads before your message (system prompt, tools, MCP servers, CLAUDE.md, rules, memory), each file priced per month.
36
37
  - `tasks`, `reads`, `subagents`, `compactions`: cost per commit; files read into session after session; whether each subagent was cheaper than the same steps in the parent; whether sessions work worse after compacting.
37
38
  - `cache-misses`: requests that re-wrote the prompt cache while it should still have been warm, priced, by model and context size, with the cause where the transcript shows one.
39
+ - `limits`: your plan's 5-hour and weekly windows (Claude Pro/Max, recorded by the status line) and Codex's, the pace and when each runs out, and what 1M tokens of each kind cost in % of the limit, fitted on your own readings with the error shown.
38
40
  - `cache-plan <request.json>`: where an Anthropic API request should carry `cache_control`, and what it saves over N calls.
39
41
  - `session`, `watch`, `analyze`, `report`, `dashboard`: token breakdown and wasted-context findings for any session, conversation file or agent trace.
40
42
 
41
43
  **Keep waste out of the context** ([pack and overhead](./docs/pack-and-overhead.md))
42
44
  - `pack` (and the `pack_context` MCP tool): only the chunks of a big document, PDF, log or codebase that a question needs, within a token budget, instead of the whole thing.
45
+ - `recall` (and the `recall` MCP tool): the few lines of this session's own transcript a question needs, including turns a compaction summarised away and tool output autopilot cleared, with their time and position; secrets masked.
43
46
  - `overhead split`: turns a heavy CLAUDE.md or memory file into a lean one plus a reference file the agent opens when needed, word for word, nothing lost.
44
47
  - `ci` and the GitHub Action: review memory-file growth like any other cost.
45
48
 
46
49
  **Remove waste automatically**
47
50
  - A model-switch warning (`PreModelSwitch`, Claude Code 2.1.251+) shows what a `/model` switch costs before it happens: the whole context re-written into the new model's cache.
51
+ - A subagent price (`PreToolUse` on the Agent tool) shows what a subagent costs before it starts, at your own median for that type (the author's: $3.99 for general-purpose, $1.43 for Explore, 422 runs in 30 days), with the Sonnet price where it would run on Opus or Fable, and a total when launches bunch up. It never blocks.
48
52
  - A compaction hook (`PreCompact`) tells each Claude Code compaction what the session cannot lose (files changed, open tasks, your instructions, failing tests), so compacting saves tokens without losing the thread.
49
53
  - An every-prompt hook (Claude Code, Codex, Gemini CLI; Cursor after each tool call) tells the model its real context size and the largest waste, and offers `/compact` when you return to a big session after the cache expired.
50
54
  - `compact-window`: sets Claude Code's own auto-compact window, measured on your history first. Works in the desktop app too.
55
+ - `cache-ttl`: replays your own pauses at a 5-minute and a 1-hour prompt cache and sets Claude Code's `promptCacheTtl` to the cheaper one (the author's: 7% less main-conversation input at 1 hour; 22% less than the 5-minute default an API key gets). Same content either way, so no quality cost ([fixes](./docs/fix.md)).
51
56
  - [Autopilot](./docs/autopilot.md): a local proxy (or SDK wrapper) that clears stale tool output only when the prompt cache is cold, so a request never costs more.
52
57
 
53
58
  ## What it saves
@@ -99,11 +104,11 @@ On a Claude subscription you do not pay list price; the same tokens come out of
99
104
  | **Claude Code** in the desktop app's Code tab | **Hooks**, as above, the cold-resume `/compact` offer shown to you as well as the model. **`compact-window`**, if you set one: Claude Code compacts earlier by itself. Not autopilot: the app sets its own API address and ignores the one in settings | Same as above |
100
105
  | **Cursor** (agent) | A native **after-tool-call hook** (`~/.cursor/hooks.json`): in a heavy chat the agent gets the same hygiene guidance and the largest waste, once per 40% of growth. (Cursor's prompt hook can only allow or block a prompt, so this is the event where guidance reaches the model) | MCP tools, editor status bar extension, `cursor` profiler. With your own OpenAI key, autopilot too via a tokened tunnel ([how](./docs/proxy.md#putting-the-proxy-on-a-public-url-cursor-with-your-own-openai-key-remote-apps)) |
101
106
  | **Codex** (ChatGPT app's Codex tab, IDE extension, CLI) | Every-prompt hook with the API's own token counts | MCP tools, skill, `session` reads Codex rollouts. On an API key, autopilot too (`autopilot on` sets `openai_base_url` in `~/.codex/config.toml`; Codex no longer reads `OPENAI_BASE_URL`) |
102
- | **Gemini CLI** | Every-prompt hook (`BeforeAgent`) with the API's own token counts. On an API key, autopilot too: `GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:8787` (Google sign-in traffic goes elsewhere) | MCP tools, `session` and `watch` read its chats, `overhead` sizes GEMINI.md |
107
+ | **Gemini CLI** | Every-prompt hook (`BeforeAgent`) with the API's own token counts. On an API key, autopilot too: `GOOGLE_GEMINI_BASE_URL` set to the proxy on `127.0.0.1:8787`, plain HTTP (Google sign-in traffic goes elsewhere) | MCP tools, `session` and `watch` read its chats, `overhead` sizes GEMINI.md |
103
108
  | **GitHub Copilot** (Copilot CLI, the Copilot app, VS Code agent sessions) | A **session-start hook** (`~/.copilot/hooks/context-doctor.json`) gives every new or resumed session the standing rules. No size check: Copilot passes a transcript only to hooks that cannot add context | MCP tools (`~/.copilot/mcp-config.json`, which VS Code's Copilot sessions read too) |
104
109
  | **Your own apps on the Anthropic, OpenAI or Gemini API** | Autopilot on `/v1/messages`, `/v1/chat/completions`, `/v1/responses` and Gemini's `generateContent` (`ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` / `GOOGLE_GEMINI_BASE_URL`), or the optimizing proxy (which can cost more on cached traffic); no proxy possible (serverless, edge)? `withContextDoctor(client)` runs autopilot inside the SDK client | Exact usage and cache hit rates in `/stats`, prompt-cache placement advice ([proxy](./docs/proxy.md)) |
105
110
  | **Claude Desktop chat** | The six standing rules below, sent to every chat (whether classic Chat shows them to the model is unverified, [why](./docs/chat-apps.md)); one cheap `profile_context` call the model makes once at ~30 turns and on any cost question; `pack_context` instead of reading a big local file whole; a handoff offered once a chat is long, since a chat's history cannot be cut and a new chat can | One-click `.mcpb` install, `context_checkup`, `handoff` and `ask_file` prompts, `handoff://latest` to attach in the next chat ([handoff](./docs/handoff.md)) |
106
- | **claude.ai, ChatGPT, the phone apps** | Your account's standing preferences, pasted once ([Quick start](#quick-start)) | Profile an exported chat with `analyze` or `session` |
111
+ | **claude.ai, ChatGPT, the phone apps** | Your account's standing preferences, pasted once ([Quick start](#quick-start)) | Profile an exported chat with `analyze` or `session`. ChatGPT developer mode: the MCP tools at a URL, uploads into `pack_context` ([how](./docs/chat-apps.md#chatgpt)) |
107
112
  | **CI** | `analyze --fail-over-budget` fails a build whose prompts outgrow a budget; the GitHub Action gates memory-file growth | `.contextdoctorrc` budgets and presets ([CI](./docs/ci.md)) |
108
113
 
109
114
  Not claimed, because no process on your machine sends those requests: trimming inside Claude Desktop chat, claude.ai, ChatGPT, Cursor's own subscription models, or Codex signed in with ChatGPT. Those get the rules and the measurements above, not autopilot.
@@ -123,30 +128,35 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
123
128
 
124
129
  | Command | What it does |
125
130
  |---|---|
126
- | `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI and GitHub Copilot; the Agent Skill (Claude Code, Codex); the every-prompt hook (Claude Code, Codex, Gemini CLI's `BeforeAgent`, Cursor's `postToolUse`, `postToolUseFailure` and `sessionStart`); Claude Code's `PreCompact` and `SessionStart` hooks; Copilot's `sessionStart` (the standing rules). `--statusline` adds the status bar line ([details](./docs/install.md)) |
127
- | `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes |
131
+ | `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Google Antigravity and GitHub Copilot; the Agent Skill (Claude Code, Codex, Antigravity); the every-prompt hook (Claude Code, Codex, Gemini CLI's `BeforeAgent`, Cursor's `postToolUse`, `postToolUseFailure` and `sessionStart`); Claude Code's `PreCompact`, `SessionStart`, `PreToolUse` (the subagent price) and, on 2.1.251+, `PreModelSwitch` hooks; Copilot's `sessionStart` (the standing rules). `--statusline` adds the status bar line ([details](./docs/install.md)) |
132
+ | `context-doctor fix [--apply ids\|all] [--share]` / `fix undo` | Every lever ranked by what it would have saved on your last 30 days (compact earlier, the cache lifetime, autopilot, MCP tool search, unused servers), with what each costs in quality; applies one only on a yes, `fix undo` reverts exactly what it changed, later runs show what each saved since ([details](./docs/fix.md)) |
133
+ | `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes, including which surfaces autopilot can reach and any other program on its port |
128
134
  | `context-doctor savings [--days n] [--share [--copy]]` | What your recent Claude Code sessions cost, and what `/compact` at cold resumes, autopilot and an earlier auto-compact window would save, replayed through the shipped code against your actual billed usage. `--share` prints totals only (no project names or paths) to post. A bare `context-doctor` in a terminal shows the same |
129
135
  | `context-doctor autopilot on\|off\|pause\|resume\|status` | Every new Claude Code session started in a terminal or IDE goes through the local proxy, which clears stale tool output only when the prompt cache is cold: measured 12.7% less input cost, no session worse ([details](./docs/autopilot.md)) |
130
136
  | `context-doctor proxy --autopilot` | Local proxy for your own Anthropic, OpenAI and Gemini API apps: clears stale tool output only when the prompt cache is cold, so it never costs more. Plain `proxy` runs the optimizing strategies (dedupe, trim, strip base64), which can cost more on cached traffic. `--token` for a public URL; `/stats` for cumulative savings ([details](./docs/proxy.md)) |
131
137
  | `context-doctor compact-window [status\|off\|<size>]` | Replay your last 30 days at auto-compact windows from 200k to 800k: input cost, saving, and how many more compactions each means. `400k` (or `250000`, `0.4m`) sets Claude Code's `autoCompactWindow`, with a backup; `off` removes it. Works in every Claude Code surface, the desktop app included |
138
+ | `context-doctor cache-ttl [status\|1h\|5m\|off] [--subagents]` | The main conversation's (or subagents') prompt cache lifetime: what 5 minutes and 1 hour would each have cost on your last 30 days, then set or remove `promptCacheTtl` / `subagentPromptCacheTtl` (Claude Code 2.1.243+, every surface). Price only: the same content is sent ([details](./docs/fix.md)) |
132
139
  | `context-doctor instructions [--copy]` | The ~190-token standing rules (~130 on GPT) for claude.ai / ChatGPT preferences, for web and phones where no server runs |
133
140
  | `context-doctor handoff [list\|show <id>\|latest] [--copy]` | Handoffs saved from chat apps (the `handoff` prompt or `save_handoff`): list them, print one, or copy it to paste as a new chat's first message ([handoff](./docs/handoff.md)) |
134
141
  | `context-doctor mcp [--http]` | The MCP server as a subcommand, for clients and registries that launch `npx -y context-doctor mcp` |
135
- | `context-doctor-mcp` | The MCP server itself — stdio by default (what the installer wires); `--http [--port 8808] [--host H] [--allowed-hosts names] [--store-handoffs]` serves streamable HTTP at `/mcp` for URL-based clients like ChatGPT developer-mode connectors (only for the host names it knows: behind a tunnel, pass its name to `--allowed-hosts`) |
136
- | `context-doctor session [file]` | Profile a Claude Code session: live context, findings, **measured tokens and prompt-cache economics**, **where the wall clock went** per tool, and **what its subagents cost** (their own windows, your bill; never in the parent's profile). Also reads Codex rollouts, Gemini CLI chats and ChatGPT data exports (`conversations.json`); `--list` to browse |
142
+ | `context-doctor-mcp` | The MCP server itself — stdio by default (what the installer wires); `--http [--port 8808] [--host H] [--allowed-hosts names] [--allowed-origins list] [--store-handoffs]` serves streamable HTTP at `/mcp` for URL-based clients like ChatGPT developer-mode connectors (only for the host names it knows: behind a tunnel, pass its name to `--allowed-hosts`) |
143
+ | `context-doctor session [file]` | Profile a Claude Code session: live context, findings, **measured tokens and prompt-cache economics**, **where the wall clock went** per tool, output's and reasoning's share of the cost, repeated identical (polling) tool calls priced, and **what its subagents cost** (their own windows, your bill; never in the parent's profile). Also reads Codex rollouts, Gemini CLI chats and ChatGPT data exports (`conversations.json`); `--list` to browse |
137
144
  | `context-doctor watch [file]` | Live monitor of a growing session transcript or agent trace (Claude Code / Codex JSONL, or a plain OpenAI/Anthropic conversation JSON file): token/cost line per change, findings as they appear |
138
145
  | `context-doctor cursor [--list]` | Profile a chat from Cursor's local history (both storage formats) |
139
146
  | `context-doctor analyze <file>` | Profile a conversation: token breakdown, findings, cost + latency estimates. `--exact` adds a true count; `--fail-over-budget` exits 1 on a breach, for CI |
140
147
  | `context-doctor optimize <file>` | Apply the safe fixes; add `--strategy trim-tool-calls` for big inline file writes, `--strategy prune-history` for consented lossy compaction ([what each does](./docs/detectors.md)) |
141
148
  | `context-doctor diff <before> <after>` | Compare two profiles: what moved by category, which findings were resolved or introduced, and what it saves in money and latency |
142
149
  | `context-doctor overhead [--days n] [--mcp]` | What every request re-reads before your message: measured first-request size (Claude Code, Codex and Gemini CLI sessions), each memory file (CLAUDE.md and imports, rules, auto memory, AGENTS.md, Cursor rules, GEMINI.md) priced per month, MCP calls per server; `--mcp` sizes each configured server's tool definitions and flags unused ones |
150
+ | `context-doctor overhead prune [--days n] [--write] [--undo]` | Per project, the MCP servers and skills its sessions never used in n days; `--write` switches them off for this folder's project in its `.claude/settings.local.json` (backup kept, every entry recorded), `--undo` takes exactly those out. Never the app's connectors, plugins, or context-doctor itself |
143
151
  | `context-doctor overhead split <file> [--min-tokens n] [--write]` | Move a memory file's big or code-heavy sections word for word to `<name>.reference.md`, leaving pointers; indexes stay. A plan until `--write`, which backs up first |
144
152
  | `context-doctor pack <files\|dirs\|-> -q "…"` | Only the chunks of big documents, logs or code a question needs, ranked and fit to `--max-tokens` (default 4000). No query: an outline; `--ids a#2,b#5` picks chunks from it. `--semantic` also ranks by meaning with a local Ollama model. Offline, no key |
153
+ | `context-doctor recall "<query>" [--session <id\|path>]` | Search this session's own transcript on disk (Claude Code or Codex; turns before a compaction and tool output cleared from the context included) and print the best excerpts with time and position, secrets masked. Never another project's session unless named with `--session`. Also the `recall` MCP tool |
145
154
  | `context-doctor tasks [--days n]` | Cost per commit, per project: each session priced from its recorded usage against the commits it made |
146
155
  | `context-doctor reads [--days n] [--limit n]` | Files read into session after session: reads, tokens, cost, and whether a CLAUDE.md summary or `pack` pays |
147
156
  | `context-doctor subagents [--days n]` | Which subagents paid for themselves: each one's bill vs the same steps run in the parent session |
148
157
  | `context-doctor compactions [--days n]` | Do sessions work worse right after compacting? Re-reads, tool errors and your corrections, before vs after each compaction |
149
- | `context-doctor cache-misses [--days n]` | Requests that re-wrote the prompt cache within its lifetime (no compaction between, previous context over 20k, over 60% of it written again): priced above the cache-read rate, by model and context size, with the cause where visible and the model versions that miss less; `--json` per model |
158
+ | `context-doctor cache-misses [--days n]` | Requests that re-wrote the prompt cache within its lifetime (no compaction between, previous context over 20k, over 60% of it written again): priced above the cache-read rate, by model and context size, with the cause where visible and the model versions that miss less; by Claude Code version, with step changes after an upgrade flagged (the 1-hour cache share, the first request's size, a model's miss rate); `--json` per model and version |
159
+ | `context-doctor limits [--days n]` | Your plan's limits in their own unit: each window's %, pace and run-out time (Claude's 5-hour and weekly windows from the status line's readings, Codex's from its rollouts), and % of the limit per 1M tokens of input, cache read, cache write and output, fitted on your readings with the fit's error; too-thin data is said to be thin, never quoted |
150
160
  | `context-doctor cache-plan <request.json> [--calls n] [--out file] [--explicit]` | Where an Anthropic API request should carry `cache_control` (top-level automatic caching for the moving end, unless `--explicit`), and what it saves over n calls; `--out` writes it applied |
151
161
  | `context-doctor accuracy` | How much of what you are billed for is visible in your transcript (the fixed harness baseline, per-turn injected content), plus a tokenizer check: real chars/token per model from the API's own counts, next to the ratio the estimator uses |
152
162
  | `context-doctor report` | Machine-wide impact report (proxy savings persist across restarts): exact proxy savings, hook activity, how often the cold-resume `/compact` offer was followed by a compaction, recoverable waste in recent sessions |
@@ -155,7 +165,7 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
155
165
  | `context-doctor init [preset]` | Write a `.contextdoctorrc` from a preset (`chat`, `agent`, `batch`) — a budget you can adopt in one command and tune later |
156
166
  | `context-doctor experiment --task "…"` | Run one task twice from the same commit, in a fresh session and forked from an `--existing` one, same model and tools; compare bill, cache split, wall clock, and whether `--check` passed. The only command here that spends money, so it caps spend per arm and refuses a dirty tree ([details](./docs/experiment.md)) |
157
167
  | `context-doctor ab [--lever …] [--yes]` | Does a lever cost quality? Eight small coding tasks, each a tiny repository scored by a hidden check, run with and without the standing rules, autopilot's clearing, `pack_context` or the PreCompact instructions through the Messages API; pass counts, tokens and cost side by side. Bills `ANTHROPIC_API_KEY`: prints the estimate, sends nothing without `--yes`, stops at `--budget` ([details](./docs/ab.md)) |
158
- | `context-doctor statusline` | Claude Code status bar: live context vs window, cache share, cost. Wired by `install --statusline`; never overwrites a statusLine you already have ([details](./docs/editor-and-statusline.md)) |
168
+ | `context-doctor statusline` | Claude Code status bar: live context vs window, cache share, cost, and (Claude Code 2.1.251+) until when the cache is warm and what the next turn costs once it is cold. Wired by `install --statusline`; never overwrites a statusLine you already have ([details](./docs/editor-and-statusline.md)) |
159
169
  | `context-doctor hook` | The every-prompt hook (Claude Code, Codex, Gemini CLI, Cursor) and Claude Code's compaction hook, registered by `install`; `hook copilot` is GitHub Copilot's session-start hook; you never run these yourself. Warning threshold tunable via `CONTEXT_DOCTOR_WARN_TOKENS` (default 80000) |
160
170
  | `context-doctor --version` | Print the installed version. `--help` lists every flag |
161
171
 
@@ -163,27 +173,29 @@ Rules 1-4 end exactly at character 512, the part ChatGPT's guide says must stand
163
173
 
164
174
  ## What's new
165
175
 
176
+ - **0.39 `fix`, the cache lifetime, the cache clock, and Antigravity**: `context-doctor fix` turns the measurements into changes: every lever ranked by what it would have saved on your own sessions, with what each costs in quality, applied only on a yes, undone with `fix undo`, and re-measured afterwards (`/context-doctor:fix` in the plugin). `cache-ttl` replays your pauses at a 5-minute and a 1-hour prompt cache and sets Claude Code's `promptCacheTtl` to the cheaper one, a price-only change. On Claude Code 2.1.251+ the status line says until when the cache is warm and what going cold costs, `cache-misses` explains misses in Claude Code's own words, and `install` wires Google Antigravity.
177
+ - **0.38 Your limits in their own unit, regressions after upgrades, recall, and a subagent price**: `context-doctor limits` shows each plan window's %, pace and run-out time (Claude Pro/Max through the status line, Codex from its rollouts) and what 1M tokens cost in % of it, fitted on your readings with the error; `savings` then speaks in your limit too. `cache-misses` flags step changes after a Claude Code upgrade, `recall` searches the session's own transcript (compacted turns included), a hook prices a subagent before it starts (never blocking), and `overhead prune` switches off unused MCP servers and skills per project, reversibly. OpenAI caches count as warm for up to 24 hours. An independent QA pass's findings were fixed before the release.
166
178
  - **0.37 Desktop chat apps: a handoff, uploads, compact results, and a security pass**: a chat app's history cannot be edited, so the `handoff` prompt (Claude Desktop's **+** menu) has the model write a ≤400-token brief and save it with `save_handoff` (secrets masked, `handoff://latest` to attach in the next chat, the per-turn saving reported: a 52k-token chat drops to ~600). `ask_file` answers from a big file through `pack_context`, which over `--http` also takes ChatGPT uploads; ChatGPT gets compact results. An independent QA pass's eleven findings were fixed with tests; **behind a tunnel, `--http` now needs `--allowed-hosts <tunnel host>`** ([handoff](./docs/handoff.md)).
167
- - **0.36 GitHub Copilot, and a quality test for every lever**: `install` wires GitHub Copilot (CLI, app, VS Code agent sessions): the MCP server, and a session-start hook that gives each new or resumed session the standing rules (no size check: Copilot gives no transcript to the hooks that could add context). `context-doctor ab` runs eight small coding tasks, scored by hidden checks, with and without each lever (the standing rules, autopilot's clearing, `pack_context`, the PreCompact instructions) through the Messages API and puts pass counts, tokens and cost side by side; it bills your key, prints the estimate first, sends nothing without `--yes` and never passes `--budget` ([details](./docs/ab.md)). Not yet run on a real key, so no pass rates are claimed.
168
179
 
169
- Every release: [docs/whats-new.md](./docs/whats-new.md).
180
+ Every release, with the details: [docs/whats-new.md](./docs/whats-new.md).
170
181
 
171
182
  ## Documentation
172
183
 
173
184
  - [What `install` does](./docs/install.md): every file it writes, what runs in each session after, and when you need MCP
174
185
  - [Autopilot](./docs/autopilot.md): how it clears stale tool output, and why it never costs more
186
+ - [Fixes](./docs/fix.md): `fix` (one plan, applied with consent, undone in one step, re-measured) and `cache-ttl`
175
187
  - [The proxy](./docs/proxy.md): autopilot and the optimizing mode for your API apps, `/stats`, cache advice, a public URL for Cursor
176
- - [Chat apps](./docs/chat-apps.md): Claude Desktop, ChatGPT, claude.ai and the phone apps; what acts by itself and what only nudges; the MCP tools
177
- - [Profiling](./docs/profiling.md): conversations, sessions, prompt-cache economics, subagents, `report`, sharing a profile safely
178
- - [Pack and overhead](./docs/pack-and-overhead.md): keep big documents and fixed overhead out of the context
188
+ - [Chat apps](./docs/chat-apps.md): Claude Desktop, ChatGPT, claude.ai and the phone apps; what acts by itself and what only nudges; the MCP tools, prompts and resources
189
+ - [Handoff](./docs/handoff.md): continue a long chat in a new one from a ≤400-token brief
190
+ - [Profiling](./docs/profiling.md): sessions, prompt-cache economics, subagents, `tasks`, `reads`, `compactions`, `cache-misses`, `limits`, `report`
191
+ - [Pack and overhead](./docs/pack-and-overhead.md): `pack`, `recall`, `overhead`, `overhead split` and `overhead prune`
179
192
  - [Detectors and fixes](./docs/detectors.md): what the profiler finds and what each optimizer strategy changes
180
193
  - [Library](./docs/library.md): `profileConversation`, `optimizeConversation`, `packContext`, `withContextDoctor`
181
194
  - [Budgets and CI](./docs/ci.md): the GitHub Action and `.contextdoctorrc`
182
195
  - [Editor and status line](./docs/editor-and-statusline.md): the VS Code / Cursor extension and Claude Code's status bar
183
196
  - [Token counts](./docs/tokenizer.md): why counts are "~", how the Claude ratios were measured, exact counts
184
- - [Performance](./docs/performance.md): what context-doctor itself costs
185
- - [Experiment](./docs/experiment.md): does a smaller context actually help? Measure it
186
- - [A/B suite](./docs/ab.md): does a lever cost quality? Eight small coding tasks, each run with and without it and scored by a hidden check
197
+ - [Performance](./docs/performance.md): what context-doctor itself costs (its six MCP tool definitions: at most ~2,344 tokens)
198
+ - [Experiment](./docs/experiment.md) and [A/B suite](./docs/ab.md): does a smaller context help, and does a lever cost quality? Measured on real tasks
187
199
  - [What's new](./docs/whats-new.md), [Roadmap](./ROADMAP.md), [Python package](./python/README.md)
188
200
 
189
201
  ## Contributing
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Google Antigravity: the app, the IDE and the CLI. Checked 2026-10-27
3
+ * against antigravity.google/docs (mcp, skills, hooks) and the 2.12.0 app on
4
+ * the author's machine:
5
+ *
6
+ * - MCP: `~/.gemini/config/mcp_config.json` for the IDE and the CLI, the
7
+ * same `{"mcpServers": {name: {command, args, env, disabled, ...}}}` shape
8
+ * as Claude Desktop's. The app manages it in its settings; on the author's
9
+ * machine its own `~/.gemini/antigravity/mcp_config.json` is a symlink to
10
+ * that file, with a `.migrated` marker beside it. An install from before
11
+ * that move has only the app's file, so that one is used when the shared
12
+ * folder does not exist yet.
13
+ * - Skills: `~/.gemini/config/skills/<name>/SKILL.md` for the app and the
14
+ * IDE, `~/.gemini/antigravity-cli/skills/<name>/` for the CLI; the same
15
+ * SKILL.md format as Claude Code (`description` required).
16
+ * - Hooks (`~/.gemini/config/hooks.json`, `injectSteps`) are not installed.
17
+ * They pass a `transcriptPath`, but its format is undocumented and no
18
+ * transcript exists on the author's machine (the 13 `brain/` folders have
19
+ * empty `logs/`), so the every-prompt size check has nothing it can read;
20
+ * and the standing rules already arrive with the MCP server.
21
+ *
22
+ * `~/.gemini` alone is not Antigravity: Gemini CLI creates it too. Its own
23
+ * folders are what count.
24
+ */
25
+ /** The folders Antigravity creates: the shared config, and the app's, the IDE's and the CLI's data. */
26
+ export declare function antigravityDirs(): string[];
27
+ export declare function antigravityPresent(): boolean;
28
+ /** The app's own MCP file: before the shared config folder, the only one. */
29
+ export declare function antigravityLegacyMcpConfigPath(): string;
30
+ /**
31
+ * The MCP file to write: the shared one, unless this install predates it
32
+ * (no config folder, and the app's file is a real file, not the symlink the
33
+ * migration leaves).
34
+ */
35
+ export declare function antigravityMcpConfigPath(): string;
36
+ /**
37
+ * Where our skill goes: the shared skills folder (app and IDE) when the
38
+ * shared config folder exists, else the IDE's legacy one, which it still
39
+ * reads; and the CLI's own when the CLI is here. No folder of Antigravity's
40
+ * is created that it did not have.
41
+ */
42
+ export declare function antigravitySkillDirs(): string[];
43
+ /** Every place a skill of ours may be, for uninstall and doctor. */
44
+ export declare function antigravityAllSkillDirs(): string[];
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Google Antigravity: the app, the IDE and the CLI. Checked 2026-10-27
3
+ * against antigravity.google/docs (mcp, skills, hooks) and the 2.12.0 app on
4
+ * the author's machine:
5
+ *
6
+ * - MCP: `~/.gemini/config/mcp_config.json` for the IDE and the CLI, the
7
+ * same `{"mcpServers": {name: {command, args, env, disabled, ...}}}` shape
8
+ * as Claude Desktop's. The app manages it in its settings; on the author's
9
+ * machine its own `~/.gemini/antigravity/mcp_config.json` is a symlink to
10
+ * that file, with a `.migrated` marker beside it. An install from before
11
+ * that move has only the app's file, so that one is used when the shared
12
+ * folder does not exist yet.
13
+ * - Skills: `~/.gemini/config/skills/<name>/SKILL.md` for the app and the
14
+ * IDE, `~/.gemini/antigravity-cli/skills/<name>/` for the CLI; the same
15
+ * SKILL.md format as Claude Code (`description` required).
16
+ * - Hooks (`~/.gemini/config/hooks.json`, `injectSteps`) are not installed.
17
+ * They pass a `transcriptPath`, but its format is undocumented and no
18
+ * transcript exists on the author's machine (the 13 `brain/` folders have
19
+ * empty `logs/`), so the every-prompt size check has nothing it can read;
20
+ * and the standing rules already arrive with the MCP server.
21
+ *
22
+ * `~/.gemini` alone is not Antigravity: Gemini CLI creates it too. Its own
23
+ * folders are what count.
24
+ */
25
+ import { existsSync, lstatSync } from "node:fs";
26
+ import { homedir } from "node:os";
27
+ import { join } from "node:path";
28
+ function gemini() {
29
+ return join(homedir(), ".gemini");
30
+ }
31
+ /** The folders Antigravity creates: the shared config, and the app's, the IDE's and the CLI's data. */
32
+ export function antigravityDirs() {
33
+ return ["config", "antigravity", "antigravity-ide", "antigravity-cli"].map((d) => join(gemini(), d));
34
+ }
35
+ export function antigravityPresent() {
36
+ return antigravityDirs().some((d) => existsSync(d));
37
+ }
38
+ /** The app's own MCP file: before the shared config folder, the only one. */
39
+ export function antigravityLegacyMcpConfigPath() {
40
+ return join(gemini(), "antigravity", "mcp_config.json");
41
+ }
42
+ /**
43
+ * The MCP file to write: the shared one, unless this install predates it
44
+ * (no config folder, and the app's file is a real file, not the symlink the
45
+ * migration leaves).
46
+ */
47
+ export function antigravityMcpConfigPath() {
48
+ const shared = join(gemini(), "config", "mcp_config.json");
49
+ if (existsSync(join(gemini(), "config")))
50
+ return shared;
51
+ const legacy = antigravityLegacyMcpConfigPath();
52
+ try {
53
+ if (lstatSync(legacy).isFile())
54
+ return legacy;
55
+ }
56
+ catch {
57
+ /* absent */
58
+ }
59
+ return shared;
60
+ }
61
+ /**
62
+ * Where our skill goes: the shared skills folder (app and IDE) when the
63
+ * shared config folder exists, else the IDE's legacy one, which it still
64
+ * reads; and the CLI's own when the CLI is here. No folder of Antigravity's
65
+ * is created that it did not have.
66
+ */
67
+ export function antigravitySkillDirs() {
68
+ const dirs = [];
69
+ if (existsSync(join(gemini(), "config")))
70
+ dirs.push(join(gemini(), "config", "skills", "context-doctor"));
71
+ else if (existsSync(join(gemini(), "antigravity")))
72
+ dirs.push(join(gemini(), "antigravity", "skills", "context-doctor"));
73
+ if (existsSync(join(gemini(), "antigravity-cli")))
74
+ dirs.push(join(gemini(), "antigravity-cli", "skills", "context-doctor"));
75
+ return dirs;
76
+ }
77
+ /** Every place a skill of ours may be, for uninstall and doctor. */
78
+ export function antigravityAllSkillDirs() {
79
+ return [join(gemini(), "config", "skills", "context-doctor"), join(gemini(), "antigravity", "skills", "context-doctor"), join(gemini(), "antigravity-cli", "skills", "context-doctor")];
80
+ }
@@ -130,14 +130,15 @@ interface View {
130
130
  seenUpTo: number;
131
131
  ttlMs: number;
132
132
  }
133
- export declare function clearedNote(tokens: number): string;
133
+ export declare function clearedNote(tokens: number, recall?: boolean): string;
134
+ /** GPT-5.6 or later (gpt-5.6-sol, gpt-6.1-sol...): the models that take prompt_cache_options. */
135
+ export declare function openAICacheOptionsModel(model: unknown): boolean;
134
136
  /**
135
137
  * How long the provider may keep this prompt cached, taking the LONGER
136
138
  * possibility when unsure: calling a warm cache cold would pay a rewrite,
137
139
  * calling a cold one warm only delays a free clearing.
138
140
  * - Anthropic: the request's own cache_control, "1h" or the 5-minute default.
139
- * - OpenAI: caches live up to an hour (in-memory retention), or 24 hours when
140
- * the request sets prompt_cache_retention "24h".
141
+ * - OpenAI: see openAITtlMs (24 hours unless the request says otherwise).
141
142
  */
142
143
  export declare function requestTtlMs(body: Record<string, unknown>): number;
143
144
  export declare function viewOf(body: Record<string, unknown>): View | undefined;
@@ -160,8 +161,14 @@ export declare class AutoClearer {
160
161
  * OpenAI Responses request. Never throws; anything unrecognised is left alone.
161
162
  * `account` names the credential the request carries (the proxy passes a
162
163
  * salted hash), for accounts whose API rejects edited history.
164
+ * `recallHint`: the client keeps a transcript recall can search (Claude
165
+ * Code); the cleared note then says where the full output still is. It
166
+ * must be the same on every request of a conversation (the note is part of
167
+ * the cached prefix), which a client's User-Agent is.
163
168
  */
164
- apply(body: Record<string, unknown>, now?: number, modelHint?: string, account?: string): AutoClearResult;
169
+ apply(body: Record<string, unknown>, now?: number, modelHint?: string, account?: string, opts?: {
170
+ recallHint?: boolean;
171
+ }): AutoClearResult;
165
172
  /**
166
173
  * Warm cache: clearing rewrites everything after the first cleared result
167
174
  * at the write rate (1.25x instead of 0.1x: 1.15x extra, once), and saves
package/dist/autoclear.js CHANGED
@@ -93,9 +93,14 @@ function lastIndex(items, pred) {
93
93
  return i;
94
94
  return -1;
95
95
  }
96
- export function clearedNote(tokens) {
96
+ export function clearedNote(tokens, recall = false) {
97
97
  // Not "run it again": a cleared Bash result may come from a command with
98
98
  // side effects (a push, a delete), and repeating that would be wrong.
99
+ // Claude Code keeps the original output in its transcript on disk, where
100
+ // recall finds it; other clients may keep no transcript, so they are not
101
+ // pointed there.
102
+ if (recall)
103
+ return `[context-doctor: old tool output cleared to keep context lean (~${tokens} tokens). The call above shows what ran; the full output is in the session transcript (the recall tool, or npx context-doctor recall "<words>"). Repeat the call only if it is read-only, otherwise ask the user.]`;
99
104
  return `[context-doctor: old tool output cleared to keep context lean (~${tokens} tokens). The call above shows what ran; repeat it only if it is read-only, otherwise ask the user.]`;
100
105
  }
101
106
  function resultTokens(content, model) {
@@ -114,13 +119,50 @@ function resultTokens(content, model) {
114
119
  }
115
120
  return n;
116
121
  }
122
+ /** GPT-5.6 or later (gpt-5.6-sol, gpt-6.1-sol...): the models that take prompt_cache_options. */
123
+ export function openAICacheOptionsModel(model) {
124
+ const m = /gpt-(\d+)(?:\.(\d+))?/i.exec(typeof model === "string" ? model : "");
125
+ if (!m)
126
+ return false;
127
+ const major = Number(m[1]), minor = Number(m[2] ?? 0);
128
+ return major > 5 || (major === 5 && minor >= 6);
129
+ }
130
+ /**
131
+ * How long OpenAI may keep this request's prompt cached, the longest it
132
+ * plausibly could. From OpenAI's prompt caching guide (read 2026-10-26):
133
+ * - GPT-5.6 and later set the lifetime with `prompt_cache_options.ttl`
134
+ * ("30m", the default, or "12h") and per breakpoint with
135
+ * `prompt_cache_breakpoint.ttl`; both are minimums ("OpenAI may retain
136
+ * entries longer than the requested minimum"; "12h" "does not set a
137
+ * deletion deadline"). Measured on the author's Codex history (gpt-5.6-sol,
138
+ * no ttl set): requests after 48- and 83-minute gaps read 100% from cache.
139
+ * - Earlier models use `prompt_cache_retention`: "in_memory" lasts "up to one
140
+ * hour", "24h" up to 24 hours, and organizations without Zero Data
141
+ * Retention default to "24h".
142
+ * - Any entry: "a maximum retention period of 24 hours".
143
+ * So 24 hours, unless the request asks an earlier model for "in_memory" (one
144
+ * hour; not GPT-5.5 or 5.5 Pro, which "support only 24h"), or uses explicit
145
+ * mode with no breakpoint, which caches nothing.
146
+ * Through 0.37 this was one hour unless "24h": a GPT-5.6 cache still warm at
147
+ * 83 minutes was called cold, and clearing it paid a rewrite.
148
+ */
149
+ function openAITtlMs(body) {
150
+ const options = body.prompt_cache_options;
151
+ const history = JSON.stringify(body.input ?? body.messages ?? "");
152
+ if (options && typeof options === "object" && options.mode === "explicit" && !history.includes('"prompt_cache_breakpoint"'))
153
+ return 0;
154
+ // GPT-5.5 and GPT-5.5 Pro support only "24h": an "in_memory" there is not what the cache does.
155
+ const only24h = /gpt-5\.5(?![\d.])/i.test(typeof body.model === "string" ? body.model : "");
156
+ if (!openAICacheOptionsModel(body.model) && !only24h && !options && body.prompt_cache_retention === "in_memory" && !history.includes('"prompt_cache_breakpoint"'))
157
+ return HOUR;
158
+ return 24 * HOUR;
159
+ }
117
160
  /**
118
161
  * How long the provider may keep this prompt cached, taking the LONGER
119
162
  * possibility when unsure: calling a warm cache cold would pay a rewrite,
120
163
  * calling a cold one warm only delays a free clearing.
121
164
  * - Anthropic: the request's own cache_control, "1h" or the 5-minute default.
122
- * - OpenAI: caches live up to an hour (in-memory retention), or 24 hours when
123
- * the request sets prompt_cache_retention "24h".
165
+ * - OpenAI: see openAITtlMs (24 hours unless the request says otherwise).
124
166
  */
125
167
  export function requestTtlMs(body) {
126
168
  // Gemini: implicit caching's lifetime is not published, explicit caches default to an hour.
@@ -128,7 +170,7 @@ export function requestTtlMs(body) {
128
170
  return HOUR;
129
171
  const openai = Array.isArray(body.input) || (Array.isArray(body.messages) && isOpenAIChat(body.messages));
130
172
  if (openai)
131
- return body.prompt_cache_retention === "24h" ? 24 * HOUR : HOUR;
173
+ return openAITtlMs(body);
132
174
  // Automatic caching puts cache_control at the top level of the request; a
133
175
  // 1-hour cache marked there was read as the 5-minute default, so autopilot
134
176
  // could clear into a cache that was still warm.
@@ -290,8 +332,12 @@ export class AutoClearer {
290
332
  * OpenAI Responses request. Never throws; anything unrecognised is left alone.
291
333
  * `account` names the credential the request carries (the proxy passes a
292
334
  * salted hash), for accounts whose API rejects edited history.
335
+ * `recallHint`: the client keeps a transcript recall can search (Claude
336
+ * Code); the cleared note then says where the full output still is. It
337
+ * must be the same on every request of a conversation (the note is part of
338
+ * the cached prefix), which a client's User-Agent is.
293
339
  */
294
- apply(body, now = Date.now(), modelHint, account) {
340
+ apply(body, now = Date.now(), modelHint, account, opts = {}) {
295
341
  const none = (reason, cold = false) => ({ changed: false, newlyCleared: 0, tokensRemoved: 0, cold, reason, firstChanged: -1, newIds: [], appliedIds: [] });
296
342
  try {
297
343
  const view = viewOf(body);
@@ -369,7 +415,7 @@ export class AutoClearer {
369
415
  const sk = scoped(key, r.id);
370
416
  if (!this.cleared.has(sk) || !eligibleIds.has(r.id))
371
417
  continue;
372
- const note = clearedNote(this.cleared.get(sk));
418
+ const note = clearedNote(this.cleared.get(sk), opts.recallHint === true);
373
419
  if (r.content === note)
374
420
  continue;
375
421
  removed += Math.max(0, r.tokens - estimateTokens(note, model));
@@ -67,6 +67,30 @@ export interface Health {
67
67
  version?: string;
68
68
  }
69
69
  export declare function health(port: number, timeoutMs?: number): Promise<Health>;
70
+ /** Who holds a local port: nobody, our proxy, or another program (named when it says). */
71
+ export interface PortOccupant {
72
+ /** Something answers a connection to 127.0.0.1:port. */
73
+ listening: boolean;
74
+ ours: boolean;
75
+ /** What the other program calls itself: its /health service, its Server header, or its process name. */
76
+ name?: string;
77
+ pid?: number;
78
+ /**
79
+ * Whether the proxy could bind 127.0.0.1:port beside it. On macOS a
80
+ * listener on 0.0.0.0, :: or ::1 leaves 127.0.0.1 free (the more specific
81
+ * address wins for 127.0.0.1 traffic); on Linux a 0.0.0.0 listener does not.
82
+ */
83
+ bindable?: boolean;
84
+ /** Another program on [::1]:port, where `localhost` may resolve, while 127.0.0.1 is ours or free. */
85
+ onIpv6Loopback?: string;
86
+ }
87
+ /**
88
+ * Whether something already listens on 127.0.0.1:`port`, whether it is this
89
+ * proxy (by its /health, however slowly it answers), whether the proxy could
90
+ * still bind 127.0.0.1 beside it, and whether another program holds
91
+ * [::1]:port, where `localhost` may go. Headroom's default port is 8787 too.
92
+ */
93
+ export declare function portOccupant(port: number, timeoutMs?: number): Promise<PortOccupant>;
70
94
  export declare function baseUrlToRestore(paths: AutopilotPaths, port: number, current: string | null): string | null;
71
95
  /** Which Claude Code surfaces ran recent sessions: entrypoint -> count. */
72
96
  export declare function recentSurfaces(days?: number, home?: string): Map<string, number>;
package/dist/autopilot.js CHANGED
@@ -26,10 +26,11 @@ import { fileURLToPath } from "node:url";
26
26
  import { isEphemeralPath, readJson, writeJsonWithBackup } from "./install.js";
27
27
  import { formatTokens } from "./tokens.js";
28
28
  import { codexAuthMode, codexHomeIn, codexRouting, routeCodex, unrouteCodex } from "./codexroute.js";
29
+ import { claudeDir } from "./claudedir.js";
29
30
  export const DEFAULT_AUTOPILOT_PORT = 8787;
30
31
  const LABEL = "com.gai-ventures.context-doctor.proxy";
31
32
  export function autopilotPaths(home = homedir()) {
32
- const dir = join(home, ".claude");
33
+ const dir = claudeDir(home);
33
34
  return {
34
35
  settings: join(dir, "settings.json"),
35
36
  config: join(dir, ".context-doctor-autopilot.json"),
@@ -270,6 +271,114 @@ export async function health(port, timeoutMs = 800) {
270
271
  return { ok: false };
271
272
  }
272
273
  }
274
+ const isOurHealth = (j) => j?.service === "context-doctor-proxy";
275
+ /** GET a local URL's /health (or /) and say who it is, without throwing. */
276
+ async function probe(base, timeoutMs) {
277
+ for (const path of ["/health", "/"]) {
278
+ try {
279
+ const r = await fetch(`${base}${path}`, { signal: AbortSignal.timeout(timeoutMs) });
280
+ const text = (await r.text()).slice(0, 2000);
281
+ let j;
282
+ try {
283
+ j = JSON.parse(text);
284
+ }
285
+ catch { /* not JSON */ }
286
+ if (isOurHealth(j))
287
+ return { ours: true };
288
+ const service = j?.service ?? j?.name ?? j?.app;
289
+ const named = typeof service === "string" && service.trim() ? service : /headroom/i.test(text) ? "headroom" : r.headers.get("server") ?? undefined;
290
+ if (named)
291
+ return { ours: false, name: named.replace(/[\u0000-\u001f]/g, "").slice(0, 60) };
292
+ if (path === "/")
293
+ return { ours: false };
294
+ }
295
+ catch {
296
+ /* not HTTP, or slow */
297
+ }
298
+ }
299
+ return undefined;
300
+ }
301
+ async function connects(host, port, timeoutMs) {
302
+ const { createConnection } = await import("node:net");
303
+ return new Promise((resolve) => {
304
+ const socket = createConnection({ host, port });
305
+ const done = (v) => { socket.destroy(); resolve(v); };
306
+ socket.setTimeout(timeoutMs, () => done(false));
307
+ socket.once("connect", () => done(true));
308
+ socket.once("error", () => done(false));
309
+ });
310
+ }
311
+ async function canBind(port) {
312
+ const { createServer } = await import("node:net");
313
+ return new Promise((resolve) => {
314
+ const s = createServer();
315
+ s.once("error", () => resolve(false));
316
+ s.listen(port, "127.0.0.1", () => s.close(() => resolve(true)));
317
+ });
318
+ }
319
+ /** The process listening on a TCP port: lsof on macOS and Linux, netstat and tasklist on Windows; nothing when neither can say. */
320
+ function listenerProcess(port) {
321
+ try {
322
+ if (platform() === "win32") {
323
+ const net = execFileSync("netstat", ["-ano", "-p", "TCP"], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
324
+ const line = net.split(/\r?\n/).find((l) => new RegExp(`:${port}\\s+\\S+\\s+LISTENING\\s+\\d+`, "i").test(l));
325
+ const pid = Number(/LISTENING\s+(\d+)/i.exec(line ?? "")?.[1]);
326
+ if (!(pid > 0))
327
+ return {};
328
+ let command;
329
+ try {
330
+ const task = execFileSync("tasklist", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] });
331
+ command = /^"([^"]+)"/.exec(task.trim())?.[1];
332
+ }
333
+ catch { /* the pid alone */ }
334
+ return { pid, command };
335
+ }
336
+ const out = execFileSync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpc"], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] });
337
+ const pid = Number(/^p(\d+)/m.exec(out)?.[1]);
338
+ return { pid: pid > 0 ? pid : undefined, command: /^c(.+)$/m.exec(out)?.[1] };
339
+ }
340
+ catch {
341
+ return {}; // no lsof (minimal Linux), no netstat, or nothing it can see
342
+ }
343
+ }
344
+ /**
345
+ * Whether something already listens on 127.0.0.1:`port`, whether it is this
346
+ * proxy (by its /health, however slowly it answers), whether the proxy could
347
+ * still bind 127.0.0.1 beside it, and whether another program holds
348
+ * [::1]:port, where `localhost` may go. Headroom's default port is 8787 too.
349
+ */
350
+ export async function portOccupant(port, timeoutMs = 2000) {
351
+ const h = await health(port, timeoutMs);
352
+ const ipv6 = async () => {
353
+ if (!(await connects("::1", port, 500)))
354
+ return undefined;
355
+ const p = await probe(`http://[::1]:${port}`, timeoutMs);
356
+ return p && !p.ours ? p.name ?? "another program" : undefined;
357
+ };
358
+ if (h.ok) {
359
+ const other = await ipv6();
360
+ return { listening: true, ours: true, ...(other ? { onIpv6Loopback: other } : {}) };
361
+ }
362
+ if (!(await connects("127.0.0.1", port, timeoutMs))) {
363
+ const other = await ipv6();
364
+ return { listening: false, ours: false, ...(other ? { onIpv6Loopback: other } : {}) };
365
+ }
366
+ const who = await probe(proxyUrl(port), timeoutMs);
367
+ // Our own proxy, answering /health too slowly the first time.
368
+ if (who?.ours)
369
+ return { listening: true, ours: true };
370
+ const out = { listening: true, ours: false, bindable: await canBind(port) };
371
+ if (who?.name)
372
+ out.name = who.name;
373
+ const proc = listenerProcess(port);
374
+ if (proc.pid)
375
+ out.pid = proc.pid;
376
+ if (proc.command && !out.name)
377
+ out.name = proc.command.slice(0, 60);
378
+ else if (proc.command && out.name && !out.name.toLowerCase().includes(proc.command.toLowerCase()))
379
+ out.name = `${out.name} (${proc.command.slice(0, 40)})`;
380
+ return out;
381
+ }
273
382
  async function waitHealthy(port, ms) {
274
383
  const end = Date.now() + ms;
275
384
  for (;;) {
@@ -322,7 +431,7 @@ function readConfig(paths) {
322
431
  /** Which Claude Code surfaces ran recent sessions: entrypoint -> count. */
323
432
  export function recentSurfaces(days = 30, home = homedir()) {
324
433
  const out = new Map();
325
- const root = join(home, ".claude", "projects");
434
+ const root = join(claudeDir(home), "projects");
326
435
  const since = Date.now() - days * 86_400_000;
327
436
  let dirs = [];
328
437
  try {