context-doctor 0.32.0 → 0.34.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 +84 -694
- package/dist/autoclear.js +4 -1
- package/dist/autopilot.d.ts +20 -6
- package/dist/autopilot.js +105 -7
- package/dist/cachekey.d.ts +25 -0
- package/dist/cachekey.js +73 -0
- package/dist/cacheplan.d.ts +29 -9
- package/dist/cacheplan.js +110 -29
- package/dist/ci.js +9 -1
- package/dist/cli.js +359 -247
- package/dist/clihelp.d.ts +24 -0
- package/dist/clihelp.js +116 -0
- package/dist/codexroute.d.ts +46 -0
- package/dist/codexroute.js +122 -0
- package/dist/coldresume.d.ts +62 -0
- package/dist/coldresume.js +85 -6
- package/dist/compactquality.d.ts +3 -1
- package/dist/compactquality.js +15 -4
- package/dist/compactwindow.d.ts +31 -5
- package/dist/compactwindow.js +80 -25
- package/dist/diff.js +24 -2
- package/dist/doctor.d.ts +8 -2
- package/dist/doctor.js +138 -35
- package/dist/hook.js +23 -4
- package/dist/install.d.ts +35 -0
- package/dist/install.js +280 -48
- package/dist/invocation.d.ts +18 -0
- package/dist/invocation.js +49 -0
- package/dist/ledger.d.ts +2 -0
- package/dist/mcp.d.ts +5 -2
- package/dist/mcp.js +93 -299
- package/dist/mcpclient.js +45 -0
- package/dist/mcpschema.d.ts +1 -1
- package/dist/mcpschema.js +11 -8
- package/dist/optimize.d.ts +2 -0
- package/dist/optimize.js +2 -0
- package/dist/overhead.d.ts +12 -1
- package/dist/overhead.js +31 -7
- package/dist/preferences.d.ts +1 -1
- package/dist/preferences.js +5 -5
- package/dist/proxy.d.ts +14 -1
- package/dist/proxy.js +45 -4
- package/dist/savings.d.ts +17 -1
- package/dist/savings.js +12 -13
- package/dist/session.d.ts +15 -0
- package/dist/session.js +43 -0
- package/dist/subagentpay.d.ts +1 -1
- package/dist/subagentpay.js +3 -2
- package/package.json +5 -8
- package/skills/context-doctor/SKILL.md +3 -3
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,
|
|
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
|
-
|
|
56
|
-
context-doctor
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
context-doctor
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
context-doctor
|
|
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
|
|
108
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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,28 @@ 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
|
|
133
|
-
|
|
134
|
-
|
|
137
|
+
context-doctor cache-plan <request.json> [--calls n] [--out file] [--explicit]
|
|
138
|
+
Where an Anthropic request should carry cache_control,
|
|
139
|
+
what it saves over n calls; --out writes it applied
|
|
140
|
+
(top-level automatic caching unless --explicit)
|
|
141
|
+
|
|
142
|
+
Integrations:
|
|
143
|
+
context-doctor ci [--base <ref>] [--max-tokens n] [--max-increase n] [--markdown]
|
|
144
|
+
For pull requests: memory files (CLAUDE.md, AGENTS.md,
|
|
145
|
+
GEMINI.md, rules) at HEAD vs base; exit 1 over budget
|
|
146
|
+
context-doctor instructions [--copy] Standing context rules to paste into claude.ai or
|
|
147
|
+
ChatGPT preferences (works on web and mobile too)
|
|
148
|
+
context-doctor init [preset] Write a .contextdoctorrc from a preset
|
|
149
|
+
(chat, agent, batch; no argument lists them)
|
|
150
|
+
|
|
151
|
+
Internal (Claude Code and MCP clients run these for you):
|
|
152
|
+
context-doctor hook The every-prompt and PreCompact hook (installed by
|
|
153
|
+
\`install\`; reads hook JSON on stdin)
|
|
154
|
+
context-doctor statusline Claude Code status bar line: live context size, cache
|
|
155
|
+
share, cost (wired by \`install --statusline\`; reads
|
|
156
|
+
the status JSON on stdin)
|
|
157
|
+
context-doctor mcp [--http] The MCP server (same as context-doctor-mcp), for clients
|
|
158
|
+
that launch \`npx -y context-doctor mcp\`
|
|
135
159
|
|
|
136
160
|
Project config: an optional .contextdoctorrc (nearest, walking up from cwd, then
|
|
137
161
|
~/.contextdoctorrc) can set a context budget and default strategies:
|
|
@@ -157,7 +181,16 @@ Options:
|
|
|
157
181
|
Default: dedupe, trim-tool-results, strip-base64 (lossless-ish set)
|
|
158
182
|
--keep-recent <n> (optimize) Messages at the tail to leave untouched (default 6)
|
|
159
183
|
--max-tool-tokens <n> (optimize) Token budget for trimmed tool results (default 300)
|
|
160
|
-
--limit <n> (accuracy, session --list
|
|
184
|
+
--limit <n> (accuracy, session --list, reads, tasks, subagents) How many to sample
|
|
185
|
+
or list
|
|
186
|
+
--days <n> (savings, compact-window, overhead, reads, tasks, subagents, compactions)
|
|
187
|
+
Days of history to read (default 30; compactions 60)
|
|
188
|
+
-q, --query <text> (pack) The question to rank chunks against
|
|
189
|
+
--max-tokens <n> (pack) Token budget (default 4000); (ci) fail over this many tokens
|
|
190
|
+
--chunk-tokens <n> (pack) Largest chunk, in tokens (default 400)
|
|
191
|
+
--ids <a#2,b#5> (pack) Return these chunks by id
|
|
192
|
+
--min-tokens <n> (overhead split) Smallest section to move, in tokens (default 400)
|
|
193
|
+
--requests-per-day <n> (ci --markdown) Price the change at this many requests a day
|
|
161
194
|
--check <cmd> (experiment) Command whose exit code is the pass/fail for each arm
|
|
162
195
|
--existing <id> (experiment) Session id to fork the second arm from (never mutated)
|
|
163
196
|
--budget <usd> (experiment) Spend cap per arm (default 1)
|
|
@@ -165,6 +198,8 @@ Options:
|
|
|
165
198
|
--allow-dirty (experiment) Skip the clean-tree check (uncommitted changes will be lost)
|
|
166
199
|
--statusline (install) Also set Claude Code's statusLine to context-doctor (never
|
|
167
200
|
overwrites a statusLine you already have)
|
|
201
|
+
--autopilot (proxy) Cold-cache clearing only, the mode \`autopilot on\` runs; never
|
|
202
|
+
costs more. Without it the proxy runs the optimizing strategies
|
|
168
203
|
--port <n> (proxy) Port to listen on (default 8787)
|
|
169
204
|
--host <addr> (proxy) Bind address (default 127.0.0.1; use 0.0.0.0 to expose)
|
|
170
205
|
--token <secret> (proxy) Require /t/<secret>/ in every request path; needed before
|
|
@@ -174,170 +209,164 @@ Options:
|
|
|
174
209
|
"keepRecent":n,"maxToolResultTokens":n}]} — first prefix match wins
|
|
175
210
|
--upstream-anthropic <url> (proxy) Override Anthropic upstream (testing)
|
|
176
211
|
--upstream-openai <url> (proxy) Override OpenAI upstream (testing)
|
|
212
|
+
--upstream-google <url> (proxy) Override Gemini upstream (testing)
|
|
177
213
|
-h, --help Show this help
|
|
178
214
|
|
|
179
215
|
Examples:
|
|
180
216
|
context-doctor analyze chat.json --model claude-sonnet-5
|
|
181
217
|
context-doctor optimize chat.json --strategy dedupe --strategy prune-history --out slim.json
|
|
182
|
-
context-doctor proxy --port 8787
|
|
218
|
+
context-doctor proxy --autopilot --port 8787
|
|
183
219
|
then: export ANTHROPIC_BASE_URL=http://localhost:8787
|
|
184
220
|
export OPENAI_BASE_URL=http://localhost:8787/v1
|
|
221
|
+
export GOOGLE_GEMINI_BASE_URL=http://localhost:8787
|
|
185
222
|
`;
|
|
223
|
+
/**
|
|
224
|
+
* What a bare `context-doctor` prints when there is no Claude Code history
|
|
225
|
+
* to measure, or when stdout is not a terminal: where to begin, in a dozen
|
|
226
|
+
* lines, instead of the full reference above.
|
|
227
|
+
*/
|
|
228
|
+
const START_HERE = `context-doctor: see where your Claude Code tokens go, and cut them.
|
|
229
|
+
|
|
230
|
+
Start here
|
|
231
|
+
In Claude Code, as a plugin:
|
|
232
|
+
/plugin marketplace add KushalP1/context-doctor
|
|
233
|
+
/plugin install context-doctor@context-doctor
|
|
234
|
+
then /context-doctor:savings, :checkup, :overhead, :compact-window, :autopilot, :pack
|
|
235
|
+
In a terminal:
|
|
236
|
+
context-doctor install wire the MCP server, skill and hooks into the apps it finds
|
|
237
|
+
context-doctor savings what your recent sessions cost, and what each fix would save
|
|
238
|
+
context-doctor doctor check the installation
|
|
239
|
+
|
|
240
|
+
All commands: context-doctor --help
|
|
241
|
+
Guide: https://github.com/KushalP1/context-doctor#readme`;
|
|
242
|
+
/** Exit 1 with a usage message: wrong arguments are the caller's to fix, not a crash. */
|
|
243
|
+
function usageError(message) {
|
|
244
|
+
console.error(message);
|
|
245
|
+
process.exit(1);
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Every command main() handles. An unknown one is an error with a
|
|
249
|
+
* suggestion, never a silent fall-through to the help text.
|
|
250
|
+
*/
|
|
251
|
+
const COMMANDS = [
|
|
252
|
+
"analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
|
|
253
|
+
"instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
|
|
254
|
+
"experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "subagents", "tasks",
|
|
255
|
+
"reads", "pack", "watch", "help", "version",
|
|
256
|
+
];
|
|
257
|
+
/** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
|
|
258
|
+
function strategyArg(v) {
|
|
259
|
+
if (STRATEGY_IDS.includes(v))
|
|
260
|
+
return v;
|
|
261
|
+
return usageError(`--strategy "${v}" is not a strategy.${didYouMean(v, STRATEGY_IDS)} Available: ${STRATEGY_IDS.join(", ")}.`);
|
|
262
|
+
}
|
|
263
|
+
const FLAGS = [
|
|
264
|
+
{ names: ["--json"], set: (a) => { a.json = true; } },
|
|
265
|
+
{ names: ["--list"], set: (a) => { a.list = true; } },
|
|
266
|
+
{ names: ["--exact"], set: (a) => { a.exact = true; } },
|
|
267
|
+
{ names: ["--redact"], set: (a) => { a.redact = true; } },
|
|
268
|
+
{ names: ["--fail-over-budget"], set: (a) => { a.failOverBudget = true; } },
|
|
269
|
+
{ names: ["--model"], value: "text", set: (a, v) => { a.model = v; } },
|
|
270
|
+
{ names: ["--out"], value: "text", set: (a, v) => { a.out = v; } },
|
|
271
|
+
{ names: ["--strategy"], value: "text", set: (a, v) => { a.strategies.push(strategyArg(v)); } },
|
|
272
|
+
{ names: ["--keep-recent"], value: "number", num: { min: 0, integer: true }, set: (a, v) => { a.keepRecent = v; } },
|
|
273
|
+
{ names: ["--max-tool-tokens"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.maxToolTokens = v; } },
|
|
274
|
+
{ names: ["--port"], value: "number", num: { min: 0, max: 65535, integer: true }, set: (a, v) => { a.port = v; } },
|
|
275
|
+
{ names: ["--interval-ms"], value: "number", num: { min: 100, integer: true }, set: (a, v) => { a.intervalMs = v; } },
|
|
276
|
+
{ names: ["--limit"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.limit = v; } },
|
|
277
|
+
{ names: ["--task"], value: "text", set: (a, v) => { a.task = v; } },
|
|
278
|
+
{ names: ["--check"], value: "text", set: (a, v) => { a.check = v; } },
|
|
279
|
+
{ names: ["--existing"], value: "text", set: (a, v) => { a.existing = v; } },
|
|
280
|
+
{ names: ["--budget"], value: "number", num: { min: 0 }, set: (a, v) => { a.budgetUsd = v; } },
|
|
281
|
+
{ names: ["--dry-run"], set: (a) => { a.dryRun = true; } },
|
|
282
|
+
{ names: ["--copy"], set: (a) => { a.copy = true; } },
|
|
283
|
+
{ names: ["--share"], set: (a) => { a.share = true; } },
|
|
284
|
+
{ names: ["--allow-dirty"], set: (a) => { a.allowDirty = true; } },
|
|
285
|
+
{ names: ["--statusline"], set: (a) => { a.statusLine = true; } },
|
|
286
|
+
{ names: ["--host"], value: "text", set: (a, v) => { a.host = v; } },
|
|
287
|
+
{ names: ["--token"], value: "text", set: (a, v) => { a.token = v; } },
|
|
288
|
+
{ names: ["--days"], value: "number", num: { min: 1 }, set: (a, v) => { a.days = v; } },
|
|
289
|
+
{ names: ["--autopilot"], set: (a) => { a.autopilot = true; } },
|
|
290
|
+
{ names: ["--autopilot-state"], value: "text", set: (a, v) => { a.autopilotState = v; } },
|
|
291
|
+
{ names: ["--autopilot-pause-file"], value: "text", set: (a, v) => { a.autopilotPauseFile = v; } },
|
|
292
|
+
{ names: ["--config"], value: "text", set: (a, v) => { a.config = v; } },
|
|
293
|
+
{ names: ["-q", "--query"], value: "text", set: (a, v) => { a.query = v; } },
|
|
294
|
+
{ names: ["--max-tokens"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.maxTokens = v; } },
|
|
295
|
+
{ names: ["--chunk-tokens"], value: "number", num: { min: 50, integer: true }, set: (a, v) => { a.chunkTokens = v; } },
|
|
296
|
+
{ names: ["--mcp"], set: (a) => { a.mcp = true; } },
|
|
297
|
+
{ names: ["--write"], set: (a) => { a.write = true; } },
|
|
298
|
+
{ names: ["--calls"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.calls = v; } },
|
|
299
|
+
{ names: ["--explicit"], set: (a) => { a.explicit = true; } },
|
|
300
|
+
{ names: ["--semantic"], set: (a) => { a.semantic = a.semantic || true; } },
|
|
301
|
+
{ names: ["--embed-model"], value: "text", set: (a, v) => { a.semantic = v; } },
|
|
302
|
+
{ names: ["--base"], value: "text", set: (a, v) => { a.base = v; } },
|
|
303
|
+
{ names: ["--markdown"], set: (a) => { a.markdown = true; } },
|
|
304
|
+
{ names: ["--max-increase"], value: "number", num: { min: 0, integer: true }, set: (a, v) => { a.maxIncrease = v; } },
|
|
305
|
+
{ names: ["--requests-per-day"], value: "number", num: { min: 1 }, set: (a, v) => { a.requestsPerDay = v; } },
|
|
306
|
+
{ names: ["--min-tokens"], value: "number", num: { min: 50, integer: true }, set: (a, v) => { a.minTokens = v; } },
|
|
307
|
+
{ names: ["--ids"], value: "text", set: (a, v) => { a.ids = v.split(",").map((x) => x.trim()).filter(Boolean); } },
|
|
308
|
+
{ names: ["--upstream-anthropic"], value: "text", set: (a, v) => { a.upstreamAnthropic = v; } },
|
|
309
|
+
{ names: ["--upstream-openai"], value: "text", set: (a, v) => { a.upstreamOpenai = v; } },
|
|
310
|
+
{ names: ["--upstream-google"], value: "text", set: (a, v) => { a.upstreamGoogle = v; } },
|
|
311
|
+
// Read by the MCP server itself: `mcp --http [--port n] [--host h]`.
|
|
312
|
+
{ names: ["--http"], set: () => { } },
|
|
313
|
+
];
|
|
314
|
+
const FLAG_BY_NAME = new Map(FLAGS.flatMap((f) => f.names.map((n) => [n, f])));
|
|
315
|
+
const FLAG_NAMES = [...FLAG_BY_NAME.keys(), "--help", "--version"];
|
|
316
|
+
/** An option, not a value: "-q", "--days". "-" (stdin) and "-1" are values. */
|
|
317
|
+
function looksLikeFlag(s) {
|
|
318
|
+
return /^-[A-Za-z-]/.test(s) && s !== "--";
|
|
319
|
+
}
|
|
186
320
|
function parseArgs(argv) {
|
|
187
|
-
const args = { json: false, strategies: [], list: false, exact: false, redact: false, failOverBudget: false, dryRun: false, allowDirty: false, statusLine: false };
|
|
321
|
+
const args = { json: false, strategies: [], list: false, exact: false, redact: false, failOverBudget: false, dryRun: false, allowDirty: false, statusLine: false, help: false };
|
|
188
322
|
const positional = [];
|
|
189
323
|
for (let i = 0; i < argv.length; i++) {
|
|
190
|
-
const
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
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);
|
|
324
|
+
const raw = argv[i];
|
|
325
|
+
if (raw === "--") {
|
|
326
|
+
positional.push(...argv.slice(i + 1));
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
if (!looksLikeFlag(raw)) {
|
|
330
|
+
positional.push(raw);
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
const eq = raw.startsWith("--") ? raw.indexOf("=") : -1;
|
|
334
|
+
const name = eq > 0 ? raw.slice(0, eq) : raw;
|
|
335
|
+
const inline = eq > 0 ? raw.slice(eq + 1) : undefined;
|
|
336
|
+
if (name === "-h" || name === "--help") {
|
|
337
|
+
args.help = true;
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
if (name === "-v" || name === "--version") {
|
|
341
|
+
console.log(packageVersion());
|
|
342
|
+
process.exit(0);
|
|
343
|
+
}
|
|
344
|
+
const spec = FLAG_BY_NAME.get(name);
|
|
345
|
+
if (!spec)
|
|
346
|
+
return usageError(`Unknown option ${name}.${didYouMean(name, FLAG_NAMES)} Run \`context-doctor --help\` for the list.`);
|
|
347
|
+
if (!spec.value) {
|
|
348
|
+
if (inline !== undefined)
|
|
349
|
+
usageError(`${name} takes no value; got "${inline}".`);
|
|
350
|
+
spec.set(args);
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
let value = inline;
|
|
354
|
+
if (value === undefined) {
|
|
355
|
+
const next = argv[i + 1];
|
|
356
|
+
if (next !== undefined && looksLikeFlag(next)) {
|
|
357
|
+
usageError(`${name} needs a value; got the option ${next}. For a value that starts with "-", write ${name}=<value>.`);
|
|
358
|
+
}
|
|
359
|
+
if (next !== undefined) {
|
|
360
|
+
value = next;
|
|
361
|
+
i++;
|
|
362
|
+
}
|
|
340
363
|
}
|
|
364
|
+
if (spec.value === "number")
|
|
365
|
+
spec.set(args, numArg(name, value, spec.num));
|
|
366
|
+
else if (value === undefined)
|
|
367
|
+
usageError(`${name} needs a value; got nothing.`);
|
|
368
|
+
else
|
|
369
|
+
spec.set(args, value);
|
|
341
370
|
}
|
|
342
371
|
args.command = positional[0];
|
|
343
372
|
args.file = positional[1];
|
|
@@ -397,6 +426,27 @@ function numArg(flag, raw, { min, max, integer } = {}) {
|
|
|
397
426
|
}
|
|
398
427
|
return n;
|
|
399
428
|
}
|
|
429
|
+
/**
|
|
430
|
+
* A one-line "n/N transcripts" counter on stderr while a report reads the
|
|
431
|
+
* history (tens of seconds on a busy machine), in a terminal only: piped or
|
|
432
|
+
* captured output gets none of it. `clear()` erases the line before the
|
|
433
|
+
* report prints.
|
|
434
|
+
*/
|
|
435
|
+
function progressLine(label) {
|
|
436
|
+
if (!process.stderr.isTTY)
|
|
437
|
+
return { clear() { } };
|
|
438
|
+
let shown = false;
|
|
439
|
+
return {
|
|
440
|
+
tick(done, total) {
|
|
441
|
+
shown = true;
|
|
442
|
+
process.stderr.write(`\r${label}… ${done}/${total} transcripts\x1b[K`);
|
|
443
|
+
},
|
|
444
|
+
clear() {
|
|
445
|
+
if (shown)
|
|
446
|
+
process.stderr.write("\r\x1b[K");
|
|
447
|
+
},
|
|
448
|
+
};
|
|
449
|
+
}
|
|
400
450
|
/** Any Claude Code transcript on this machine? One directory listing, no parsing. */
|
|
401
451
|
function hasClaudeSessions() {
|
|
402
452
|
try {
|
|
@@ -408,6 +458,29 @@ function hasClaudeSessions() {
|
|
|
408
458
|
}
|
|
409
459
|
async function main() {
|
|
410
460
|
const args = parseArgs(process.argv.slice(2));
|
|
461
|
+
if (args.command && !COMMANDS.includes(args.command)) {
|
|
462
|
+
usageError(`Unknown command "${args.command}".${didYouMean(args.command, COMMANDS)} Run \`context-doctor --help\` for the list.`);
|
|
463
|
+
}
|
|
464
|
+
if (args.command === "version") {
|
|
465
|
+
console.log(packageVersion());
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
// `<command> --help` and `help <command>`: that command's lines, not all of them.
|
|
469
|
+
if (args.help || args.command === "help") {
|
|
470
|
+
const topic = args.command === "help" ? args.file : args.command;
|
|
471
|
+
if (topic && !COMMANDS.includes(topic)) {
|
|
472
|
+
usageError(`Unknown command "${topic}".${didYouMean(topic, COMMANDS)} Run \`context-doctor --help\` for the list.`);
|
|
473
|
+
}
|
|
474
|
+
console.log((topic && commandHelp(HELP, topic)) || HELP);
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
// Run by hand in a terminal, these waited forever for JSON that only
|
|
478
|
+
// Claude Code sends.
|
|
479
|
+
if ((args.command === "hook" || args.command === "statusline") && process.stdin.isTTY) {
|
|
480
|
+
const setup = args.command === "hook" ? "`context-doctor install` registers it" : "`context-doctor install --statusline` sets it up";
|
|
481
|
+
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}).`);
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
411
484
|
if (args.command === "hook") {
|
|
412
485
|
void runHook();
|
|
413
486
|
return;
|
|
@@ -430,7 +503,7 @@ async function main() {
|
|
|
430
503
|
console.log("Presets for .contextdoctorrc — pick the one that matches your workload:\n");
|
|
431
504
|
for (const p of PRESETS)
|
|
432
505
|
console.log(` ${p.id.padEnd(7)} ${p.summary}`);
|
|
433
|
-
console.log(
|
|
506
|
+
console.log(`\nThen: ${selfCommand("init <preset>")}`);
|
|
434
507
|
return;
|
|
435
508
|
}
|
|
436
509
|
const preset = findPreset(requested);
|
|
@@ -550,7 +623,10 @@ async function main() {
|
|
|
550
623
|
}
|
|
551
624
|
return;
|
|
552
625
|
}
|
|
553
|
-
|
|
626
|
+
// No file: the session this runs in (the plugin's checkup runs it from
|
|
627
|
+
// inside one), then this folder's newest, then the machine's newest.
|
|
628
|
+
const picked = args.file ? undefined : pickCurrentSession();
|
|
629
|
+
const path = args.file ?? picked?.path;
|
|
554
630
|
if (!path) {
|
|
555
631
|
console.error("No session transcript found. Pass a .jsonl path or run inside a machine with Claude Code sessions.");
|
|
556
632
|
process.exit(1);
|
|
@@ -565,7 +641,7 @@ async function main() {
|
|
|
565
641
|
}
|
|
566
642
|
const profile = profileConversation(parseConversation(parsed.conversationJson), args.model ?? parsed.model);
|
|
567
643
|
if (args.json) {
|
|
568
|
-
console.log(JSON.stringify({ session: { path: parsed.path, title: parsed.title, toolTimings: parsed.toolTimings ?? [], subagents: subagentReport(path) }, profile }, null, 2));
|
|
644
|
+
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
645
|
// --json is what CI pipes, so the gate must hold here too (as it does for
|
|
570
646
|
// analyze); it used to run only after the text report and never failed.
|
|
571
647
|
applyBudgetGate(checkBudget(loadConfig(process.cwd(), (m) => console.error(`context-doctor: ${m}`)).config.budget, profile).overBudget, args.failOverBudget);
|
|
@@ -576,6 +652,8 @@ async function main() {
|
|
|
576
652
|
console.log(args.redact
|
|
577
653
|
? "Session: [redacted]\nFile: [redacted]"
|
|
578
654
|
: `Session: ${parsed.title ?? "(untitled)"}\nFile: ${parsed.path}`);
|
|
655
|
+
if (picked)
|
|
656
|
+
console.log(`Picked: ${picked.how} (pass a file to profile another; --list shows them)`);
|
|
579
657
|
if (parsed.compactedAway) {
|
|
580
658
|
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
659
|
}
|
|
@@ -619,14 +697,16 @@ async function main() {
|
|
|
619
697
|
// A bare `context-doctor` in a terminal, with Claude Code history on the
|
|
620
698
|
// machine, answers the question people install this for: what would it
|
|
621
699
|
// save me? Scripts and pipes still get the help text.
|
|
622
|
-
const
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
const report = estimateSavings(args.days ?? 30, {}, undefined, progress);
|
|
626
|
-
if (progress)
|
|
627
|
-
process.stderr.write("\r\x1b[K");
|
|
700
|
+
const replaying = progressLine("Replaying your Claude Code sessions through autopilot");
|
|
701
|
+
const report = estimateSavings(args.days ?? 30, {}, undefined, replaying.tick);
|
|
702
|
+
replaying.clear();
|
|
628
703
|
const setWindow = currentCompactWindow();
|
|
629
|
-
const
|
|
704
|
+
const measuring = progressLine("Measuring your compactions");
|
|
705
|
+
const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
|
|
706
|
+
measuring.clear();
|
|
707
|
+
const windowing = progressLine("Replaying an earlier auto-compact window");
|
|
708
|
+
const cwReport = estimateCompactWindows([setWindow ?? 400_000], args.days ?? 30, undefined, reread, windowing.tick);
|
|
709
|
+
windowing.clear();
|
|
630
710
|
const est = cwReport.estimates[0];
|
|
631
711
|
const cwLine = cwReport.sessions > 0 && est
|
|
632
712
|
? { window: est.window, savedUsd: est.savedUsd, compactionsPerWeek: (est.compactions / cwReport.days) * 7, nowPerWeek: (cwReport.actualCompactions / cwReport.days) * 7, isCurrent: setWindow !== undefined }
|
|
@@ -643,7 +723,7 @@ async function main() {
|
|
|
643
723
|
else {
|
|
644
724
|
console.log(renderSavings(report, on, cwLine));
|
|
645
725
|
if (!args.command)
|
|
646
|
-
console.log(
|
|
726
|
+
console.log(`\nAll commands: ${selfCommand("--help")}`);
|
|
647
727
|
}
|
|
648
728
|
return;
|
|
649
729
|
}
|
|
@@ -659,8 +739,10 @@ async function main() {
|
|
|
659
739
|
if (args.command === "compact-window") {
|
|
660
740
|
const sub = args.file ?? "status";
|
|
661
741
|
if (sub === "off") {
|
|
662
|
-
setCompactWindow(undefined);
|
|
663
|
-
console.log(
|
|
742
|
+
const r = setCompactWindow(undefined);
|
|
743
|
+
console.log(r.changed
|
|
744
|
+
? "✓ autoCompactWindow removed from ~/.claude/settings.json: Claude Code compacts near the model's full window again (new sessions)."
|
|
745
|
+
: "No auto-compact window was set. Nothing changed.");
|
|
664
746
|
return;
|
|
665
747
|
}
|
|
666
748
|
if (sub !== "status") {
|
|
@@ -670,19 +752,30 @@ async function main() {
|
|
|
670
752
|
process.exitCode = 1;
|
|
671
753
|
return;
|
|
672
754
|
}
|
|
673
|
-
setCompactWindow(w);
|
|
674
|
-
|
|
755
|
+
const r = setCompactWindow(w);
|
|
756
|
+
if (!r.changed) {
|
|
757
|
+
console.log(`autoCompactWindow is already ${w} in ~/.claude/settings.json. Nothing changed.`);
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
// Only claim a backup that exists: a new settings.json had nothing to back up.
|
|
761
|
+
const note = r.created ? "a new file" : r.backup ? `the previous file is kept as ${r.backup.replace(homedir(), "~")}` : "";
|
|
762
|
+
console.log(`✓ autoCompactWindow = ${w} in ~/.claude/settings.json${note ? ` (${note})` : ""}.`);
|
|
675
763
|
console.log(" Claude Code sessions started from now on compact as if the window were that size,");
|
|
676
764
|
console.log(" in the terminal, IDEs and the desktop app. Check in a session with /context.");
|
|
677
|
-
console.log(
|
|
765
|
+
console.log(` Undo: ${selfCommand("compact-window off")}`);
|
|
678
766
|
return;
|
|
679
767
|
}
|
|
680
768
|
const current = currentCompactWindow();
|
|
681
769
|
const windows = [200_000, 300_000, 400_000, 600_000, 800_000];
|
|
682
770
|
if (current && !windows.includes(current))
|
|
683
771
|
windows.push(current);
|
|
684
|
-
const
|
|
685
|
-
|
|
772
|
+
const measuring = progressLine("Measuring your compactions");
|
|
773
|
+
const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
|
|
774
|
+
measuring.clear();
|
|
775
|
+
const replaying = progressLine("Replaying your sessions at each window");
|
|
776
|
+
const cw = estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread, replaying.tick);
|
|
777
|
+
replaying.clear();
|
|
778
|
+
console.log(renderCompactWindows(cw, current));
|
|
686
779
|
return;
|
|
687
780
|
}
|
|
688
781
|
if (args.command === "autopilot") {
|
|
@@ -698,7 +791,10 @@ async function main() {
|
|
|
698
791
|
console.log((await autopilotOff()).join("\n"));
|
|
699
792
|
}
|
|
700
793
|
else if (sub === "pause" || sub === "resume") {
|
|
701
|
-
|
|
794
|
+
const r = autopilotPauseResult(sub === "pause");
|
|
795
|
+
console.log(r.message);
|
|
796
|
+
if (!r.ok)
|
|
797
|
+
process.exitCode = 1;
|
|
702
798
|
}
|
|
703
799
|
else if (sub === "status") {
|
|
704
800
|
console.log((await autopilotStatus()).join("\n"));
|
|
@@ -754,19 +850,21 @@ async function main() {
|
|
|
754
850
|
return;
|
|
755
851
|
}
|
|
756
852
|
if (args.command === "subagents") {
|
|
757
|
-
const
|
|
853
|
+
const reading = progressLine("Reading your sessions' subagents");
|
|
854
|
+
const report = subagentPayback(args.days ?? 30, undefined, reading.tick);
|
|
855
|
+
reading.clear();
|
|
758
856
|
console.log(args.json ? JSON.stringify(report, null, 2) : renderPayback(report, args.limit ?? 8));
|
|
759
857
|
return;
|
|
760
858
|
}
|
|
761
859
|
if (args.command === "cache-plan") {
|
|
762
860
|
const file = args.positionals?.[0];
|
|
763
861
|
if (!file) {
|
|
764
|
-
console.error("usage: context-doctor cache-plan <request.json|-> [--calls 10] [--out planned.json]");
|
|
862
|
+
console.error("usage: context-doctor cache-plan <request.json|-> [--calls 10] [--out planned.json] [--explicit]");
|
|
765
863
|
process.exit(1);
|
|
766
864
|
}
|
|
767
865
|
let result;
|
|
768
866
|
try {
|
|
769
|
-
result = planCache(readInput(file), args.calls ?? 10, args.model);
|
|
867
|
+
result = planCache(readInput(file), args.calls ?? 10, args.model, { explicit: args.explicit });
|
|
770
868
|
}
|
|
771
869
|
catch (e) {
|
|
772
870
|
console.error(`Could not read a request from ${file}: ${e.message}`);
|
|
@@ -828,7 +926,14 @@ async function main() {
|
|
|
828
926
|
return;
|
|
829
927
|
}
|
|
830
928
|
if (args.command === "overhead") {
|
|
831
|
-
const
|
|
929
|
+
const sessions = progressLine("Measuring each session's first request");
|
|
930
|
+
const tools = progressLine("Counting MCP tool calls");
|
|
931
|
+
const report = overheadReport({
|
|
932
|
+
days: args.days,
|
|
933
|
+
onProgress: (done, total, stage) => (stage === "sessions" ? sessions : tools).tick?.(done, total),
|
|
934
|
+
});
|
|
935
|
+
sessions.clear();
|
|
936
|
+
tools.clear();
|
|
832
937
|
if (args.mcp)
|
|
833
938
|
await measureMcpSizes(report);
|
|
834
939
|
console.log(args.json ? JSON.stringify(report, (_k, v) => (v instanceof Map ? Object.fromEntries(v) : v), 2) : renderOverhead(report));
|
|
@@ -851,14 +956,14 @@ async function main() {
|
|
|
851
956
|
console.log(args.json ? JSON.stringify({ ...result, chunks: undefined, outline: result.chunks.map(({ text, ...c }) => c) }, null, 2) : renderPack(result));
|
|
852
957
|
return;
|
|
853
958
|
}
|
|
854
|
-
if (!args.command
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
959
|
+
if (!args.command) {
|
|
960
|
+
// Bare, with no history to measure or not in a terminal: where to begin.
|
|
961
|
+
console.log(withInvocation(START_HERE));
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
if (!args.file) {
|
|
965
|
+
// analyze/optimize without a file: say what is missing, then how to call it.
|
|
966
|
+
usageError(`${args.command} needs a conversation file (or - to read stdin).\n\n${commandHelp(HELP, args.command) ?? ""}`);
|
|
862
967
|
}
|
|
863
968
|
let input;
|
|
864
969
|
try {
|
|
@@ -868,9 +973,16 @@ async function main() {
|
|
|
868
973
|
console.error(`Could not read ${args.file}: ${e.message}`);
|
|
869
974
|
process.exit(1);
|
|
870
975
|
}
|
|
976
|
+
// Broken JSON, or JSON that is not a conversation, used to profile as a
|
|
977
|
+
// few tokens (or none) and report the context "in good shape". Raw text
|
|
978
|
+
// stays a supported input: it parses without a warning.
|
|
979
|
+
const conversation = parseConversation(input);
|
|
980
|
+
if (conversation.parseWarning) {
|
|
981
|
+
usageError(`Could not ${args.command} ${args.file === "-" ? "stdin" : args.file}: ${conversation.parseWarning}`);
|
|
982
|
+
}
|
|
871
983
|
if (args.command === "analyze") {
|
|
872
984
|
const loaded = loadConfig(process.cwd(), (m) => console.error(`context-doctor: ${m}`));
|
|
873
|
-
const profile = profileConversation(
|
|
985
|
+
const profile = profileConversation(conversation, args.model ?? loaded.config.model);
|
|
874
986
|
// The exact count is awaited before anything prints: with --json it goes
|
|
875
987
|
// inside the one JSON object. Printed after it, as it once was, the extra
|
|
876
988
|
// lines made stdout invalid JSON for every script that parsed it.
|