context-doctor 0.35.1 → 0.36.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.
package/README.md CHANGED
@@ -21,7 +21,7 @@ Pick where you work. Each takes about a minute and is fully reversible.
21
21
  | You use | Do this |
22
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 and Gemini CLI: 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
+ | **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` |
25
25
  | **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
26
  | **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
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)) |
@@ -100,6 +100,7 @@ On a Claude subscription you do not pay list price; the same tokens come out of
100
100
  | **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
101
  | **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
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 |
103
+ | **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 five 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) |
103
104
  | **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)) |
104
105
  | **Claude Desktop chat** | The five standing rules below in every chat; 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 | One-click `.mcpb` install, `context_checkup` prompt ([chat apps](./docs/chat-apps.md)) |
105
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` |
@@ -119,7 +120,7 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
119
120
 
120
121
  | Command | What it does |
121
122
  |---|---|
122
- | `context-doctor install` / `uninstall` | Wire (or remove) everything it finds: the MCP server for Claude Desktop, Claude Code, Cursor, Codex and Gemini CLI; 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. `--statusline` adds the status bar line ([details](./docs/install.md)) |
123
+ | `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)) |
123
124
  | `context-doctor doctor` | Self-check the whole installation — one pasteable ✓/✗ diagnosis with fixes |
124
125
  | `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 |
125
126
  | `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)) |
@@ -149,16 +150,17 @@ The MCP server hands these standing rules, verbatim, to every chat where it is e
149
150
  | `context-doctor ci [--base <ref>] [--max-tokens n] [--max-increase n] [--markdown]` | Memory files (CLAUDE.md, AGENTS.md, GEMINI.md, rules, their imports) at HEAD vs a base commit; exit 1 over budget. What the GitHub Action runs ([details](./docs/ci.md)) |
150
151
  | `context-doctor init [preset]` | Write a `.contextdoctorrc` from a preset (`chat`, `agent`, `batch`) — a budget you can adopt in one command and tune later |
151
152
  | `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)) |
153
+ | `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)) |
152
154
  | `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)) |
153
- | `context-doctor hook` | The every-prompt hook (Claude Code, Codex, Gemini CLI, Cursor) and Claude Code's compaction hook, registered by `install`; you never run this yourself. Warning threshold tunable via `CONTEXT_DOCTOR_WARN_TOKENS` (default 80000) |
155
+ | `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) |
154
156
  | `context-doctor --version` | Print the installed version. `--help` lists every flag |
155
157
 
156
158
  **Privacy:** everything runs on your machine. No API key is needed for anything core, nothing is sent anywhere, and no telemetry is collected; the proxy forwards your app's own credentials untouched and holds none of its own.
157
159
 
158
160
  ## What's new
159
161
 
162
+ - **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.
160
163
  - **0.35 Cache misses, a price before a model switch, and a QA pass fixed**: `context-doctor cache-misses` finds requests that re-wrote the prompt cache while it was still warm (on the author's history: 390 such misses, $1,925 above the cache-read price, 28% of all cache writes; claude-sonnet-5 missed on 10.4% of warm requests, claude-opus-5-5 on 0.11%) and says which model versions miss less; `savings` mentions them when they add up. On Claude Code 2.1.251+ a `PreModelSwitch` hook shows what a `/model` switch will cost before it happens. `pack` no longer reads `.env`, `.npmrc`, private keys or other credential files unless you pass `--include-secrets`, refuses `~/.ssh`-style folders, and survives unreadable files. Fixed from a QA pass: rc values warned as ignored were applied, near-duplicates were counted per pair (781 findings), autopilot's cleared results leaked between conversations reusing tool ids, a malformed config stopped `uninstall` midway, and more ([list](./ROADMAP.md#shipped-in-0350-cache-misses-a-model-switch-price-and-a-qa-pass)).
161
- - **0.34 Native idle compaction, automatic caching, Codex and Cursor fixes**: the cold-resume offer steps aside for Claude Code's own idle compaction (silent after it, still there for the 5-minute caches and sessions under 200k it skips), uses Claude Code's SessionStart verdict and price on a resumed session, and no longer offers `/compact` on a conversation that was just compacted. `cache-plan` uses Anthropic's automatic caching for the conversation's moving end and prices reads at each model's own rate. Codex on an API key is routed by `autopilot on` through `openai_base_url` (Codex no longer reads `OPENAI_BASE_URL`); ChatGPT sign-in is left alone. The OpenAI proxy adds a stable `prompt_cache_key` per conversation where the app sent none (models before GPT-5.6). Cursor gets `postToolUseFailure` and `sessionStart` hooks, and `doctor` says what your Cursor version does with the guidance. Measured and dropped: Anthropic's server-side tool-result clearing (7 to 14 of 37 replayed sessions more expensive). Re-run `context-doctor install` to add the new hooks.
162
164
 
163
165
  Every release: [docs/whats-new.md](./docs/whats-new.md).
164
166
 
@@ -177,6 +179,7 @@ Every release: [docs/whats-new.md](./docs/whats-new.md).
177
179
  - [Token counts](./docs/tokenizer.md): why counts are "~", how the Claude ratios were measured, exact counts
178
180
  - [Performance](./docs/performance.md): what context-doctor itself costs
179
181
  - [Experiment](./docs/experiment.md): does a smaller context actually help? Measure it
182
+ - [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
180
183
  - [What's new](./docs/whats-new.md), [Roadmap](./ROADMAP.md), [Python package](./python/README.md)
181
184
 
182
185
  ## Contributing
package/dist/ab.d.ts ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * `context-doctor ab`: does a lever cost quality? Each task of a small suite
3
+ * (abtasks.ts) runs with and without the lever, through the Messages API,
4
+ * with a minimal agent loop (read_file, write_file, run_check), and is
5
+ * scored by a hidden check the harness runs after the agent stops. Pass
6
+ * counts, tokens and cost per arm, side by side: "no quality loss" as a
7
+ * number rather than a proxy (re-reads, tool errors, corrections).
8
+ *
9
+ * Arms:
10
+ * none the baseline: a plain system prompt and the three tools
11
+ * rules + the standing context rules (what MCP clients and the
12
+ * Copilot hook inject) in the system prompt
13
+ * autoclear the client wrapped with withContextDoctor (autopilot in
14
+ * process), every request treated as after an idle gap so
15
+ * clearing is allowed on each one: the worst case for
16
+ * quality, not autopilot's real cost
17
+ * pack + a pack_context tool and the rule to use it for big
18
+ * files instead of reading them whole
19
+ * compact-generic one compaction mid-task with generic instructions; the
20
+ * session then continues from the summary alone
21
+ * compact the same compaction with the PreCompact hook's
22
+ * instructions (files changed, failing checks, the user's
23
+ * own instructions) added, as Claude Code merges them
24
+ *
25
+ * The agent's code runs (in the smoke test and the hidden check) with a
26
+ * minimal environment (no API key, a throwaway HOME), in its own process
27
+ * group, under a time limit; whatever it leaves running is killed and every
28
+ * temporary folder is removed, on errors and Ctrl-C too. It is a quality
29
+ * test, not a sandbox: the code runs as the user.
30
+ *
31
+ * It spends the caller's API budget, so the CLI prints the estimate first,
32
+ * needs --yes to send anything, and sends no request whose worst case
33
+ * (prompt as cache writes, max_tokens of output) would pass --budget. The
34
+ * provider is an interface: anthropicProvider() speaks the Messages API over
35
+ * fetch (this package has no runtime dependencies), and tests plug in a
36
+ * local mock server through ANTHROPIC_BASE_URL.
37
+ */
38
+ import { type AbTask } from "./abtasks.js";
39
+ import { type ModelPricing, type RecordedUsage } from "./pricing.js";
40
+ export declare const AB_LEVERS: readonly ["rules", "autoclear", "pack", "compact"];
41
+ export type AbLever = (typeof AB_LEVERS)[number];
42
+ export type AbArm = "none" | "rules" | "autoclear" | "pack" | "compact-generic" | "compact";
43
+ export declare const DEFAULT_AB_MODEL = "claude-opus-5-5";
44
+ /** The Messages API version the harness sends (sampling parameters are not sent). */
45
+ export declare const AB_API_VERSION = "2026-10-21";
46
+ export interface AbContentBlock {
47
+ type: string;
48
+ id?: string;
49
+ name?: string;
50
+ input?: Record<string, unknown>;
51
+ text?: string;
52
+ [key: string]: unknown;
53
+ }
54
+ export interface AbResponse {
55
+ content: AbContentBlock[];
56
+ stop_reason?: string;
57
+ usage?: RecordedUsage;
58
+ }
59
+ /** Anything that can answer a Messages API request. */
60
+ export interface AbProvider {
61
+ readonly name: string;
62
+ /** One request; rejects with an Error carrying `status` on an HTTP error. */
63
+ create(body: Record<string, unknown>): Promise<AbResponse>;
64
+ }
65
+ /**
66
+ * The Messages API over fetch. Retries what the API asks to be retried
67
+ * (429, 5xx, 529 overloaded) and what the network breaks (a refused
68
+ * connection, a body cut short, a 200 whose body is not the message), with
69
+ * backoff, honouring retry-after. Anything else is the caller's error and
70
+ * is thrown with its status, so the SDK wrapper can recognise a refused
71
+ * history edit and the suite can stop on a refused key.
72
+ */
73
+ export declare function anthropicProvider(options: {
74
+ apiKey: string;
75
+ baseUrl?: string;
76
+ retries?: number;
77
+ timeoutMs?: number;
78
+ }): AbProvider;
79
+ export interface AbRun {
80
+ task: string;
81
+ arm: AbArm;
82
+ rep: number;
83
+ /** The hidden check, run by the harness after the agent stopped. */
84
+ pass: boolean;
85
+ /** Why the loop ended: end_turn, turns (the cap), budget, error, or the API's stop_reason. */
86
+ stop: string;
87
+ error?: string;
88
+ requests: number;
89
+ inputTokens: number;
90
+ cacheReadTokens: number;
91
+ cacheWriteTokens: number;
92
+ outputTokens: number;
93
+ costUsd: number;
94
+ wallMs: number;
95
+ /** What the lever did: requests autopilot changed, pack_context calls, or compactions. */
96
+ leverUses: number;
97
+ /** autoclear: tokens it kept off the wire, over all requests. */
98
+ leverTokens: number;
99
+ }
100
+ /** Ends that say nothing about the lever: the API failed or declined, or the harness's own caps cut the run. */
101
+ export declare const STOPPED_EARLY: Set<string>;
102
+ export interface AbOptions {
103
+ provider: AbProvider;
104
+ model?: string;
105
+ tasks?: AbTask[];
106
+ levers?: readonly AbLever[];
107
+ repeat?: number;
108
+ /** Requests per run, the compaction's included, before the loop is stopped (default 16). */
109
+ maxTurns?: number;
110
+ /** No request is sent whose worst case would take the spend past this, USD. */
111
+ budgetUsd?: number;
112
+ /** Runs in flight at once (default 4). */
113
+ concurrency?: number;
114
+ /** compact arms: compact after this many requests (default 2). */
115
+ compactAfter?: number;
116
+ /** Time limit for each smoke test and hidden check, ms (default 30,000). */
117
+ checkTimeoutMs?: number;
118
+ /** Called as each run finishes. */
119
+ onRun?: (run: AbRun, done: number, total: number) => void;
120
+ }
121
+ /**
122
+ * The verdict on files as they stand, for the tests and the self-check:
123
+ * a fresh run folder with `files`, the hidden check, everything removed.
124
+ */
125
+ export declare function abVerify(task: AbTask, files?: Record<string, string>): Promise<boolean>;
126
+ /** The arms a set of levers needs: one shared baseline for rules, autoclear and pack; compact brings its own. */
127
+ export declare function armsFor(levers: readonly AbLever[]): AbArm[];
128
+ export interface AbEstimate {
129
+ runs: number;
130
+ /** With prompt caching: each token written once, then read at the cache rate. */
131
+ expectedUsd: number;
132
+ /** As if nothing cached: every request's whole prompt at the input rate. */
133
+ upperUsd: number;
134
+ }
135
+ /**
136
+ * A planning figure, not a quote: six requests a run, the task's files in
137
+ * context from the second request on, ~800 output tokens a request (thinking,
138
+ * tool calls, the files the agent writes).
139
+ */
140
+ export declare function estimateAb(tasks: AbTask[], arms: AbArm[], repeat: number, pricing: ModelPricing): AbEstimate;
141
+ export interface AbResult {
142
+ model: string;
143
+ provider: string;
144
+ tasks: string[];
145
+ levers: AbLever[];
146
+ arms: AbArm[];
147
+ repeat: number;
148
+ runs: AbRun[];
149
+ spentUsd: number;
150
+ /** Why the suite stopped before every run (the API refused the key). */
151
+ aborted?: string;
152
+ }
153
+ export declare function runAbSuite(options: AbOptions): Promise<AbResult>;
154
+ export interface ArmTotals {
155
+ runs: number;
156
+ /** Runs that ended on their own: the ones a pass rate is about. */
157
+ completed: number;
158
+ passed: number;
159
+ stoppedEarly: number;
160
+ tokens: number;
161
+ costUsd: number;
162
+ leverUses: number;
163
+ leverTokens: number;
164
+ }
165
+ /** Per arm: runs, completed runs and their passes, runs stopped early, billed tokens, cost. */
166
+ export declare function summarizeAb(result: AbResult): Record<string, ArmTotals>;
167
+ /** Arms every one of whose runs ended on an API error: nothing was measured there. */
168
+ export declare function erroredArms(result: AbResult): AbArm[];
169
+ export declare function renderAb(result: AbResult): string;
170
+ export interface AbCommandOptions {
171
+ levers?: string[];
172
+ tasks?: string[];
173
+ model?: string;
174
+ repeat?: number;
175
+ maxTurns?: number;
176
+ concurrency?: number;
177
+ budgetUsd?: number;
178
+ /** Spend: without it the plan and estimate are printed and nothing is sent. */
179
+ yes: boolean;
180
+ json: boolean;
181
+ out?: string;
182
+ list: boolean;
183
+ }
184
+ /**
185
+ * `context-doctor ab`: the exit code. 1 for a refusal, a bad argument, a key
186
+ * the API refused, or an arm all of whose runs ended on an API error.
187
+ */
188
+ export declare function abCommand(o: AbCommandOptions): Promise<number>;