context-doctor 0.38.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +28 -19
  2. package/dist/antigravity.d.ts +44 -0
  3. package/dist/antigravity.js +80 -0
  4. package/dist/autoclear.d.ts +15 -0
  5. package/dist/autoclear.js +17 -0
  6. package/dist/autopilot.js +3 -2
  7. package/dist/cachemisses.d.ts +56 -2
  8. package/dist/cachemisses.js +252 -42
  9. package/dist/cachettl.d.ts +127 -0
  10. package/dist/cachettl.js +357 -0
  11. package/dist/claudedir.d.ts +17 -0
  12. package/dist/claudedir.js +32 -0
  13. package/dist/cli.js +303 -26
  14. package/dist/coldresume.d.ts +15 -0
  15. package/dist/coldresume.js +60 -11
  16. package/dist/compactquality.d.ts +5 -0
  17. package/dist/compactquality.js +108 -61
  18. package/dist/compactwindow.d.ts +14 -5
  19. package/dist/compactwindow.js +36 -43
  20. package/dist/doctor.d.ts +14 -0
  21. package/dist/doctor.js +94 -8
  22. package/dist/effective.d.ts +55 -0
  23. package/dist/effective.js +163 -0
  24. package/dist/experiment.js +2 -2
  25. package/dist/extract.js +4 -1
  26. package/dist/fanout.js +2 -2
  27. package/dist/fix.d.ts +176 -0
  28. package/dist/fix.js +574 -0
  29. package/dist/hook.js +2 -2
  30. package/dist/install.d.ts +27 -1
  31. package/dist/install.js +248 -37
  32. package/dist/ledger.js +2 -2
  33. package/dist/lens.d.ts +2 -0
  34. package/dist/lens.js +50 -24
  35. package/dist/limits.d.ts +10 -0
  36. package/dist/limits.js +36 -12
  37. package/dist/mcp.js +61 -61
  38. package/dist/mcpclient.js +28 -28
  39. package/dist/mcpschema.d.ts +18 -0
  40. package/dist/mcpschema.js +74 -31
  41. package/dist/missledger.d.ts +61 -0
  42. package/dist/missledger.js +198 -0
  43. package/dist/overhead.js +22 -25
  44. package/dist/profile.js +8 -8
  45. package/dist/proxy.d.ts +1 -1
  46. package/dist/proxy.js +2 -1
  47. package/dist/prune.d.ts +4 -0
  48. package/dist/prune.js +89 -49
  49. package/dist/reads.js +2 -2
  50. package/dist/recall.js +2 -1
  51. package/dist/savings.d.ts +5 -9
  52. package/dist/savings.js +217 -115
  53. package/dist/scan.d.ts +96 -0
  54. package/dist/scan.js +482 -0
  55. package/dist/session.d.ts +6 -0
  56. package/dist/session.js +16 -3
  57. package/dist/settingsedit.d.ts +72 -0
  58. package/dist/settingsedit.js +493 -0
  59. package/dist/statusline.d.ts +38 -2
  60. package/dist/statusline.js +66 -4
  61. package/dist/subagentpay.js +2 -2
  62. package/dist/tasks.js +2 -2
  63. package/dist/tokens.d.ts +5 -0
  64. package/dist/tokens.js +11 -1
  65. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * `-` reads from stdin, so you can pipe: `cat chat.json | context-doctor analyze -`
9
9
  */
10
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
11
11
  import { homedir } from "node:os";
12
12
  import { join } from "node:path";
13
13
  import process from "node:process";
@@ -19,15 +19,18 @@ import { selfCommand, withInvocation } from "./invocation.js";
19
19
  import { renderProfile } from "./report.js";
20
20
  import { formatTokens } from "./tokens.js";
21
21
  import { startProxy } from "./proxy.js";
22
- import { runInstall, runUninstall } from "./install.js";
23
- import { listSessions, parseSessionFile, pickCurrentSession } from "./session.js";
22
+ import { claudeCodeInstallsFromEnv, claudePluginEnabled, runInstall, runUninstall } from "./install.js";
23
+ import { listSessions, parseSessionFile, pickCurrentSession, isClaudeSession } from "./session.js";
24
24
  import { runHook } from "./hook.js";
25
25
  import { abCommand } from "./ab.js";
26
26
  import { buildImpactReport } from "./impact.js";
27
27
  import { measureTokenizer, renderTokenizer } from "./tokenizer-measure.js";
28
28
  import { autopilotOff, autopilotOn, autopilotPauseResult, autopilotPaths, autopilotStatus, DEFAULT_AUTOPILOT_PORT } from "./autopilot.js";
29
- import { estimateSavings, renderSavings, renderShare } from "./savings.js";
30
- import { currentCompactWindow, estimateCompactWindows, MAX_WINDOW, MIN_WINDOW, parseWindow, renderCompactWindows, setCompactWindow } from "./compactwindow.js";
29
+ import { estimateSavings, renderSavings, renderShare, savingsRows } from "./savings.js";
30
+ import { prescan } from "./scan.js";
31
+ import { REQUEST_ROWS } from "./coldresume.js";
32
+ import { currentCompactWindow, estimateCompactWindows, MAX_WINDOW, MIN_WINDOW, parseWindow, renderCompactWindows, setCompactWindow, settingsPath } from "./compactwindow.js";
33
+ import { tilde } from "./claudedir.js";
31
34
  import { renderPreferences, copyToClipboard, CHAT_PREFERENCES } from "./preferences.js";
32
35
  import { recordLedger } from "./ledger.js";
33
36
  import { runDoctor } from "./doctor.js";
@@ -35,7 +38,7 @@ import { measureAccuracy, renderAccuracy } from "./accuracy.js";
35
38
  import { renderDiff } from "./diff.js";
36
39
  import { renderExperiment, runExperiment } from "./experiment.js";
37
40
  import { runStatusLine } from "./statusline.js";
38
- import { renderSubagents, subagentReport } from "./subagents.js";
41
+ import { renderSubagents, subagentDir, subagentReport } from "./subagents.js";
39
42
  import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
40
43
  import { runWatch } from "./watch.js";
41
44
  import { exactTokenCount } from "./exact.js";
@@ -52,31 +55,43 @@ import { ciReport, renderCiMarkdown, renderCiText } from "./ci.js";
52
55
  import { renderReads, repeatedReads } from "./reads.js";
53
56
  import { costPerTask, renderTasks } from "./tasks.js";
54
57
  import { planCache, renderCachePlan } from "./cacheplan.js";
55
- import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses } from "./cachemisses.js";
58
+ import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses, MISS_ROWS } from "./cachemisses.js";
56
59
  import { renderPayback, subagentPayback } from "./subagentpay.js";
57
- import { compactionQuality, renderCompactionQuality } from "./compactquality.js";
60
+ import { compactionQuality, renderCompactionQuality, QUALITY_ROWS } from "./compactquality.js";
58
61
  import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
59
62
  import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits } from "./limits.js";
60
63
  import { currentTranscript, findSession, recall, renderRecall } from "./recall.js";
61
64
  import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
62
- import { applyPrune, canonical, planPrune, renderPrune, undoPrune } from "./prune.js";
63
- import { lensOverSessions, renderLens, sessionLens } from "./lens.js";
65
+ import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPrune } from "./prune.js";
66
+ import { lensOverSessions, renderLens, sessionLens, LENS_ROWS } from "./lens.js";
67
+ import { applyFix, fixOverrides, loadFixRecords, parseFixIds, planFixes, readFixRecords, renderFixPlan, renderFixShare, savedSince, undoFixes } from "./fix.js";
68
+ import { claudeMcpConfigs, MCP_ROWS } from "./mcpschema.js";
69
+ import { effectiveEnv, settingsSources } from "./effective.js";
70
+ import { SettingsError } from "./settingsedit.js";
71
+ import { currentTtl, estimateCacheTtl, renderCacheTtl, setCacheTtl, settingKey, subagentTranscripts, ttlUnsupported, CACHE_TTL_SINCE } from "./cachettl.js";
72
+ import { claudeDir } from "./claudedir.js";
64
73
  const HELP = `context-doctor — profile and optimize LLM context windows
65
74
 
66
75
  Start here:
67
76
  context-doctor install [--statusline] Wire everything it finds: the MCP server (Claude
68
77
  Desktop, Claude Code, Cursor, Codex, Gemini CLI,
69
- GitHub Copilot), the skill (Claude Code, Codex), the
70
- every-prompt hook (Claude Code, Codex, Gemini CLI's
71
- BeforeAgent, Cursor's postToolUse), Claude Code's
72
- PreCompact hook, which tells each compaction what to
73
- keep, and Copilot's sessionStart (the standing rules)
78
+ GitHub Copilot, Antigravity), the skill (Claude
79
+ Code, Codex, Antigravity), the every-prompt hook
80
+ (Claude Code, Codex, Gemini CLI's BeforeAgent,
81
+ Cursor's postToolUse), Claude Code's PreCompact
82
+ hook, which tells each compaction what to keep,
83
+ and Copilot's sessionStart (the standing rules)
74
84
  context-doctor savings [--days n] [--share [--copy]]
75
85
  What your recent Claude Code sessions cost, and what
76
86
  /compact at cold resumes, autopilot and an earlier
77
87
  auto-compact window would save, replayed and priced
78
88
  as billed. --share: totals only, to paste. Also
79
89
  what a bare \`context-doctor\` shows
90
+ context-doctor fix [--apply ids|all] [--share] What to change, ranked by dollars on your own
91
+ sessions (compact earlier, the cache lifetime,
92
+ autopilot, MCP tool search, unused servers): each
93
+ applied only on a yes, \`fix undo\` reverts them,
94
+ later runs show what each saved since
80
95
  context-doctor doctor Self-check the installation (configs, hook, skill,
81
96
  MCP handshake) with one pasteable diagnosis
82
97
  context-doctor uninstall Undo install
@@ -139,6 +154,12 @@ Fix automatically:
139
154
  Claude Code's own auto-compact window (e.g. 400k):
140
155
  what each size would have saved on your sessions,
141
156
  and set or remove it. Works in the desktop app too
157
+ context-doctor cache-ttl [status|1h|5m|off] [--subagents]
158
+ How long Claude Code's prompt cache lives (5 minutes
159
+ or 1 hour), replayed on your own pauses: what each
160
+ would have cost, then set or remove promptCacheTtl
161
+ (--subagents: subagentPromptCacheTtl). Same content
162
+ either way: price only. Desktop app too
142
163
  context-doctor proxy --autopilot [options] Local proxy for your own API apps (Anthropic, OpenAI,
143
164
  Gemini): clears stale tool output only when the
144
165
  prompt cache is cold, so it never costs more.
@@ -225,8 +246,8 @@ Options:
225
246
  --max-tool-tokens <n> (optimize) Token budget for trimmed tool results (default 300)
226
247
  --limit <n> (accuracy, session --list, reads, tasks, subagents) How many to sample
227
248
  or list
228
- --days <n> (savings, compact-window, overhead, reads, tasks, subagents, compactions,
229
- cache-misses, limits)
249
+ --days <n> (savings, compact-window, cache-ttl, overhead, reads, tasks, subagents,
250
+ compactions, cache-misses, limits)
230
251
  Days of history to read (default 30; compactions 60)
231
252
  -q, --query <text> (pack) The question to rank chunks against
232
253
  --max-tokens <n> (pack) Token budget (default 4000); (recall) default 2000; (ci) fail over
@@ -278,14 +299,100 @@ Start here
278
299
  In Claude Code, as a plugin:
279
300
  /plugin marketplace add KushalP1/context-doctor
280
301
  /plugin install context-doctor@context-doctor
281
- then /context-doctor:savings, :checkup, :overhead, :compact-window, :autopilot, :pack
302
+ then /context-doctor:fix, :savings, :checkup, :overhead, :compact-window, :autopilot, :pack
282
303
  In a terminal:
304
+ context-doctor fix what to change, ranked by what it saves you; applied only on a yes
283
305
  context-doctor install wire the MCP server, skill and hooks into the apps it finds
284
306
  context-doctor savings what your recent sessions cost, and what each fix would save
285
307
  context-doctor doctor check the installation
286
308
 
287
309
  All commands: context-doctor --help
288
310
  Guide: https://github.com/KushalP1/context-doctor#readme`;
311
+ /** Claude Code transcripts written in the last `days`: the ones the replays read. */
312
+ function claudeTranscripts(days) {
313
+ const since = Date.now() - days * 86_400_000;
314
+ return listSessions(10_000).filter((s) => isClaudeSession(s) && s.modifiedAt.getTime() >= since).map((s) => s.path);
315
+ }
316
+ /**
317
+ * Everything `fix` ranks, measured on this machine's history (read-only):
318
+ * the same replays `savings`, `compact-window` and `cache-ttl` run.
319
+ */
320
+ async function measureFixInputs(days) {
321
+ const cwd = process.cwd();
322
+ const autopilotOnNow = existsSync(autopilotPaths().config);
323
+ // With autopilot already on, its replay (most of the time) answers nothing `fix` asks.
324
+ const replaying = progressLine(autopilotOnNow ? "Reading your Claude Code sessions" : "Replaying your Claude Code sessions");
325
+ const setWindow = currentCompactWindow();
326
+ // Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
327
+ prescan([
328
+ { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS] },
329
+ { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS] },
330
+ ...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
331
+ ], replaying.tick);
332
+ const report = estimateSavings(days, {}, undefined, replaying.tick, !autopilotOnNow);
333
+ replaying.clear();
334
+ let compactWindow;
335
+ if (setWindow !== undefined) {
336
+ compactWindow = { window: setWindow, savedUsd: 0, savedShare: 0, compactionsPerWeek: 0, nowPerWeek: 0, current: setWindow };
337
+ }
338
+ else {
339
+ const measuring = progressLine("Measuring your compactions");
340
+ const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
341
+ measuring.clear();
342
+ const windowing = progressLine("Replaying an earlier auto-compact window");
343
+ const cw = estimateCompactWindows([400_000], days, undefined, reread, windowing.tick);
344
+ windowing.clear();
345
+ const est = cw.estimates[0];
346
+ if (cw.sessions > 0 && est)
347
+ compactWindow = { window: est.window, savedUsd: est.savedUsd, savedShare: est.savedPct, compactionsPerWeek: (est.compactions / cw.days) * 7, nowPerWeek: (cw.actualCompactions / cw.days) * 7 };
348
+ }
349
+ const ttling = progressLine("Replaying both cache lifetimes");
350
+ const ttl = estimateCacheTtl(days, { onProgress: ttling.tick });
351
+ ttling.clear();
352
+ const sources = settingsSources({ cwd });
353
+ const ts = effectiveEnv("ENABLE_TOOL_SEARCH", sources);
354
+ const toolSearchOff = ts && /^(false|0|no|off)$/i.test(ts.value.trim()) ? ts.value : undefined;
355
+ const servers = claudeMcpConfigs(cwd).filter((c) => !/context-doctor/i.test(c.name));
356
+ // Prune reads every transcript for MCP and skill use: only when this project has something to prune.
357
+ let prunePlan;
358
+ if (servers.length > 0 || installedSkills(cwd).some((k) => !/context-doctor/i.test(k.name))) {
359
+ try {
360
+ prunePlan = planPrune(days, { cwds: [cwd] }).plans[0];
361
+ }
362
+ catch { /* no project here */ }
363
+ }
364
+ let userSettings = {};
365
+ try {
366
+ userSettings = JSON.parse(readFileSync(join(claudeDir(), "settings.json"), "utf8")) ?? {};
367
+ }
368
+ catch { /* none */ }
369
+ let recordProblem;
370
+ try {
371
+ loadFixRecords();
372
+ }
373
+ catch (e) {
374
+ recordProblem = e.message;
375
+ }
376
+ const sessions = report.sessions.length;
377
+ const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search"];
378
+ return {
379
+ prunePlan,
380
+ inputs: {
381
+ days,
382
+ billedUsd: report.billedUsd,
383
+ compactWindow,
384
+ ttl,
385
+ currentTtl: currentTtl(),
386
+ autopilot: { on: autopilotOnNow, reachableUsd: report.reachableUsd, reachableShare: report.billedUsd > 0 ? report.reachableUsd / report.billedUsd : 0, unreachableSessions: report.unreachableSessions, sessions },
387
+ toolSearchOff,
388
+ mcpServers: toolSearchOff ? servers.length : 0,
389
+ prune: prunePlan,
390
+ overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
391
+ recordProblem,
392
+ coldResume: { netUsd: Math.max(0, report.coldResumeNetUsd), returns: report.coldResumes, hooked: claudePluginEnabled() || /context-doctor|cli\.js"?\s+hook/.test(JSON.stringify(userSettings.hooks?.UserPromptSubmit ?? [])) },
393
+ },
394
+ };
395
+ }
289
396
  /** Exit 1 with a usage message: wrong arguments are the caller's to fix, not a crash. */
290
397
  function usageError(message) {
291
398
  console.error(message);
@@ -298,7 +405,7 @@ function usageError(message) {
298
405
  const COMMANDS = [
299
406
  "analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
300
407
  "instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
301
- "experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "limits", "subagents", "tasks",
408
+ "experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "cache-ttl", "fix", "limits", "subagents", "tasks",
302
409
  "reads", "pack", "watch", "ab", "handoff", "recall", "help", "version",
303
410
  ];
304
411
  /** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
@@ -349,6 +456,8 @@ const FLAGS = [
349
456
  { names: ["--mcp"], set: (a) => { a.mcp = true; } },
350
457
  { names: ["--write"], set: (a) => { a.write = true; } },
351
458
  { names: ["--undo"], set: (a) => { a.undo = true; } },
459
+ { names: ["--subagents"], set: (a) => { a.subagentsTtl = true; } },
460
+ { names: ["--apply"], value: "text", set: (a, v) => { a.apply = v; } },
352
461
  { names: ["--calls"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.calls = v; } },
353
462
  { names: ["--explicit"], set: (a) => { a.explicit = true; } },
354
463
  { names: ["--semantic"], set: (a) => { a.semantic = a.semantic || true; } },
@@ -515,7 +624,7 @@ function progressLine(label) {
515
624
  /** Any Claude Code transcript on this machine? One directory listing, no parsing. */
516
625
  function hasClaudeSessions() {
517
626
  try {
518
- return listSessions(1).some((s) => s.path.includes(".claude"));
627
+ return listSessions(1).some((s) => isClaudeSession(s));
519
628
  }
520
629
  catch {
521
630
  return false;
@@ -786,6 +895,11 @@ async function main() {
786
895
  // machine, answers the question people install this for: what would it
787
896
  // save me? Scripts and pipes still get the help text.
788
897
  const replaying = progressLine("Replaying your Claude Code sessions through autopilot");
898
+ // Each transcript read once for every report below; what an earlier run kept is not read again (scan.ts).
899
+ prescan([
900
+ { paths: claudeTranscripts(args.days ?? 30), extractors: [savingsRows(), REQUEST_ROWS, MISS_ROWS, LENS_ROWS] },
901
+ { paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] },
902
+ ], replaying.tick);
789
903
  const report = estimateSavings(args.days ?? 30, {}, undefined, replaying.tick);
790
904
  replaying.clear();
791
905
  const setWindow = currentCompactWindow();
@@ -825,8 +939,9 @@ async function main() {
825
939
  }
826
940
  else {
827
941
  console.log(renderSavings(report, on, cwLine, cacheMissesSignificant(misses) ? cacheMissesLine(misses) : undefined, limitLines, renderLens(lens)));
942
+ console.log(`\nNext: ${selfCommand("fix")} ranks every fix by what it saves you and applies only the ones you say yes to (${selfCommand("fix undo")} reverts them).`);
828
943
  if (!args.command)
829
- console.log(`\nAll commands: ${selfCommand("--help")}`);
944
+ console.log(`All commands: ${selfCommand("--help")}`);
830
945
  }
831
946
  return;
832
947
  }
@@ -842,9 +957,19 @@ async function main() {
842
957
  if (args.command === "compact-window") {
843
958
  const sub = args.file ?? "status";
844
959
  if (sub === "off") {
845
- const r = setCompactWindow(undefined);
960
+ let r;
961
+ try {
962
+ r = setCompactWindow(undefined);
963
+ }
964
+ catch (e) {
965
+ if (!(e instanceof SettingsError))
966
+ throw e;
967
+ console.error(e.message);
968
+ process.exitCode = 1;
969
+ return;
970
+ }
846
971
  console.log(r.changed
847
- ? "✓ autoCompactWindow removed from ~/.claude/settings.json: Claude Code compacts near the model's full window again (new sessions)."
972
+ ? `✓ autoCompactWindow removed from ${tilde(settingsPath())}: Claude Code compacts near the model's full window again (new sessions).`
848
973
  : "No auto-compact window was set. Nothing changed.");
849
974
  return;
850
975
  }
@@ -855,16 +980,31 @@ async function main() {
855
980
  process.exitCode = 1;
856
981
  return;
857
982
  }
858
- const r = setCompactWindow(w);
983
+ let r;
984
+ try {
985
+ r = setCompactWindow(w);
986
+ }
987
+ catch (e) {
988
+ if (!(e instanceof SettingsError))
989
+ throw e;
990
+ console.error(e.message);
991
+ process.exitCode = 1;
992
+ return;
993
+ }
859
994
  if (!r.changed) {
860
- console.log(`autoCompactWindow is already ${w} in ~/.claude/settings.json. Nothing changed.`);
995
+ console.log(`autoCompactWindow is already ${w} in ${tilde(settingsPath())}. Nothing changed.`);
861
996
  return;
862
997
  }
863
998
  // Only claim a backup that exists: a new settings.json had nothing to back up.
864
999
  const note = r.created ? "a new file" : r.backup ? `the previous file is kept as ${r.backup.replace(homedir(), "~")}` : "";
865
- console.log(`✓ autoCompactWindow = ${w} in ~/.claude/settings.json${note ? ` (${note})` : ""}.`);
1000
+ console.log(`✓ autoCompactWindow = ${w} in ${tilde(settingsPath())}${note ? ` (${note})` : ""}.`);
866
1001
  console.log(" Claude Code sessions started from now on compact as if the window were that size,");
867
1002
  console.log(" in the terminal, IDEs and the desktop app. Check in a session with /context.");
1003
+ const over = fixOverrides("compact-window");
1004
+ if (over.length) {
1005
+ console.log(` ⚠ It will not take effect while ${over.join("; ")} ${over.length === 1 ? "overrides" : "override"} it.`);
1006
+ process.exitCode = 1;
1007
+ }
868
1008
  console.log(` Undo: ${selfCommand("compact-window off")}`);
869
1009
  return;
870
1010
  }
@@ -873,6 +1013,10 @@ async function main() {
873
1013
  if (current && !windows.includes(current))
874
1014
  windows.push(current);
875
1015
  const measuring = progressLine("Measuring your compactions");
1016
+ prescan([
1017
+ { paths: claudeTranscripts(args.days ?? 30), extractors: [REQUEST_ROWS] },
1018
+ { paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] },
1019
+ ], measuring.tick);
876
1020
  const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
877
1021
  measuring.clear();
878
1022
  const replaying = progressLine("Replaying your sessions at each window");
@@ -995,6 +1139,128 @@ async function main() {
995
1139
  });
996
1140
  return; // server keeps the process alive
997
1141
  }
1142
+ if (args.command === "fix") {
1143
+ const sub = args.file;
1144
+ if (sub === "undo") {
1145
+ const named = (args.positionals ?? []).slice(1).flatMap((x) => x.split(",")).map((x) => x.trim()).filter(Boolean);
1146
+ const lines = await undoFixes(named.length ? named : undefined, { autopilotOff: () => autopilotOff() });
1147
+ console.log(lines.join("\n"));
1148
+ if (lines.some((l) => l.startsWith("✗")))
1149
+ process.exitCode = 1;
1150
+ return;
1151
+ }
1152
+ if (sub !== undefined && sub !== "plan")
1153
+ usageError(`Usage: context-doctor fix [--apply <ids|all>] [--share] [--json] | fix undo [ids]; got "${sub}".`);
1154
+ if (args.apply !== undefined && args.share)
1155
+ usageError("--apply and --share do not go together: --share only prints totals.");
1156
+ const { inputs, prunePlan } = await measureFixInputs(args.days ?? 30);
1157
+ const fixes = planFixes(inputs);
1158
+ const since = savedSince(readFixRecords());
1159
+ if (args.share) {
1160
+ const text = renderFixShare(inputs.days, inputs.billedUsd, fixes);
1161
+ console.log(text);
1162
+ if (args.copy)
1163
+ console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
1164
+ return;
1165
+ }
1166
+ const available = fixes.filter((f) => f.state === "available");
1167
+ let chosen = [];
1168
+ if (args.apply !== undefined) {
1169
+ const { ids, unknown } = parseFixIds(args.apply, fixes);
1170
+ if (unknown.length)
1171
+ usageError(`--apply: unknown fix ${unknown.join(", ")}. Fixes: ${available.map((f) => f.id).join(", ") || "none available"}.`);
1172
+ chosen = ids;
1173
+ }
1174
+ if (!args.json)
1175
+ console.log(renderFixPlan(inputs.days, inputs.billedUsd, fixes, since, selfCommand, inputs.coldResume, inputs.recordProblem));
1176
+ if (args.apply === undefined && !args.json && process.stdin.isTTY && process.stdout.isTTY && available.length && !inputs.recordProblem) {
1177
+ const rl = (await import("node:readline/promises")).createInterface({ input: process.stdin, output: process.stdout });
1178
+ console.log("");
1179
+ for (const [n, f] of available.entries()) {
1180
+ const a = (await rl.question(`Apply ${n + 1}. ${f.title}? [y/N] `)).trim().toLowerCase();
1181
+ if (a === "y" || a === "yes")
1182
+ chosen.push(f.id);
1183
+ }
1184
+ rl.close();
1185
+ }
1186
+ const results = [];
1187
+ for (const id of chosen) {
1188
+ const f = fixes.find((x) => x.id === id);
1189
+ if (!f || f.state !== "available") {
1190
+ results.push({ id, ok: false, lines: [`${id}: ${f?.note ?? "not available here"}; skipped.`] });
1191
+ continue;
1192
+ }
1193
+ const kind = id === "cache-ttl" ? "main" : id === "cache-ttl-subagents" ? "subagents" : undefined;
1194
+ const r = await applyFix(f, { autopilotOn: () => autopilotOn(args.port ?? DEFAULT_AUTOPILOT_PORT) }, { oneHourShare: kind ? inputs.ttl?.[kind].oneHourShare : undefined, prune: prunePlan });
1195
+ results.push({ id, ...r });
1196
+ }
1197
+ // Naming fixes that are not there (or nothing at all, with "all") is not a silent success.
1198
+ if (args.apply !== undefined && (chosen.length === 0 || results.some((r) => !r.ok)))
1199
+ process.exitCode = 1;
1200
+ if (args.json) {
1201
+ console.log(JSON.stringify({ days: inputs.days, billedUsd: inputs.billedUsd, fixes, since, ...(args.apply !== undefined ? { applied: results } : {}), ...(inputs.recordProblem ? { recordProblem: inputs.recordProblem } : {}) }, null, 2));
1202
+ if (args.apply !== undefined && chosen.length === 0)
1203
+ console.error("--apply: no fix available to apply.");
1204
+ return;
1205
+ }
1206
+ if (args.apply !== undefined && chosen.length === 0)
1207
+ console.error("\n--apply: no fix available to apply.");
1208
+ if (!results.length)
1209
+ return;
1210
+ console.log("");
1211
+ for (const r of results)
1212
+ console.log(r.lines.join("\n"));
1213
+ if (results.some((r) => r.ok))
1214
+ console.log(`\nNew Claude Code sessions pick these up. Undo: ${selfCommand("fix undo")}; ${selfCommand("fix")} later shows what each saved since.`);
1215
+ return;
1216
+ }
1217
+ if (args.command === "cache-ttl") {
1218
+ const sub = args.file ?? "status";
1219
+ const kind = args.subagentsTtl ? "subagents" : "main";
1220
+ const key = settingKey(kind);
1221
+ if (sub === "1h" || sub === "5m" || sub === "off") {
1222
+ let r;
1223
+ try {
1224
+ r = setCacheTtl(kind, sub === "off" ? undefined : sub);
1225
+ }
1226
+ catch (e) {
1227
+ if (!(e instanceof SettingsError))
1228
+ throw e;
1229
+ console.error(e.message);
1230
+ process.exitCode = 1;
1231
+ return;
1232
+ }
1233
+ if (!r.changed) {
1234
+ console.log(sub === "off" ? `${key} was not set. Nothing changed.` : `${key} is already "${sub}" in ${tilde(settingsPath())}. Nothing changed.`);
1235
+ return;
1236
+ }
1237
+ const note = r.created ? " (a new file)" : r.backup ? ` (the previous file is kept as ${r.backup.replace(homedir(), "~")})` : "";
1238
+ console.log(sub === "off"
1239
+ ? `✓ ${key} removed from ${tilde(settingsPath())}${note}: Claude Code picks the lifetime itself again (new sessions).`
1240
+ : `✓ ${key} = "${sub}" in ${tilde(settingsPath())}${note}.`);
1241
+ if (sub !== "off") {
1242
+ console.log(` New ${kind === "main" ? "sessions write the main conversation's" : "subagents write their"} cache at ${sub === "1h" ? "1 hour (2x input per written token)" : "5 minutes (1.25x)"}, in every Claude Code surface.`);
1243
+ const old = ttlUnsupported(claudeCodeInstallsFromEnv());
1244
+ if (old.length)
1245
+ console.log(` ${old.map((i) => "Claude Code " + i.version).join(", ")} predates the setting (${CACHE_TTL_SINCE}) and ignores it.`);
1246
+ const over = fixOverrides(kind === "main" ? "cache-ttl" : "cache-ttl-subagents");
1247
+ if (over.length) {
1248
+ console.log(` ⚠ It will not take effect while ${over.join("; ")} ${over.length === 1 ? "overrides" : "override"} it.`);
1249
+ process.exitCode = 1;
1250
+ }
1251
+ console.log(` Undo: ${selfCommand(`cache-ttl off${kind === "subagents" ? " --subagents" : ""}`)}`);
1252
+ }
1253
+ return;
1254
+ }
1255
+ if (sub !== "status")
1256
+ usageError(`Usage: context-doctor cache-ttl [status | 1h | 5m | off] [--subagents]; got "${sub}".`);
1257
+ const reading = progressLine("Replaying your sessions at both cache lifetimes");
1258
+ const report = estimateCacheTtl(args.days ?? 30, { onProgress: reading.tick });
1259
+ reading.clear();
1260
+ const current = currentTtl();
1261
+ console.log(args.json ? JSON.stringify({ ...report, current }, null, 2) : renderCacheTtl(report, current, claudeCodeInstallsFromEnv(), selfCommand));
1262
+ return;
1263
+ }
998
1264
  if (args.command === "cache-misses") {
999
1265
  const reading = progressLine("Reading your Claude Code transcripts");
1000
1266
  const report = cacheMisses(args.days ?? 30, undefined, reading.tick);
@@ -1157,6 +1423,17 @@ async function main() {
1157
1423
  if (args.command === "overhead") {
1158
1424
  const sessions = progressLine("Measuring each session's first request");
1159
1425
  const tools = progressLine("Counting MCP tool calls");
1426
+ // One read of each Claude Code transcript for both counts (scan.ts); subagents hold MCP calls too.
1427
+ const mains = claudeTranscripts(args.days ?? 30);
1428
+ prescan([
1429
+ { paths: mains, extractors: [REQUEST_ROWS, MCP_ROWS] },
1430
+ { paths: mains.flatMap((p) => { try {
1431
+ return readdirSync(subagentDir(p)).filter((f) => f.endsWith(".jsonl")).map((f) => join(subagentDir(p), f));
1432
+ }
1433
+ catch {
1434
+ return [];
1435
+ } }), extractors: [MCP_ROWS] },
1436
+ ], sessions.tick);
1160
1437
  const report = overheadReport({
1161
1438
  days: args.days,
1162
1439
  onProgress: (done, total, stage) => (stage === "sessions" ? sessions : tools).tick?.(done, total),
@@ -25,6 +25,7 @@
25
25
  * host-orchestrated and drops a settings-file ANTHROPIC_BASE_URL, but it runs
26
26
  * the every-prompt hook, which is where this is called from.
27
27
  */
28
+ import { type Extractor } from "./scan.js";
28
29
  /**
29
30
  * Claude Code's own idle compaction (2.1.290+, account-gated by a server
30
31
  * flag; the `idleCompaction` setting can only turn it off). Read from the
@@ -47,6 +48,20 @@ export declare const IDLE_COMPACT_NOTICE = "Compacted while idle";
47
48
  export declare const IDLE_COMPACT_MIN_TOKENS = 200000;
48
49
  /** The row Claude Code writes after an idle compaction's boundary. */
49
50
  export declare function isIdleCompactNotice(e: any): boolean;
51
+ /**
52
+ * What the request replays (`cache-ttl`, `compact-window`, the cold returns
53
+ * of `savings`, `overhead`'s session starts) take from a Claude Code
54
+ * transcript, as rows of the same shape, cut to what they read: assistant
55
+ * rows (id, model, usage, time, uuid, thread), compaction boundaries, idle
56
+ * compaction notices, and the first user message with text (its length and
57
+ * whether it reads as code: what the token estimate needs of it). A later row of a
58
+ * reply already kept, in the same thread and with usage, is left out: every
59
+ * reader meets it as a repeat of that reply and skips it.
60
+ */
61
+ export declare const REQUEST_ROWS: Extractor<{
62
+ ids: Record<string, number>;
63
+ user: boolean;
64
+ }>;
50
65
  /** The context at which Claude Code's idle compaction acts, as it reads the environment. */
51
66
  export declare function idleCompactMinTokens(env?: NodeJS.ProcessEnv): number;
52
67
  /**
@@ -28,9 +28,11 @@
28
28
  import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs";
29
29
  import { homedir } from "node:os";
30
30
  import { join } from "node:path";
31
- import { forEachLine, replyCounter } from "./session.js";
31
+ import { forEachLine, replyCounter, textOf } from "./session.js";
32
+ import { pick, rowsOf, slimUsage } from "./scan.js";
32
33
  import { cacheWriteSplit, pricingFor, formatUsd, writeMultiplier } from "./pricing.js";
33
- import { contextWindowFor, formatTokens, realModel } from "./tokens.js";
34
+ import { contextWindowFor, formatTokens, isCodeLike, realModel } from "./tokens.js";
35
+ import { claudeDir } from "./claudedir.js";
34
36
  /**
35
37
  * Claude Code's own idle compaction (2.1.290+, account-gated by a server
36
38
  * flag; the `idleCompaction` setting can only turn it off). Read from the
@@ -55,6 +57,60 @@ export const IDLE_COMPACT_MIN_TOKENS = 200_000;
55
57
  export function isIdleCompactNotice(e) {
56
58
  return e?.type === "system" && typeof e.content === "string" && e.content.startsWith(IDLE_COMPACT_NOTICE);
57
59
  }
60
+ /**
61
+ * What the request replays (`cache-ttl`, `compact-window`, the cold returns
62
+ * of `savings`, `overhead`'s session starts) take from a Claude Code
63
+ * transcript, as rows of the same shape, cut to what they read: assistant
64
+ * rows (id, model, usage, time, uuid, thread), compaction boundaries, idle
65
+ * compaction notices, and the first user message with text (its length and
66
+ * whether it reads as code: what the token estimate needs of it). A later row of a
67
+ * reply already kept, in the same thread and with usage, is left out: every
68
+ * reader meets it as a repeat of that reply and skips it.
69
+ */
70
+ export const REQUEST_ROWS = {
71
+ id: "requests.1",
72
+ init: () => ({ ids: {}, user: false }),
73
+ line(raw, row, out, st) {
74
+ let e;
75
+ try {
76
+ e = row();
77
+ }
78
+ catch {
79
+ return;
80
+ }
81
+ if (!e || typeof e !== "object")
82
+ return;
83
+ if (e.type === "system") {
84
+ if (e.subtype === "compact_boundary")
85
+ out.push(pick(e, ["type", "subtype", "isSidechain", "uuid", "timestamp"]));
86
+ else if (isIdleCompactNotice(e))
87
+ out.push(pick({ ...e, content: IDLE_COMPACT_NOTICE }, ["type", "subtype", "content", "isSidechain", "uuid", "timestamp"]));
88
+ return;
89
+ }
90
+ if (e.type === "user") {
91
+ if (st.user || e.isSidechain || e.isMeta)
92
+ return;
93
+ const text = textOf(e.message?.content);
94
+ if (!text)
95
+ return;
96
+ st.user = true;
97
+ // What the estimate reads of it, not the message itself: the cache keeps no message text.
98
+ out.push({ type: "user", text: { len: text.length, code: isCodeLike(text) } });
99
+ return;
100
+ }
101
+ if (e.type !== "assistant")
102
+ return;
103
+ const m = e.message;
104
+ const thread = e.isSidechain ? 2 : 1;
105
+ if (m && typeof m === "object" && typeof m.id === "string") {
106
+ if ((st.ids[m.id] ?? 0) & thread)
107
+ return;
108
+ if (m.usage)
109
+ st.ids[m.id] = (st.ids[m.id] ?? 0) | thread;
110
+ }
111
+ out.push(pick({ ...e, message: m && typeof m === "object" && !Array.isArray(m) ? pick({ ...m, usage: slimUsage(m.usage) }, ["id", "model", "usage"]) : m }, ["type", "isSidechain", "uuid", "timestamp", "message"]));
112
+ },
113
+ };
58
114
  /** The context at which Claude Code's idle compaction acts, as it reads the environment. */
59
115
  export function idleCompactMinTokens(env = process.env) {
60
116
  const n = Number(env.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS);
@@ -75,7 +131,7 @@ export function autoCompactsAt(model, home = homedir(), env = process.env) {
75
131
  return undefined;
76
132
  let settings = {};
77
133
  try {
78
- settings = JSON.parse(readFileSync(join(home, ".claude", "settings.json"), "utf8")) ?? {};
134
+ settings = JSON.parse(readFileSync(join(claudeDir(home), "settings.json"), "utf8")) ?? {};
79
135
  }
80
136
  catch { /* no settings */ }
81
137
  if (settings.autoCompactEnabled === false)
@@ -316,14 +372,7 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
316
372
  const reqs = [];
317
373
  let model, writes5m = 0, writes1h = 0;
318
374
  const sighting = replyCounter(runRows);
319
- forEachLine(path, (line) => {
320
- let e;
321
- try {
322
- e = JSON.parse(line);
323
- }
324
- catch {
325
- return;
326
- }
375
+ rowsOf(path, REQUEST_ROWS).forEach((e) => {
327
376
  if (!e || e.isSidechain)
328
377
  return;
329
378
  if (e.type === "system" && e.subtype === "compact_boundary") {
@@ -15,6 +15,7 @@
15
15
  * Compactions shaped by context-doctor's PreCompact hook are reported apart,
16
16
  * so its effect can be seen as it accumulates.
17
17
  */
18
+ import { type Extractor } from "./scan.js";
18
19
  interface Signals {
19
20
  requests: number;
20
21
  rereads: number;
@@ -42,6 +43,10 @@ export interface CompactionQuality {
42
43
  after: Signals;
43
44
  };
44
45
  }
46
+ export declare const QUALITY_ROWS: Extractor<{
47
+ lastId?: unknown;
48
+ reads: Record<string, 1>;
49
+ }>;
45
50
  export declare function compactionQuality(days?: number, paths?: string[], onProgress?: (done: number, total: number) => void): CompactionQuality;
46
51
  export declare function renderCompactionQuality(q: CompactionQuality, days?: number): string;
47
52
  export {};