context-doctor 0.32.0 → 0.33.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/dist/cli.js CHANGED
@@ -8,20 +8,23 @@
8
8
  * `-` reads from stdin, so you can pipe: `cat chat.json | context-doctor analyze -`
9
9
  */
10
10
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
11
+ import { homedir } from "node:os";
11
12
  import { join } from "node:path";
12
13
  import process from "node:process";
13
14
  import { parseConversation } from "./parse.js";
14
15
  import { profileConversation } from "./profile.js";
15
- import { optimizeConversation } from "./optimize.js";
16
+ import { optimizeConversation, STRATEGY_IDS } from "./optimize.js";
17
+ import { commandHelp, didYouMean } from "./clihelp.js";
18
+ import { selfCommand, withInvocation } from "./invocation.js";
16
19
  import { renderProfile } from "./report.js";
17
20
  import { formatTokens } from "./tokens.js";
18
21
  import { startProxy } from "./proxy.js";
19
22
  import { runInstall, runUninstall } from "./install.js";
20
- import { listSessions, parseSessionFile } from "./session.js";
23
+ import { listSessions, parseSessionFile, pickCurrentSession } from "./session.js";
21
24
  import { runHook } from "./hook.js";
22
25
  import { buildImpactReport } from "./impact.js";
23
26
  import { measureTokenizer, renderTokenizer } from "./tokenizer-measure.js";
24
- import { autopilotOff, autopilotOn, autopilotPause, autopilotPaths, autopilotStatus, DEFAULT_AUTOPILOT_PORT } from "./autopilot.js";
27
+ import { autopilotOff, autopilotOn, autopilotPauseResult, autopilotPaths, autopilotStatus, DEFAULT_AUTOPILOT_PORT } from "./autopilot.js";
25
28
  import { estimateSavings, renderSavings, renderShare } from "./savings.js";
26
29
  import { currentCompactWindow, estimateCompactWindows, MAX_WINDOW, MIN_WINDOW, parseWindow, renderCompactWindows, setCompactWindow } from "./compactwindow.js";
27
30
  import { renderPreferences, copyToClipboard, CHAT_PREFERENCES } from "./preferences.js";
@@ -52,76 +55,78 @@ import { renderPayback, subagentPayback } from "./subagentpay.js";
52
55
  import { compactionQuality, renderCompactionQuality } from "./compactquality.js";
53
56
  const HELP = `context-doctor — profile and optimize LLM context windows
54
57
 
55
- Usage:
56
- context-doctor analyze <file|-> [options] Show what's eating your tokens
57
- context-doctor optimize <file|-> [options] Apply safe fixes, print slimmed conversation
58
- context-doctor proxy [options] Always-on: local proxy that optimizes every
59
- Anthropic/OpenAI API request in flight
60
- context-doctor install Wire the MCP server + skill into Claude Desktop,
61
- Claude Code, and Cursor automatically
62
- context-doctor uninstall Undo install
63
- context-doctor --version Print the installed version
58
+ Start here:
59
+ context-doctor install [--statusline] Wire everything it finds: the MCP server (Claude
60
+ Desktop, Claude Code, Cursor, Codex, Gemini CLI),
61
+ the skill (Claude Code, Codex), the every-prompt
62
+ hook (Claude Code, Codex, Gemini CLI's BeforeAgent,
63
+ Cursor's postToolUse) and Claude Code's PreCompact
64
+ hook, which tells each compaction what to keep
64
65
  context-doctor savings [--days n] [--share [--copy]]
65
66
  What your recent Claude Code sessions cost, and what
66
- /compact at cold resumes and autopilot would save,
67
- replayed and priced as billed. --share: totals only,
68
- to paste. Also what a bare \`context-doctor\` shows
69
- context-doctor compact-window [status|off|<size>]
70
- Claude Code's own auto-compact window (e.g. 400k):
71
- what each size would have saved on your sessions,
72
- and set or remove it. Works in the desktop app too
73
- context-doctor autopilot on|off|pause|resume|status
74
- Every new Claude Code session goes through the
75
- local proxy, which clears stale tool output only
76
- when the prompt cache is cold (never costs more)
77
- context-doctor mcp [--http] The MCP server (same as context-doctor-mcp), for clients
78
- that launch \`npx -y context-doctor mcp\`
79
- context-doctor instructions [--copy] Standing context rules to paste into claude.ai or
80
- ChatGPT preferences (works on web and mobile too)
81
- context-doctor session [file] Profile a Claude Code session transcript or a
82
- ChatGPT export (default: most recent; --list to browse)
83
- context-doctor cursor [--list] Profile a Cursor chat from its local history
84
- context-doctor statusline Claude Code status bar line: live context size, cache
85
- share, cost (wired by \`install --statusline\`; reads
86
- the status JSON on stdin)
87
- context-doctor hook Claude Code UserPromptSubmit hook (installed
88
- automatically by \`install\`; reads hook JSON on stdin)
89
- context-doctor report Impact report: exact proxy savings, hook activity,
90
- and remaining recoverable waste in recent sessions
67
+ /compact at cold resumes, autopilot and an earlier
68
+ auto-compact window would save, replayed and priced
69
+ as billed. --share: totals only, to paste. Also
70
+ what a bare \`context-doctor\` shows
91
71
  context-doctor doctor Self-check the installation (configs, hook, skill,
92
72
  MCP handshake) with one pasteable diagnosis
93
- context-doctor dashboard Local savings dashboard on 127.0.0.1 (--port n,
94
- default 8790) — charts from your own machine only
95
- context-doctor init [preset] Write a .contextdoctorrc from a preset
96
- (chat, agent, batch; no argument lists them)
97
- context-doctor experiment --task "<t>" Run one task twice from the same commit, in a fresh
98
- session and forked from an --existing one; compare
99
- bill, cache, time, and whether --check passed
100
- context-doctor diff <before> <after> Compare two profiles: what moved, which findings
101
- were resolved, and what it saves
102
- context-doctor accuracy Measure the token heuristic against the API's own
103
- counts recorded in your transcripts (--limit n)
73
+ context-doctor uninstall Undo install
74
+ context-doctor --version Print the installed version
75
+
76
+ Measure:
77
+ context-doctor analyze <file|-> [options] Show what's eating your tokens
78
+ context-doctor session [file] Profile a Claude Code session transcript or a
79
+ ChatGPT export (default: this session; --list to browse)
80
+ context-doctor cursor [--list] Profile a Cursor chat from its local history
104
81
  context-doctor overhead [--days n] [--mcp] What every request re-reads before your message:
105
82
  measured first-request size, each CLAUDE.md /
106
83
  AGENTS.md / rules file priced per month, findings
107
- context-doctor ci [--base <ref>] [--max-tokens n] [--max-increase n] [--markdown]
108
- For pull requests: memory files (CLAUDE.md, AGENTS.md,
109
- GEMINI.md, rules) at HEAD vs base; exit 1 over budget
110
- context-doctor cache-plan <request.json> [--calls n] [--out file]
111
- Where an Anthropic request should carry cache_control,
112
- what it saves over n calls; --out writes it applied
113
- context-doctor compactions [--days n] Do sessions work worse right after compacting? Re-reads,
114
- tool errors and your corrections, before vs after
84
+ context-doctor report Impact report: exact proxy savings, hook activity,
85
+ and remaining recoverable waste in recent sessions
115
86
  context-doctor subagents [--days n] Which subagents paid for themselves: their bill vs
116
- what carrying their reads would have cost the parent
87
+ the same steps run in the parent session
117
88
  context-doctor tasks [--days n] Cost per commit, per project: session cost at list
118
89
  price vs commits made during the sessions
119
90
  context-doctor reads [--days n] [--limit n] Files read into session after session: reads, tokens,
120
91
  cost, and whether a CLAUDE.md summary or pack pays
121
- context-doctor overhead split <file> [--write]
92
+ context-doctor compactions [--days n] Do sessions work worse right after compacting? Re-reads,
93
+ tool errors and your corrections, before vs after
94
+ context-doctor accuracy Measure the token heuristic against the API's own
95
+ counts recorded in your transcripts (--limit n)
96
+ context-doctor diff <before> <after> Compare two profiles: what moved, which findings
97
+ were resolved, and what it saves
98
+ context-doctor watch [file] Live-monitor a growing session/agent trace: running
99
+ token/cost line per change, new findings as they appear
100
+ (--interval-ms n, default 2000)
101
+ context-doctor dashboard Local savings dashboard on 127.0.0.1 (--port n,
102
+ default 8790) — charts from your own machine only
103
+ context-doctor experiment --task "<t>" Run one task twice from the same commit, in a fresh
104
+ session and forked from an --existing one; compare
105
+ bill, cache, time, and whether --check passed
106
+
107
+ Fix automatically:
108
+ context-doctor autopilot on|off|pause|resume|status
109
+ Every new Claude Code session started in a terminal
110
+ or IDE goes through the local proxy, which clears
111
+ stale tool output only when the prompt cache is
112
+ cold (never costs more). The desktop app's Code tab
113
+ sets its own API address, so it is not reached
114
+ context-doctor compact-window [status|off|<size>]
115
+ Claude Code's own auto-compact window (e.g. 400k):
116
+ what each size would have saved on your sessions,
117
+ and set or remove it. Works in the desktop app too
118
+ context-doctor proxy --autopilot [options] Local proxy for your own API apps (Anthropic, OpenAI,
119
+ Gemini): clears stale tool output only when the
120
+ prompt cache is cold, so it never costs more.
121
+ Plain \`proxy\` is the optimizing mode (dedupe, trim,
122
+ strip base64), which can cost more on cached traffic
123
+
124
+ Fix on request:
125
+ context-doctor optimize <file|-> [options] Apply safe fixes, print slimmed conversation
126
+ context-doctor overhead split <file> [--min-tokens n] [--write]
122
127
  Move a memory file's big sections to a reference
123
128
  file, leaving pointers (plan first; --write backs up)
124
- context-doctor pack <files|dirs...> --query "<q>" [--max-tokens n]
129
+ context-doctor pack <files|dirs...|-> -q "<q>" [--max-tokens n]
125
130
  Only the parts of big docs/code a question needs:
126
131
  chunk along headings and declarations, rank, fit a
127
132
  token budget (default 4000). No --query: an outline
@@ -129,9 +134,27 @@ Usage:
129
134
  --semantic: also rank by meaning with a local
130
135
  Ollama embedding model, when one is installed
131
136
  (--embed-model <name> picks it)
132
- context-doctor watch [file] Live-monitor a growing session/agent trace: running
133
- token/cost line per change, new findings as they appear
134
- (--interval-ms n, default 2000)
137
+ context-doctor cache-plan <request.json> [--calls n] [--out file]
138
+ Where an Anthropic request should carry cache_control,
139
+ what it saves over n calls; --out writes it applied
140
+
141
+ Integrations:
142
+ context-doctor ci [--base <ref>] [--max-tokens n] [--max-increase n] [--markdown]
143
+ For pull requests: memory files (CLAUDE.md, AGENTS.md,
144
+ GEMINI.md, rules) at HEAD vs base; exit 1 over budget
145
+ context-doctor instructions [--copy] Standing context rules to paste into claude.ai or
146
+ ChatGPT preferences (works on web and mobile too)
147
+ context-doctor init [preset] Write a .contextdoctorrc from a preset
148
+ (chat, agent, batch; no argument lists them)
149
+
150
+ Internal (Claude Code and MCP clients run these for you):
151
+ context-doctor hook The every-prompt and PreCompact hook (installed by
152
+ \`install\`; reads hook JSON on stdin)
153
+ context-doctor statusline Claude Code status bar line: live context size, cache
154
+ share, cost (wired by \`install --statusline\`; reads
155
+ the status JSON on stdin)
156
+ context-doctor mcp [--http] The MCP server (same as context-doctor-mcp), for clients
157
+ that launch \`npx -y context-doctor mcp\`
135
158
 
136
159
  Project config: an optional .contextdoctorrc (nearest, walking up from cwd, then
137
160
  ~/.contextdoctorrc) can set a context budget and default strategies:
@@ -157,7 +180,16 @@ Options:
157
180
  Default: dedupe, trim-tool-results, strip-base64 (lossless-ish set)
158
181
  --keep-recent <n> (optimize) Messages at the tail to leave untouched (default 6)
159
182
  --max-tool-tokens <n> (optimize) Token budget for trimmed tool results (default 300)
160
- --limit <n> (accuracy, session --list) Sessions to sample or list (default 20)
183
+ --limit <n> (accuracy, session --list, reads, tasks, subagents) How many to sample
184
+ or list
185
+ --days <n> (savings, compact-window, overhead, reads, tasks, subagents, compactions)
186
+ Days of history to read (default 30; compactions 60)
187
+ -q, --query <text> (pack) The question to rank chunks against
188
+ --max-tokens <n> (pack) Token budget (default 4000); (ci) fail over this many tokens
189
+ --chunk-tokens <n> (pack) Largest chunk, in tokens (default 400)
190
+ --ids <a#2,b#5> (pack) Return these chunks by id
191
+ --min-tokens <n> (overhead split) Smallest section to move, in tokens (default 400)
192
+ --requests-per-day <n> (ci --markdown) Price the change at this many requests a day
161
193
  --check <cmd> (experiment) Command whose exit code is the pass/fail for each arm
162
194
  --existing <id> (experiment) Session id to fork the second arm from (never mutated)
163
195
  --budget <usd> (experiment) Spend cap per arm (default 1)
@@ -165,6 +197,8 @@ Options:
165
197
  --allow-dirty (experiment) Skip the clean-tree check (uncommitted changes will be lost)
166
198
  --statusline (install) Also set Claude Code's statusLine to context-doctor (never
167
199
  overwrites a statusLine you already have)
200
+ --autopilot (proxy) Cold-cache clearing only, the mode \`autopilot on\` runs; never
201
+ costs more. Without it the proxy runs the optimizing strategies
168
202
  --port <n> (proxy) Port to listen on (default 8787)
169
203
  --host <addr> (proxy) Bind address (default 127.0.0.1; use 0.0.0.0 to expose)
170
204
  --token <secret> (proxy) Require /t/<secret>/ in every request path; needed before
@@ -174,170 +208,163 @@ Options:
174
208
  "keepRecent":n,"maxToolResultTokens":n}]} — first prefix match wins
175
209
  --upstream-anthropic <url> (proxy) Override Anthropic upstream (testing)
176
210
  --upstream-openai <url> (proxy) Override OpenAI upstream (testing)
211
+ --upstream-google <url> (proxy) Override Gemini upstream (testing)
177
212
  -h, --help Show this help
178
213
 
179
214
  Examples:
180
215
  context-doctor analyze chat.json --model claude-sonnet-5
181
216
  context-doctor optimize chat.json --strategy dedupe --strategy prune-history --out slim.json
182
- context-doctor proxy --port 8787
217
+ context-doctor proxy --autopilot --port 8787
183
218
  then: export ANTHROPIC_BASE_URL=http://localhost:8787
184
219
  export OPENAI_BASE_URL=http://localhost:8787/v1
220
+ export GOOGLE_GEMINI_BASE_URL=http://localhost:8787
185
221
  `;
222
+ /**
223
+ * What a bare `context-doctor` prints when there is no Claude Code history
224
+ * to measure, or when stdout is not a terminal: where to begin, in a dozen
225
+ * lines, instead of the full reference above.
226
+ */
227
+ const START_HERE = `context-doctor: see where your Claude Code tokens go, and cut them.
228
+
229
+ Start here
230
+ In Claude Code, as a plugin:
231
+ /plugin marketplace add KushalP1/context-doctor
232
+ /plugin install context-doctor@context-doctor
233
+ then /context-doctor:savings, :checkup, :overhead, :compact-window, :autopilot, :pack
234
+ In a terminal:
235
+ context-doctor install wire the MCP server, skill and hooks into the apps it finds
236
+ context-doctor savings what your recent sessions cost, and what each fix would save
237
+ context-doctor doctor check the installation
238
+
239
+ All commands: context-doctor --help
240
+ Guide: https://github.com/KushalP1/context-doctor#readme`;
241
+ /** Exit 1 with a usage message: wrong arguments are the caller's to fix, not a crash. */
242
+ function usageError(message) {
243
+ console.error(message);
244
+ process.exit(1);
245
+ }
246
+ /**
247
+ * Every command main() handles. An unknown one is an error with a
248
+ * suggestion, never a silent fall-through to the help text.
249
+ */
250
+ const COMMANDS = [
251
+ "analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
252
+ "instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
253
+ "experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "subagents", "tasks",
254
+ "reads", "pack", "watch", "help", "version",
255
+ ];
256
+ /** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
257
+ function strategyArg(v) {
258
+ if (STRATEGY_IDS.includes(v))
259
+ return v;
260
+ return usageError(`--strategy "${v}" is not a strategy.${didYouMean(v, STRATEGY_IDS)} Available: ${STRATEGY_IDS.join(", ")}.`);
261
+ }
262
+ const FLAGS = [
263
+ { names: ["--json"], set: (a) => { a.json = true; } },
264
+ { names: ["--list"], set: (a) => { a.list = true; } },
265
+ { names: ["--exact"], set: (a) => { a.exact = true; } },
266
+ { names: ["--redact"], set: (a) => { a.redact = true; } },
267
+ { names: ["--fail-over-budget"], set: (a) => { a.failOverBudget = true; } },
268
+ { names: ["--model"], value: "text", set: (a, v) => { a.model = v; } },
269
+ { names: ["--out"], value: "text", set: (a, v) => { a.out = v; } },
270
+ { names: ["--strategy"], value: "text", set: (a, v) => { a.strategies.push(strategyArg(v)); } },
271
+ { names: ["--keep-recent"], value: "number", num: { min: 0, integer: true }, set: (a, v) => { a.keepRecent = v; } },
272
+ { names: ["--max-tool-tokens"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.maxToolTokens = v; } },
273
+ { names: ["--port"], value: "number", num: { min: 0, max: 65535, integer: true }, set: (a, v) => { a.port = v; } },
274
+ { names: ["--interval-ms"], value: "number", num: { min: 100, integer: true }, set: (a, v) => { a.intervalMs = v; } },
275
+ { names: ["--limit"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.limit = v; } },
276
+ { names: ["--task"], value: "text", set: (a, v) => { a.task = v; } },
277
+ { names: ["--check"], value: "text", set: (a, v) => { a.check = v; } },
278
+ { names: ["--existing"], value: "text", set: (a, v) => { a.existing = v; } },
279
+ { names: ["--budget"], value: "number", num: { min: 0 }, set: (a, v) => { a.budgetUsd = v; } },
280
+ { names: ["--dry-run"], set: (a) => { a.dryRun = true; } },
281
+ { names: ["--copy"], set: (a) => { a.copy = true; } },
282
+ { names: ["--share"], set: (a) => { a.share = true; } },
283
+ { names: ["--allow-dirty"], set: (a) => { a.allowDirty = true; } },
284
+ { names: ["--statusline"], set: (a) => { a.statusLine = true; } },
285
+ { names: ["--host"], value: "text", set: (a, v) => { a.host = v; } },
286
+ { names: ["--token"], value: "text", set: (a, v) => { a.token = v; } },
287
+ { names: ["--days"], value: "number", num: { min: 1 }, set: (a, v) => { a.days = v; } },
288
+ { names: ["--autopilot"], set: (a) => { a.autopilot = true; } },
289
+ { names: ["--autopilot-state"], value: "text", set: (a, v) => { a.autopilotState = v; } },
290
+ { names: ["--autopilot-pause-file"], value: "text", set: (a, v) => { a.autopilotPauseFile = v; } },
291
+ { names: ["--config"], value: "text", set: (a, v) => { a.config = v; } },
292
+ { names: ["-q", "--query"], value: "text", set: (a, v) => { a.query = v; } },
293
+ { names: ["--max-tokens"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.maxTokens = v; } },
294
+ { names: ["--chunk-tokens"], value: "number", num: { min: 50, integer: true }, set: (a, v) => { a.chunkTokens = v; } },
295
+ { names: ["--mcp"], set: (a) => { a.mcp = true; } },
296
+ { names: ["--write"], set: (a) => { a.write = true; } },
297
+ { names: ["--calls"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.calls = v; } },
298
+ { names: ["--semantic"], set: (a) => { a.semantic = a.semantic || true; } },
299
+ { names: ["--embed-model"], value: "text", set: (a, v) => { a.semantic = v; } },
300
+ { names: ["--base"], value: "text", set: (a, v) => { a.base = v; } },
301
+ { names: ["--markdown"], set: (a) => { a.markdown = true; } },
302
+ { names: ["--max-increase"], value: "number", num: { min: 0, integer: true }, set: (a, v) => { a.maxIncrease = v; } },
303
+ { names: ["--requests-per-day"], value: "number", num: { min: 1 }, set: (a, v) => { a.requestsPerDay = v; } },
304
+ { names: ["--min-tokens"], value: "number", num: { min: 50, integer: true }, set: (a, v) => { a.minTokens = v; } },
305
+ { names: ["--ids"], value: "text", set: (a, v) => { a.ids = v.split(",").map((x) => x.trim()).filter(Boolean); } },
306
+ { names: ["--upstream-anthropic"], value: "text", set: (a, v) => { a.upstreamAnthropic = v; } },
307
+ { names: ["--upstream-openai"], value: "text", set: (a, v) => { a.upstreamOpenai = v; } },
308
+ { names: ["--upstream-google"], value: "text", set: (a, v) => { a.upstreamGoogle = v; } },
309
+ // Read by the MCP server itself: `mcp --http [--port n] [--host h]`.
310
+ { names: ["--http"], set: () => { } },
311
+ ];
312
+ const FLAG_BY_NAME = new Map(FLAGS.flatMap((f) => f.names.map((n) => [n, f])));
313
+ const FLAG_NAMES = [...FLAG_BY_NAME.keys(), "--help", "--version"];
314
+ /** An option, not a value: "-q", "--days". "-" (stdin) and "-1" are values. */
315
+ function looksLikeFlag(s) {
316
+ return /^-[A-Za-z-]/.test(s) && s !== "--";
317
+ }
186
318
  function parseArgs(argv) {
187
- const args = { json: false, strategies: [], list: false, exact: false, redact: false, failOverBudget: false, dryRun: false, allowDirty: false, statusLine: false };
319
+ const args = { json: false, strategies: [], list: false, exact: false, redact: false, failOverBudget: false, dryRun: false, allowDirty: false, statusLine: false, help: false };
188
320
  const positional = [];
189
321
  for (let i = 0; i < argv.length; i++) {
190
- const a = argv[i];
191
- switch (a) {
192
- case "-h":
193
- case "--help":
194
- console.log(HELP);
195
- process.exit(0);
196
- case "-v":
197
- case "--version":
198
- console.log(packageVersion());
199
- process.exit(0);
200
- case "--json":
201
- args.json = true;
202
- break;
203
- case "--list":
204
- args.list = true;
205
- break;
206
- case "--exact":
207
- args.exact = true;
208
- break;
209
- case "--redact":
210
- args.redact = true;
211
- break;
212
- case "--fail-over-budget":
213
- args.failOverBudget = true;
214
- break;
215
- case "--model":
216
- args.model = argv[++i];
217
- break;
218
- case "--out":
219
- args.out = argv[++i];
220
- break;
221
- case "--strategy":
222
- args.strategies.push(argv[++i]);
223
- break;
224
- case "--keep-recent":
225
- args.keepRecent = numArg("--keep-recent", argv[++i], { min: 0, integer: true });
226
- break;
227
- case "--max-tool-tokens":
228
- args.maxToolTokens = numArg("--max-tool-tokens", argv[++i], { min: 1, integer: true });
229
- break;
230
- case "--port":
231
- args.port = numArg("--port", argv[++i], { min: 0, max: 65535, integer: true });
232
- break;
233
- case "--interval-ms":
234
- args.intervalMs = numArg("--interval-ms", argv[++i], { min: 100, integer: true });
235
- break;
236
- case "--limit":
237
- args.limit = numArg("--limit", argv[++i], { min: 1, integer: true });
238
- break;
239
- case "--task":
240
- args.task = argv[++i];
241
- break;
242
- case "--check":
243
- args.check = argv[++i];
244
- break;
245
- case "--existing":
246
- args.existing = argv[++i];
247
- break;
248
- case "--budget":
249
- args.budgetUsd = numArg("--budget", argv[++i], { min: 0 });
250
- break;
251
- case "--dry-run":
252
- args.dryRun = true;
253
- break;
254
- case "--copy":
255
- args.copy = true;
256
- break;
257
- case "--share":
258
- args.share = true;
259
- break;
260
- case "--allow-dirty":
261
- args.allowDirty = true;
262
- break;
263
- case "--statusline":
264
- args.statusLine = true;
265
- break;
266
- case "--host":
267
- args.host = argv[++i];
268
- break;
269
- case "--token":
270
- args.token = argv[++i];
271
- break;
272
- case "--days":
273
- args.days = numArg("--days", argv[++i], { min: 1 });
274
- break;
275
- case "--autopilot":
276
- args.autopilot = true;
277
- break;
278
- case "--autopilot-state":
279
- args.autopilotState = argv[++i];
280
- break;
281
- case "--autopilot-pause-file":
282
- args.autopilotPauseFile = argv[++i];
283
- break;
284
- case "--config":
285
- args.config = argv[++i];
286
- break;
287
- case "-q":
288
- case "--query":
289
- args.query = argv[++i];
290
- break;
291
- case "--max-tokens":
292
- args.maxTokens = numArg("--max-tokens", argv[++i], { min: 1, integer: true });
293
- break;
294
- case "--chunk-tokens":
295
- args.chunkTokens = numArg("--chunk-tokens", argv[++i], { min: 50, integer: true });
296
- break;
297
- case "--mcp":
298
- args.mcp = true;
299
- break;
300
- case "--write":
301
- args.write = true;
302
- break;
303
- case "--calls":
304
- args.calls = numArg("--calls", argv[++i], { min: 1, integer: true });
305
- break;
306
- case "--semantic":
307
- args.semantic = args.semantic || true;
308
- break;
309
- case "--embed-model":
310
- args.semantic = argv[++i];
311
- break;
312
- case "--base":
313
- args.base = argv[++i];
314
- break;
315
- case "--markdown":
316
- args.markdown = true;
317
- break;
318
- case "--max-increase":
319
- args.maxIncrease = numArg("--max-increase", argv[++i], { min: 0, integer: true });
320
- break;
321
- case "--requests-per-day":
322
- args.requestsPerDay = numArg("--requests-per-day", argv[++i], { min: 1 });
323
- break;
324
- case "--min-tokens":
325
- args.minTokens = numArg("--min-tokens", argv[++i], { min: 50, integer: true });
326
- break;
327
- case "--ids":
328
- args.ids = (argv[++i] ?? "").split(",").map((x) => x.trim()).filter(Boolean);
329
- break;
330
- case "--upstream-anthropic":
331
- args.upstreamAnthropic = argv[++i];
332
- break;
333
- case "--upstream-openai":
334
- args.upstreamOpenai = argv[++i];
335
- break;
336
- case "--upstream-google":
337
- args.upstreamGoogle = argv[++i];
338
- break;
339
- default: positional.push(a);
322
+ const raw = argv[i];
323
+ if (raw === "--") {
324
+ positional.push(...argv.slice(i + 1));
325
+ break;
326
+ }
327
+ if (!looksLikeFlag(raw)) {
328
+ positional.push(raw);
329
+ continue;
330
+ }
331
+ const eq = raw.startsWith("--") ? raw.indexOf("=") : -1;
332
+ const name = eq > 0 ? raw.slice(0, eq) : raw;
333
+ const inline = eq > 0 ? raw.slice(eq + 1) : undefined;
334
+ if (name === "-h" || name === "--help") {
335
+ args.help = true;
336
+ continue;
337
+ }
338
+ if (name === "-v" || name === "--version") {
339
+ console.log(packageVersion());
340
+ process.exit(0);
341
+ }
342
+ const spec = FLAG_BY_NAME.get(name);
343
+ if (!spec)
344
+ return usageError(`Unknown option ${name}.${didYouMean(name, FLAG_NAMES)} Run \`context-doctor --help\` for the list.`);
345
+ if (!spec.value) {
346
+ if (inline !== undefined)
347
+ usageError(`${name} takes no value; got "${inline}".`);
348
+ spec.set(args);
349
+ continue;
350
+ }
351
+ let value = inline;
352
+ if (value === undefined) {
353
+ const next = argv[i + 1];
354
+ if (next !== undefined && looksLikeFlag(next)) {
355
+ usageError(`${name} needs a value; got the option ${next}. For a value that starts with "-", write ${name}=<value>.`);
356
+ }
357
+ if (next !== undefined) {
358
+ value = next;
359
+ i++;
360
+ }
340
361
  }
362
+ if (spec.value === "number")
363
+ spec.set(args, numArg(name, value, spec.num));
364
+ else if (value === undefined)
365
+ usageError(`${name} needs a value; got nothing.`);
366
+ else
367
+ spec.set(args, value);
341
368
  }
342
369
  args.command = positional[0];
343
370
  args.file = positional[1];
@@ -397,6 +424,27 @@ function numArg(flag, raw, { min, max, integer } = {}) {
397
424
  }
398
425
  return n;
399
426
  }
427
+ /**
428
+ * A one-line "n/N transcripts" counter on stderr while a report reads the
429
+ * history (tens of seconds on a busy machine), in a terminal only: piped or
430
+ * captured output gets none of it. `clear()` erases the line before the
431
+ * report prints.
432
+ */
433
+ function progressLine(label) {
434
+ if (!process.stderr.isTTY)
435
+ return { clear() { } };
436
+ let shown = false;
437
+ return {
438
+ tick(done, total) {
439
+ shown = true;
440
+ process.stderr.write(`\r${label}… ${done}/${total} transcripts\x1b[K`);
441
+ },
442
+ clear() {
443
+ if (shown)
444
+ process.stderr.write("\r\x1b[K");
445
+ },
446
+ };
447
+ }
400
448
  /** Any Claude Code transcript on this machine? One directory listing, no parsing. */
401
449
  function hasClaudeSessions() {
402
450
  try {
@@ -408,6 +456,29 @@ function hasClaudeSessions() {
408
456
  }
409
457
  async function main() {
410
458
  const args = parseArgs(process.argv.slice(2));
459
+ if (args.command && !COMMANDS.includes(args.command)) {
460
+ usageError(`Unknown command "${args.command}".${didYouMean(args.command, COMMANDS)} Run \`context-doctor --help\` for the list.`);
461
+ }
462
+ if (args.command === "version") {
463
+ console.log(packageVersion());
464
+ return;
465
+ }
466
+ // `<command> --help` and `help <command>`: that command's lines, not all of them.
467
+ if (args.help || args.command === "help") {
468
+ const topic = args.command === "help" ? args.file : args.command;
469
+ if (topic && !COMMANDS.includes(topic)) {
470
+ usageError(`Unknown command "${topic}".${didYouMean(topic, COMMANDS)} Run \`context-doctor --help\` for the list.`);
471
+ }
472
+ console.log((topic && commandHelp(HELP, topic)) || HELP);
473
+ return;
474
+ }
475
+ // Run by hand in a terminal, these waited forever for JSON that only
476
+ // Claude Code sends.
477
+ if ((args.command === "hook" || args.command === "statusline") && process.stdin.isTTY) {
478
+ const setup = args.command === "hook" ? "`context-doctor install` registers it" : "`context-doctor install --statusline` sets it up";
479
+ console.log(`context-doctor ${args.command} is called by Claude Code with JSON on stdin; there is nothing for it to do in a terminal (${setup}).`);
480
+ return;
481
+ }
411
482
  if (args.command === "hook") {
412
483
  void runHook();
413
484
  return;
@@ -430,7 +501,7 @@ async function main() {
430
501
  console.log("Presets for .contextdoctorrc — pick the one that matches your workload:\n");
431
502
  for (const p of PRESETS)
432
503
  console.log(` ${p.id.padEnd(7)} ${p.summary}`);
433
- console.log("\nThen: context-doctor init <preset>");
504
+ console.log(`\nThen: ${selfCommand("init <preset>")}`);
434
505
  return;
435
506
  }
436
507
  const preset = findPreset(requested);
@@ -550,7 +621,10 @@ async function main() {
550
621
  }
551
622
  return;
552
623
  }
553
- const path = args.file ?? listSessions(1)[0]?.path;
624
+ // No file: the session this runs in (the plugin's checkup runs it from
625
+ // inside one), then this folder's newest, then the machine's newest.
626
+ const picked = args.file ? undefined : pickCurrentSession();
627
+ const path = args.file ?? picked?.path;
554
628
  if (!path) {
555
629
  console.error("No session transcript found. Pass a .jsonl path or run inside a machine with Claude Code sessions.");
556
630
  process.exit(1);
@@ -565,7 +639,7 @@ async function main() {
565
639
  }
566
640
  const profile = profileConversation(parseConversation(parsed.conversationJson), args.model ?? parsed.model);
567
641
  if (args.json) {
568
- console.log(JSON.stringify({ session: { path: parsed.path, title: parsed.title, toolTimings: parsed.toolTimings ?? [], subagents: subagentReport(path) }, profile }, null, 2));
642
+ console.log(JSON.stringify({ session: { path: parsed.path, title: parsed.title, ...(picked ? { picked: picked.how } : {}), toolTimings: parsed.toolTimings ?? [], subagents: subagentReport(path) }, profile }, null, 2));
569
643
  // --json is what CI pipes, so the gate must hold here too (as it does for
570
644
  // analyze); it used to run only after the text report and never failed.
571
645
  applyBudgetGate(checkBudget(loadConfig(process.cwd(), (m) => console.error(`context-doctor: ${m}`)).config.budget, profile).overBudget, args.failOverBudget);
@@ -576,6 +650,8 @@ async function main() {
576
650
  console.log(args.redact
577
651
  ? "Session: [redacted]\nFile: [redacted]"
578
652
  : `Session: ${parsed.title ?? "(untitled)"}\nFile: ${parsed.path}`);
653
+ if (picked)
654
+ console.log(`Picked: ${picked.how} (pass a file to profile another; --list shows them)`);
579
655
  if (parsed.compactedAway) {
580
656
  console.log(`Note: ${parsed.compactedAway} earlier message(s) were compacted away and are NOT counted below — this is the live context the model still sees.`);
581
657
  }
@@ -619,14 +695,16 @@ async function main() {
619
695
  // A bare `context-doctor` in a terminal, with Claude Code history on the
620
696
  // machine, answers the question people install this for: what would it
621
697
  // save me? Scripts and pipes still get the help text.
622
- const progress = process.stderr.isTTY
623
- ? (done, total) => process.stderr.write(`\rReplaying your Claude Code sessions through autopilot… ${done}/${total}`)
624
- : undefined;
625
- const report = estimateSavings(args.days ?? 30, {}, undefined, progress);
626
- if (progress)
627
- process.stderr.write("\r\x1b[K");
698
+ const replaying = progressLine("Replaying your Claude Code sessions through autopilot");
699
+ const report = estimateSavings(args.days ?? 30, {}, undefined, replaying.tick);
700
+ replaying.clear();
628
701
  const setWindow = currentCompactWindow();
629
- const cwReport = estimateCompactWindows([setWindow ?? 400_000], args.days ?? 30, undefined, compactionQuality(60).extraRereadTokensPerCompaction);
702
+ const measuring = progressLine("Measuring your compactions");
703
+ const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
704
+ measuring.clear();
705
+ const windowing = progressLine("Replaying an earlier auto-compact window");
706
+ const cwReport = estimateCompactWindows([setWindow ?? 400_000], args.days ?? 30, undefined, reread, windowing.tick);
707
+ windowing.clear();
630
708
  const est = cwReport.estimates[0];
631
709
  const cwLine = cwReport.sessions > 0 && est
632
710
  ? { window: est.window, savedUsd: est.savedUsd, compactionsPerWeek: (est.compactions / cwReport.days) * 7, nowPerWeek: (cwReport.actualCompactions / cwReport.days) * 7, isCurrent: setWindow !== undefined }
@@ -643,7 +721,7 @@ async function main() {
643
721
  else {
644
722
  console.log(renderSavings(report, on, cwLine));
645
723
  if (!args.command)
646
- console.log("\nAll commands: context-doctor --help");
724
+ console.log(`\nAll commands: ${selfCommand("--help")}`);
647
725
  }
648
726
  return;
649
727
  }
@@ -659,8 +737,10 @@ async function main() {
659
737
  if (args.command === "compact-window") {
660
738
  const sub = args.file ?? "status";
661
739
  if (sub === "off") {
662
- setCompactWindow(undefined);
663
- console.log("✓ autoCompactWindow removed from ~/.claude/settings.json: Claude Code compacts near the model's full window again (new sessions).");
740
+ const r = setCompactWindow(undefined);
741
+ console.log(r.changed
742
+ ? "✓ autoCompactWindow removed from ~/.claude/settings.json: Claude Code compacts near the model's full window again (new sessions)."
743
+ : "No auto-compact window was set. Nothing changed.");
664
744
  return;
665
745
  }
666
746
  if (sub !== "status") {
@@ -670,19 +750,30 @@ async function main() {
670
750
  process.exitCode = 1;
671
751
  return;
672
752
  }
673
- setCompactWindow(w);
674
- console.log(`✓ autoCompactWindow = ${w} in ~/.claude/settings.json (a .backup was kept).`);
753
+ const r = setCompactWindow(w);
754
+ if (!r.changed) {
755
+ console.log(`autoCompactWindow is already ${w} in ~/.claude/settings.json. Nothing changed.`);
756
+ return;
757
+ }
758
+ // Only claim a backup that exists: a new settings.json had nothing to back up.
759
+ const note = r.created ? "a new file" : r.backup ? `the previous file is kept as ${r.backup.replace(homedir(), "~")}` : "";
760
+ console.log(`✓ autoCompactWindow = ${w} in ~/.claude/settings.json${note ? ` (${note})` : ""}.`);
675
761
  console.log(" Claude Code sessions started from now on compact as if the window were that size,");
676
762
  console.log(" in the terminal, IDEs and the desktop app. Check in a session with /context.");
677
- console.log(" Undo: context-doctor compact-window off");
763
+ console.log(` Undo: ${selfCommand("compact-window off")}`);
678
764
  return;
679
765
  }
680
766
  const current = currentCompactWindow();
681
767
  const windows = [200_000, 300_000, 400_000, 600_000, 800_000];
682
768
  if (current && !windows.includes(current))
683
769
  windows.push(current);
684
- const reread = compactionQuality(60).extraRereadTokensPerCompaction;
685
- console.log(renderCompactWindows(estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread), current));
770
+ const measuring = progressLine("Measuring your compactions");
771
+ const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
772
+ measuring.clear();
773
+ const replaying = progressLine("Replaying your sessions at each window");
774
+ const cw = estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread, replaying.tick);
775
+ replaying.clear();
776
+ console.log(renderCompactWindows(cw, current));
686
777
  return;
687
778
  }
688
779
  if (args.command === "autopilot") {
@@ -698,7 +789,10 @@ async function main() {
698
789
  console.log((await autopilotOff()).join("\n"));
699
790
  }
700
791
  else if (sub === "pause" || sub === "resume") {
701
- console.log(autopilotPause(sub === "pause"));
792
+ const r = autopilotPauseResult(sub === "pause");
793
+ console.log(r.message);
794
+ if (!r.ok)
795
+ process.exitCode = 1;
702
796
  }
703
797
  else if (sub === "status") {
704
798
  console.log((await autopilotStatus()).join("\n"));
@@ -754,7 +848,9 @@ async function main() {
754
848
  return;
755
849
  }
756
850
  if (args.command === "subagents") {
757
- const report = subagentPayback(args.days ?? 30);
851
+ const reading = progressLine("Reading your sessions' subagents");
852
+ const report = subagentPayback(args.days ?? 30, undefined, reading.tick);
853
+ reading.clear();
758
854
  console.log(args.json ? JSON.stringify(report, null, 2) : renderPayback(report, args.limit ?? 8));
759
855
  return;
760
856
  }
@@ -828,7 +924,14 @@ async function main() {
828
924
  return;
829
925
  }
830
926
  if (args.command === "overhead") {
831
- const report = overheadReport({ days: args.days });
927
+ const sessions = progressLine("Measuring each session's first request");
928
+ const tools = progressLine("Counting MCP tool calls");
929
+ const report = overheadReport({
930
+ days: args.days,
931
+ onProgress: (done, total, stage) => (stage === "sessions" ? sessions : tools).tick?.(done, total),
932
+ });
933
+ sessions.clear();
934
+ tools.clear();
832
935
  if (args.mcp)
833
936
  await measureMcpSizes(report);
834
937
  console.log(args.json ? JSON.stringify(report, (_k, v) => (v instanceof Map ? Object.fromEntries(v) : v), 2) : renderOverhead(report));
@@ -851,14 +954,14 @@ async function main() {
851
954
  console.log(args.json ? JSON.stringify({ ...result, chunks: undefined, outline: result.chunks.map(({ text, ...c }) => c) }, null, 2) : renderPack(result));
852
955
  return;
853
956
  }
854
- if (!args.command || !args.file) {
855
- const known = ["analyze", "optimize"];
856
- if (args.command && !known.includes(args.command)) {
857
- console.error(`Unknown command "${args.command}". Run \`context-doctor --help\` for the list.`);
858
- process.exit(1);
859
- }
860
- console.log(HELP);
861
- process.exit(args.command ? 1 : 0);
957
+ if (!args.command) {
958
+ // Bare, with no history to measure or not in a terminal: where to begin.
959
+ console.log(withInvocation(START_HERE));
960
+ return;
961
+ }
962
+ if (!args.file) {
963
+ // analyze/optimize without a file: say what is missing, then how to call it.
964
+ usageError(`${args.command} needs a conversation file (or - to read stdin).\n\n${commandHelp(HELP, args.command) ?? ""}`);
862
965
  }
863
966
  let input;
864
967
  try {
@@ -868,9 +971,16 @@ async function main() {
868
971
  console.error(`Could not read ${args.file}: ${e.message}`);
869
972
  process.exit(1);
870
973
  }
974
+ // Broken JSON, or JSON that is not a conversation, used to profile as a
975
+ // few tokens (or none) and report the context "in good shape". Raw text
976
+ // stays a supported input: it parses without a warning.
977
+ const conversation = parseConversation(input);
978
+ if (conversation.parseWarning) {
979
+ usageError(`Could not ${args.command} ${args.file === "-" ? "stdin" : args.file}: ${conversation.parseWarning}`);
980
+ }
871
981
  if (args.command === "analyze") {
872
982
  const loaded = loadConfig(process.cwd(), (m) => console.error(`context-doctor: ${m}`));
873
- const profile = profileConversation(parseConversation(input), args.model ?? loaded.config.model);
983
+ const profile = profileConversation(conversation, args.model ?? loaded.config.model);
874
984
  // The exact count is awaited before anything prints: with --json it goes
875
985
  // inside the one JSON object. Printed after it, as it once was, the extra
876
986
  // lines made stdout invalid JSON for every script that parsed it.