context-doctor 0.45.0 → 0.47.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 (75) hide show
  1. package/README.md +8 -3
  2. package/dist/ab.js +3 -2
  3. package/dist/autopilot.js +9 -5
  4. package/dist/blob.js +66 -12
  5. package/dist/budget.d.ts +10 -1
  6. package/dist/budget.js +37 -8
  7. package/dist/cachemisses.js +5 -3
  8. package/dist/cacheplan.js +2 -2
  9. package/dist/cachettl.js +2 -1
  10. package/dist/ci.js +2 -1
  11. package/dist/claudeplugin.d.ts +97 -0
  12. package/dist/claudeplugin.js +142 -0
  13. package/dist/cli.js +126 -39
  14. package/dist/coldresume.d.ts +6 -0
  15. package/dist/coldresume.js +7 -6
  16. package/dist/compactcost.d.ts +74 -0
  17. package/dist/compactcost.js +115 -0
  18. package/dist/compactwindow.js +5 -4
  19. package/dist/cursor.js +2 -0
  20. package/dist/doctor.js +106 -17
  21. package/dist/extract.js +4 -3
  22. package/dist/fanout.d.ts +15 -0
  23. package/dist/fanout.js +31 -10
  24. package/dist/firstfix.d.ts +43 -0
  25. package/dist/firstfix.js +80 -0
  26. package/dist/fix.d.ts +46 -2
  27. package/dist/fix.js +109 -20
  28. package/dist/hook.js +6 -2
  29. package/dist/httpguard.d.ts +13 -0
  30. package/dist/httpguard.js +22 -0
  31. package/dist/install.d.ts +21 -9
  32. package/dist/install.js +211 -40
  33. package/dist/limits.d.ts +5 -0
  34. package/dist/limits.js +26 -2
  35. package/dist/mcp.js +63 -62
  36. package/dist/missledger.js +5 -3
  37. package/dist/mod/api.d.ts +135 -0
  38. package/dist/mod/api.js +12 -0
  39. package/dist/mod/logic.d.ts +158 -0
  40. package/dist/mod/logic.js +244 -0
  41. package/dist/mod/register.d.ts +60 -0
  42. package/dist/mod/register.js +251 -0
  43. package/dist/modelids.d.ts +24 -0
  44. package/dist/modelids.js +65 -0
  45. package/dist/modelswitch.js +8 -4
  46. package/dist/modmeasure.d.ts +121 -0
  47. package/dist/modmeasure.js +310 -0
  48. package/dist/orgrates.d.ts +93 -0
  49. package/dist/orgrates.js +214 -0
  50. package/dist/overhead.js +11 -8
  51. package/dist/pack.d.ts +13 -0
  52. package/dist/pack.js +68 -3
  53. package/dist/preferences.js +2 -1
  54. package/dist/pricing.d.ts +26 -0
  55. package/dist/pricing.js +61 -7
  56. package/dist/progresssummaries.d.ts +148 -0
  57. package/dist/progresssummaries.js +248 -0
  58. package/dist/proxy.d.ts +1 -1
  59. package/dist/proxy.js +1 -1
  60. package/dist/prune.d.ts +8 -0
  61. package/dist/prune.js +11 -1
  62. package/dist/savings.js +8 -6
  63. package/dist/sessionprice.d.ts +22 -0
  64. package/dist/sessionprice.js +46 -14
  65. package/dist/spend.d.ts +46 -3
  66. package/dist/spend.js +86 -10
  67. package/dist/statusline.js +2 -2
  68. package/dist/subagentmodel.d.ts +12 -0
  69. package/dist/subagentmodel.js +17 -4
  70. package/dist/subagentpay.d.ts +15 -1
  71. package/dist/subagentpay.js +58 -25
  72. package/dist/subagents.js +4 -0
  73. package/dist/toolcwd.d.ts +14 -0
  74. package/dist/toolcwd.js +17 -0
  75. package/package.json +1 -1
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The Claude Code plugin as `install`'s way into Claude Code (E1).
3
+ *
4
+ * The plugin carries everything install used to wire into Claude Code by
5
+ * hand (the MCP server, the skills, the every-prompt, compaction,
6
+ * session-start, subagent-price and model-switch hooks) plus the one thing
7
+ * install could not: the mod (limits readings and Claude Code's own session
8
+ * cost after each turn, the cold-return Compact first button,
9
+ * /context-doctor-fix). Claude Code runs mods from 2.1.286 (Desktop app),
10
+ * 2.1.287 (terminal) and 2.1.299 (VS Code).
11
+ *
12
+ * How it is switched on, verified on 2.1.321 (the Desktop app's) and 2.1.311
13
+ * (Homebrew) in a throwaway HOME: two keys in ~/.claude/settings.json,
14
+ * `extraKnownMarketplaces.context-doctor` (this repository on GitHub) and
15
+ * `enabledPlugins["context-doctor@context-doctor"]: true`. Claude Code never
16
+ * rewrites the file for them. At its next start it clones the marketplace in
17
+ * the background (known_marketplaces.json, plugins/marketplaces/), then
18
+ * downloads the enabled plugin (installed_plugins.json, plugins/cache/), and
19
+ * loads it from the next session start (or /reload-plugins); a `-p` run with
20
+ * CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1 loads it in the first session. The code
21
+ * reconciling declared marketplaces is the binary's "[reconcile]" step; the
22
+ * docs: code.claude.com/docs/en/plugins/loading ("Plugins and marketplaces
23
+ * that aren't on disk at session start"). With both keys taken out again,
24
+ * `claude plugin list` shows the downloaded copy "disabled" and no session
25
+ * loads it. `claude plugin install` does not read the declaration (it
26
+ * answers "not found in marketplace" until `marketplace add`, which
27
+ * re-serialises settings.json), so the CLI is not the way.
28
+ *
29
+ * Settings are one file for every Claude Code on the machine, so the plugin
30
+ * replaces install's own wiring only when every Claude Code found runs mods;
31
+ * with an older one present (or none found) install keeps its own wiring for
32
+ * all of them, as it does for the model-switch hook.
33
+ */
34
+ import { existsSync, readFileSync, statSync } from "node:fs";
35
+ import { dirname, join } from "node:path";
36
+ import { claudeDir } from "./claudedir.js";
37
+ import { compareVersions } from "./modelswitch.js";
38
+ import { statePath } from "./ledger.js";
39
+ /** The first Claude Code that runs a plugin's mod (the Desktop app's Code tab; the terminal from 2.1.287). */
40
+ export const MOD_SINCE = "2.1.286";
41
+ /** Our marketplace's name (.claude-plugin/marketplace.json) and where it lives. */
42
+ export const MARKETPLACE = "context-doctor";
43
+ export const MARKETPLACE_REPO = "KushalP1/context-doctor";
44
+ /**
45
+ * The key Claude Code enables our plugin under: "<plugin>@<marketplace>".
46
+ * A copy listed in another marketplace keeps the plugin name, so any
47
+ * "context-doctor@…" key is ours.
48
+ */
49
+ export const PLUGIN_KEY = `context-doctor@${MARKETPLACE}`;
50
+ export function isOurPluginKey(key) {
51
+ return key === PLUGIN_KEY || key.startsWith("context-doctor@");
52
+ }
53
+ /**
54
+ * The declaration install writes. autoUpdate: Claude Code refreshes it and
55
+ * updates the plugin in the background after startup when plugin.json's
56
+ * version changes (each release), as the npx-launched MCP server follows
57
+ * npm; a third-party marketplace is off by default.
58
+ */
59
+ export function marketplaceDeclaration() {
60
+ return { source: { source: "github", repo: MARKETPLACE_REPO }, autoUpdate: true };
61
+ }
62
+ /** Is this extraKnownMarketplaces entry ours: this repository on GitHub, however Claude Code has touched it since? */
63
+ export function isOurDeclaration(entry) {
64
+ const src = entry?.source;
65
+ return src?.source === "github" && typeof src.repo === "string" && src.repo.toLowerCase() === MARKETPLACE_REPO.toLowerCase();
66
+ }
67
+ export function modReadiness(installs) {
68
+ const old = installs.filter((i) => compareVersions(i.version, MOD_SINCE) < 0);
69
+ return { ok: installs.length > 0 && old.length === 0, old, installs };
70
+ }
71
+ export function pluginMarkerPath() {
72
+ return join(claudeDir(), ".context-doctor-plugin.json");
73
+ }
74
+ export function readPluginMarker() {
75
+ try {
76
+ const raw = JSON.parse(readFileSync(pluginMarkerPath(), "utf8"));
77
+ if (!raw || typeof raw !== "object")
78
+ return undefined;
79
+ const m = { marketplace: raw.marketplace === true, enabled: raw.enabled === true };
80
+ return m.marketplace || m.enabled ? m : undefined;
81
+ }
82
+ catch {
83
+ return undefined;
84
+ }
85
+ }
86
+ /** Claude Code's plugins folder: CLAUDE_CODE_PLUGIN_CACHE_DIR, else ~/.claude/plugins. */
87
+ export function claudePluginsRoot(env = process.env) {
88
+ return env.CLAUDE_CODE_PLUGIN_CACHE_DIR?.trim() || join(claudeDir(), "plugins");
89
+ }
90
+ function readObject(path) {
91
+ try {
92
+ const v = JSON.parse(readFileSync(path, "utf8"));
93
+ return v && typeof v === "object" && !Array.isArray(v) ? v : undefined;
94
+ }
95
+ catch {
96
+ return undefined;
97
+ }
98
+ }
99
+ /** Is a marketplace named context-doctor registered with Claude Code (from any source)? */
100
+ export function marketplaceRegistered() {
101
+ return Boolean(readObject(join(claudePluginsRoot(), "known_marketplaces.json"))?.[MARKETPLACE]);
102
+ }
103
+ /**
104
+ * How far Claude Code has got with the plugin: "installed" (downloaded, at
105
+ * `version`), "registered" (marketplace fetched, plugin not yet), or "none".
106
+ */
107
+ export function pluginStage() {
108
+ const installed = readObject(join(claudePluginsRoot(), "installed_plugins.json"))?.plugins;
109
+ if (installed && typeof installed === "object") {
110
+ for (const [key, list] of Object.entries(installed)) {
111
+ if (!isOurPluginKey(key))
112
+ continue;
113
+ const first = Array.isArray(list) ? list[0] : undefined;
114
+ return { stage: "installed", version: typeof first?.version === "string" ? first.version : undefined };
115
+ }
116
+ }
117
+ return { stage: marketplaceRegistered() ? "registered" : "none" };
118
+ }
119
+ /** When the mod last wrote each ledger (ms since epoch), from the files' modification times. */
120
+ export function modActivity() {
121
+ const at = (p) => {
122
+ try {
123
+ return existsSync(p) ? statSync(p).mtimeMs : undefined;
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ };
129
+ // modmeasure.ts costLogPath and limits.ts limitsLogPath, without loading the reports here.
130
+ const dir = dirname(statePath());
131
+ return { cost: at(join(dir, ".context-doctor-session-cost.jsonl")), limits: at(join(dir, ".context-doctor-limits.jsonl")) };
132
+ }
133
+ /** "3 h ago", "2 days ago". */
134
+ export function ago(ms, now = Date.now()) {
135
+ const min = Math.max(0, Math.round((now - ms) / 60_000));
136
+ if (min < 60)
137
+ return `${min} min ago`;
138
+ const h = Math.round(min / 60);
139
+ if (h < 48)
140
+ return `${h} h ago`;
141
+ return `${Math.round(h / 24)} days ago`;
142
+ }
package/dist/cli.js CHANGED
@@ -41,6 +41,7 @@ import { measureAccuracy, renderAccuracy } from "./accuracy.js";
41
41
  import { renderDiff } from "./diff.js";
42
42
  import { renderExperiment, runExperiment } from "./experiment.js";
43
43
  import { runStatusLine } from "./statusline.js";
44
+ import { runMod } from "./modmeasure.js";
44
45
  import { renderSubagents, subagentFiles, subagentReport } from "./subagents.js";
45
46
  import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
46
47
  import { runWatch } from "./watch.js";
@@ -67,7 +68,9 @@ import { currentTranscript, findSession, recall, renderRecall } from "./recall.j
67
68
  import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
68
69
  import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPrune } from "./prune.js";
69
70
  import { lensOverSessions, renderLens, sessionLens, LENS_ROWS } from "./lens.js";
70
- import { applyFix, fixOverrides, loadFixRecords, parseFixIds, planFixes, readFixRecords, renderFixPlan, renderFixShare, savedSince, undoFixes } from "./fix.js";
71
+ import { applyFix, fixOverrides, loadFixRecords, parseFixIds, planFixes, progressSummariesState, readFixRecords, renderFixPlan, renderFixShare, savedSince, undoFixes } from "./fix.js";
72
+ import { disablesSummaries, estimateProgressSummaries, PROGRESS_ROWS } from "./progresssummaries.js";
73
+ import { firstQuestion, renderFirstScreen, splitFirstFixes } from "./firstfix.js";
71
74
  import { claudeMcpConfigs, MCP_ROWS } from "./mcpschema.js";
72
75
  import { effectiveEnv, settingsSources, shellSet, underClaudeCode } from "./effective.js";
73
76
  import { SettingsError } from "./settingsedit.js";
@@ -115,15 +118,16 @@ Start here:
115
118
  What your recent Claude Code sessions cost, and what
116
119
  /compact at cold resumes, autopilot and an earlier
117
120
  auto-compact window would save, replayed and priced
118
- as billed. --share: totals only, to paste. Also
119
- what a bare \`context-doctor\` shows
121
+ as billed. --share: totals only, to paste
120
122
  context-doctor fix [--apply ids|all] [--share] What to change, ranked by dollars on your own
121
123
  sessions (compact earlier, the cache lifetime,
122
124
  autopilot, MCP tool search, unused servers, the
123
125
  subagents' model): each applied only on a yes
124
126
  (the subagents' model only by name, never by
125
127
  "all"), \`fix undo\` reverts them, later runs show
126
- what each saved since
128
+ what each saved since. A bare \`context-doctor\`
129
+ in a terminal shows the same plan on one screen
130
+ and asks once about the fixes with no quality cost
127
131
  context-doctor doctor Self-check the installation (configs, hook, skill,
128
132
  MCP handshake) with one pasteable diagnosis
129
133
  context-doctor uninstall Undo install
@@ -156,8 +160,8 @@ Measure:
156
160
  One bill across every tool here: Claude Code (with
157
161
  its subagents), Codex, Gemini CLI and Cursor (an
158
162
  estimate: no cache split), by project, model and
159
- day, and what drives it, at list prices. --share:
160
- totals only, to paste
163
+ day, and what drives it, as billed at list rates.
164
+ --share: totals only, to paste
161
165
  context-doctor cache-misses [--days n] Requests that re-wrote the prompt cache while it was
162
166
  still warm: priced, by model and context size, with
163
167
  the cause where the transcript shows one
@@ -261,6 +265,9 @@ Internal (Claude Code and MCP clients run these for you):
261
265
  context-doctor statusline Claude Code status bar line: live context size, cache
262
266
  share, cost (wired by \`install --statusline\`; reads
263
267
  the status JSON on stdin)
268
+ context-doctor mod measure|event Run by the plugin's mod after each turn (Desktop, VS Code,
269
+ terminal): limit readings, Claude Code's cost beside
270
+ ours, the band's figures (JSON on stdin and stdout)
264
271
  context-doctor mcp [--http] The MCP server (same as context-doctor-mcp), for clients
265
272
  that launch \`npx -y context-doctor mcp\`
266
273
 
@@ -273,11 +280,13 @@ Input: a conversation JSON file (OpenAI or Anthropic message format, or a bare
273
280
  message array). Use "-" to read from stdin.
274
281
 
275
282
  Options:
276
- --model <name> Model name for window-size math (e.g. claude-sonnet-5, gpt-4o)
283
+ --model <name> (analyze, session, cursor, diff, watch, pack, cache-plan, ci, ab,
284
+ experiment) Model to count and price for (e.g. claude-sonnet-5, gpt-4o)
277
285
  --exact (analyze) Add an exact token count: Anthropic count-tokens API for
278
286
  Claude models (needs ANTHROPIC_API_KEY), tiktoken for GPT (if installed)
279
- --redact Mask message previews and file paths in the report, so it can be
280
- shared in a bug report without leaking conversation content
287
+ --redact (analyze, session, cursor) Mask message previews and file paths in
288
+ the report, so it can be shared in a bug report without leaking
289
+ conversation content
281
290
  --json ${optionText(`(${JSON_COMMANDS.join(", ")}) Machine-readable output on stdout`)}
282
291
  --fail-over-budget (analyze/session) Exit 1 when the .contextdoctorrc budget is
283
292
  exceeded — lets CI gate a pull request on context size
@@ -378,7 +387,7 @@ async function measureFixInputs(days) {
378
387
  // Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
379
388
  prescan([
380
389
  { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS, TOOL_OUTPUT_ROWS] },
381
- { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS] },
390
+ { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS, PROGRESS_ROWS] },
382
391
  ...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
383
392
  { paths: codexRollouts(Date.now() - days * 86_400_000), extractors: [CODEX_COMPACT_ROWS] },
384
393
  ], replaying.tick);
@@ -428,6 +437,10 @@ async function measureFixInputs(days) {
428
437
  : shellSet(BASH_OUTPUT_ENV, sources, process.env)
429
438
  ? { name: BASH_OUTPUT_ENV, value: process.env[BASH_OUTPUT_ENV], where: underClaudeCode() ? "this Claude Code session's environment" : "the environment" }
430
439
  : undefined;
440
+ // The subagents' progress summaries: estimated from their transcripts; a value of the variable the user set is theirs.
441
+ const psState = progressSummariesState({ cwd });
442
+ const psSince = Date.now() - days * 86_400_000;
443
+ const progressSummaries = estimateProgressSummaries(subagentTranscripts(psSince), { since: psSince, forkGateOff: psState.forkGateOff, offSince: psState.offSince });
431
444
  // Codex's auto-compact limit: its rollouts replayed at earlier limits; a limit the user set is theirs.
432
445
  const codexCompact = replayCodexCompact({ days });
433
446
  const cxSet = currentCodexCompact();
@@ -455,7 +468,7 @@ async function measureFixInputs(days) {
455
468
  recordProblem = e.message;
456
469
  }
457
470
  const sessions = report.sessions.length;
458
- const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact"];
471
+ const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact", "progress-summaries"];
459
472
  return {
460
473
  prunePlan,
461
474
  inputs: {
@@ -472,6 +485,8 @@ async function measureFixInputs(days) {
472
485
  subagentModelSet,
473
486
  toolOutput,
474
487
  toolOutputSet,
488
+ progressSummaries,
489
+ ...(psState.set ? { progressSummariesSet: psState.set } : {}),
475
490
  ...(codexCompact.requests > 0 ? { codexCompact } : {}),
476
491
  ...(cxSet ? { codexCompactSet: { raw: cxSet.raw, where: cxSet.where } } : {}),
477
492
  overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
@@ -495,7 +510,7 @@ const COMMANDS = [
495
510
  "analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
496
511
  "instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
497
512
  "experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "cache-ttl", "fix", "limits", "subagents", "tasks",
498
- "spend", "budget", "reads", "pack", "watch", "ab", "handoff", "recall", "help", "version",
513
+ "spend", "budget", "reads", "pack", "watch", "ab", "handoff", "recall", "mod", "help", "version",
499
514
  ];
500
515
  /** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
501
516
  function strategyArg(v) {
@@ -658,6 +673,18 @@ function applyBudgetGate(overBudget, failOverBudget) {
658
673
  function readInput(file) {
659
674
  return stripBom(readFileSync(file === "-" ? 0 : file, "utf8"));
660
675
  }
676
+ /** Write --out's file, or say why not and exit 1 (a folder that does not exist ended in a stack trace). */
677
+ function writeOut(path, text) {
678
+ try {
679
+ writeFileSync(path, text);
680
+ }
681
+ catch (e) {
682
+ const code = e.code;
683
+ const why = code === "ENOENT" ? "its folder does not exist" : code === "EACCES" || code === "EPERM" ? "permission denied" : code === "EISDIR" ? "it is a folder" : e.message;
684
+ console.error(`context-doctor: could not write ${path}: ${why}`);
685
+ process.exit(1);
686
+ }
687
+ }
661
688
  /**
662
689
  * A UTF-8 byte-order mark (Windows editors, PowerShell's Out-File) is not
663
690
  * part of the text: left in, JSON.parse rejects the file and a valid
@@ -720,6 +747,35 @@ function hasClaudeSessions() {
720
747
  return false;
721
748
  }
722
749
  }
750
+ /**
751
+ * Apply the chosen fixes through applyFix, in the order given: `fix`'s
752
+ * answers and `--apply`, and a bare `context-doctor`'s one question, write
753
+ * the same settings and the same records.
754
+ */
755
+ async function applyChosenFixes(chosen, fixes, inputs, prunePlan, port) {
756
+ const results = [];
757
+ for (const id of chosen) {
758
+ const f = fixes.find((x) => x.id === id);
759
+ if (!f || f.state !== "available") {
760
+ results.push({ id, ok: false, lines: [`${id}: ${f?.note ?? "not available here"}; skipped.`] });
761
+ continue;
762
+ }
763
+ const kind = id === "cache-ttl" ? "main" : id === "cache-ttl-subagents" ? "subagents" : undefined;
764
+ const r = await applyFix(f, { autopilotOn: () => autopilotOn(port ?? DEFAULT_AUTOPILOT_PORT) }, { oneHourShare: kind ? inputs.ttl?.[kind].oneHourShare : undefined, prune: prunePlan, modelsBefore: inputs.subagentModel ? shares(inputs.subagentModel.before) : undefined });
765
+ results.push({ id, ...r });
766
+ }
767
+ return results;
768
+ }
769
+ /** What each applied fix wrote, and where to undo it. */
770
+ function printApplied(results) {
771
+ if (!results.length)
772
+ return;
773
+ console.log("");
774
+ for (const r of results)
775
+ console.log(r.lines.join("\n"));
776
+ if (results.some((r) => r.ok))
777
+ console.log(`\nNew ${results.every((r) => !r.ok || r.id === "codex-compact") ? "Codex" : results.some((r) => r.ok && r.id === "codex-compact") ? "Claude Code and Codex" : "Claude Code"} sessions pick these up. Undo: ${selfCommand("fix undo")}; ${selfCommand("fix")} later shows what each saved since.`);
778
+ }
723
779
  async function main() {
724
780
  const args = parseArgs(process.argv.slice(2));
725
781
  if (args.command && !COMMANDS.includes(args.command)) {
@@ -796,6 +852,16 @@ async function main() {
796
852
  void runStatusLine();
797
853
  return;
798
854
  }
855
+ if (args.command === "mod") {
856
+ if (args.file !== "measure" && args.file !== "event")
857
+ usageError(`Usage: context-doctor mod measure|event (the plugin's mod runs these, with JSON on stdin); got "${args.file ?? ""}".`);
858
+ if (process.stdin.isTTY) {
859
+ console.log("context-doctor mod is run by the plugin's mod in Claude Code with JSON on stdin; there is nothing for it to do in a terminal.");
860
+ return;
861
+ }
862
+ await runMod(args.file);
863
+ return;
864
+ }
799
865
  if (args.command === "ab") {
800
866
  process.exitCode = await abCommand({
801
867
  levers: args.levers, tasks: args.abTasks, model: args.model, repeat: args.repeat, maxTurns: args.maxTurns,
@@ -991,10 +1057,46 @@ async function main() {
991
1057
  process.exitCode = 1;
992
1058
  return;
993
1059
  }
994
- if (args.command === "savings" || (!args.command && process.stdout.isTTY && hasClaudeSessions())) {
1060
+ if (!args.command && !args.json && !args.share && process.stdout.isTTY && hasClaudeSessions()) {
995
1061
  // A bare `context-doctor` in a terminal, with Claude Code history on the
996
- // machine, answers the question people install this for: what would it
997
- // save me? Scripts and pipes still get the help text.
1062
+ // machine: fix's plan (one scan), the quality-free fixes under one y/N
1063
+ // question, the others with their dollars and the command for each.
1064
+ // Asked only when stdin is a terminal too; scripts and pipes still get
1065
+ // the Start here screen, and `--json`/`--share` the savings report.
1066
+ const { inputs, prunePlan } = await measureFixInputs(args.days ?? 30);
1067
+ const fixes = planFixes(inputs);
1068
+ const { free } = splitFirstFixes(fixes);
1069
+ const ask = !!process.stdin.isTTY && free.length > 0 && !inputs.recordProblem;
1070
+ console.log(renderFirstScreen({ days: inputs.days, billedUsd: inputs.billedUsd, codexBilledUsd: inputs.codexCompact?.billedUsd, fixes, command: selfCommand, recordProblem: inputs.recordProblem, ask }));
1071
+ if (!ask)
1072
+ return;
1073
+ const rl = (await import("node:readline/promises")).createInterface({ input: process.stdin, output: process.stdout });
1074
+ // Ctrl-D or a closed terminal is a no, never a wait. A Ctrl-D typed during
1075
+ // the scan, while the terminal was still line-buffered, reaches readline's
1076
+ // raw mode as \x04 on macOS but as a NUL on Linux (the tty keeps a pending
1077
+ // end-of-file as \0), which readline ignores: on an empty line it is a no too.
1078
+ const typedAheadEof = (s) => { if (s === "\0" && rl.line === "")
1079
+ rl.close(); };
1080
+ process.stdin.on("keypress", typedAheadEof);
1081
+ const answer = await new Promise((resolve) => {
1082
+ rl.once("close", () => resolve(""));
1083
+ rl.question(firstQuestion(free.length, selfCommand)).then(resolve, () => resolve(""));
1084
+ });
1085
+ process.stdin.off("keypress", typedAheadEof);
1086
+ rl.close();
1087
+ if (!/^(y|yes)$/i.test(answer.trim())) {
1088
+ console.log(`Nothing changed. ${selfCommand("fix")} asks about each lever, the ones above included.`);
1089
+ return;
1090
+ }
1091
+ const results = await applyChosenFixes(free.map((f) => f.id), fixes, inputs, prunePlan, args.port);
1092
+ if (results.some((r) => !r.ok))
1093
+ process.exitCode = 1;
1094
+ printApplied(results);
1095
+ return;
1096
+ }
1097
+ if (args.command === "savings" || (!args.command && process.stdout.isTTY && hasClaudeSessions())) {
1098
+ // `savings`, and a bare `context-doctor --json` or `--share` in a terminal
1099
+ // with Claude Code history (what a bare run printed before the one-question screen).
998
1100
  const replaying = progressLine("Replaying your Claude Code sessions through autopilot");
999
1101
  // Each transcript read once for every report below; what an earlier run kept is not read again (scan.ts).
1000
1102
  prescan([
@@ -1041,8 +1143,6 @@ async function main() {
1041
1143
  else {
1042
1144
  console.log(renderSavings(report, on, cwLine, cacheMissesSignificant(misses) ? cacheMissesLine(misses) : undefined, limitLines, renderLens(lens)));
1043
1145
  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).`);
1044
- if (!args.command)
1045
- console.log(`All commands: ${selfCommand("--help")}`);
1046
1146
  }
1047
1147
  return;
1048
1148
  }
@@ -1290,35 +1390,20 @@ async function main() {
1290
1390
  }
1291
1391
  rl.close();
1292
1392
  }
1293
- const results = [];
1294
- for (const id of chosen) {
1295
- const f = fixes.find((x) => x.id === id);
1296
- if (!f || f.state !== "available") {
1297
- results.push({ id, ok: false, lines: [`${id}: ${f?.note ?? "not available here"}; skipped.`] });
1298
- continue;
1299
- }
1300
- const kind = id === "cache-ttl" ? "main" : id === "cache-ttl-subagents" ? "subagents" : undefined;
1301
- const r = await applyFix(f, { autopilotOn: () => autopilotOn(args.port ?? DEFAULT_AUTOPILOT_PORT) }, { oneHourShare: kind ? inputs.ttl?.[kind].oneHourShare : undefined, prune: prunePlan, modelsBefore: inputs.subagentModel ? shares(inputs.subagentModel.before) : undefined });
1302
- results.push({ id, ...r });
1303
- }
1393
+ const results = await applyChosenFixes(chosen, fixes, inputs, prunePlan, args.port);
1304
1394
  // Naming fixes that are not there (or nothing at all, with "all") is not a silent success.
1305
1395
  if (args.apply !== undefined && (chosen.length === 0 || results.some((r) => !r.ok)))
1306
1396
  process.exitCode = 1;
1307
1397
  if (args.json) {
1308
- console.log(JSON.stringify({ days: inputs.days, billedUsd: inputs.billedUsd, ...(inputs.codexCompact ? { codexBilledUsd: inputs.codexCompact.billedUsd } : {}), fixes, since, ...(args.apply !== undefined ? { applied: results } : {}), ...(inputs.recordProblem ? { recordProblem: inputs.recordProblem } : {}) }, null, 2));
1398
+ // qualityFree is the bare screen's grouping, not part of fix's JSON.
1399
+ console.log(JSON.stringify({ days: inputs.days, billedUsd: inputs.billedUsd, ...(inputs.codexCompact ? { codexBilledUsd: inputs.codexCompact.billedUsd } : {}), fixes: fixes.map(({ qualityFree: _q, ...f }) => f), since, ...(args.apply !== undefined ? { applied: results } : {}), ...(inputs.recordProblem ? { recordProblem: inputs.recordProblem } : {}) }, null, 2));
1309
1400
  if (args.apply !== undefined && chosen.length === 0)
1310
1401
  console.error("--apply: no fix available to apply.");
1311
1402
  return;
1312
1403
  }
1313
1404
  if (args.apply !== undefined && chosen.length === 0)
1314
1405
  console.error("\n--apply: no fix available to apply.");
1315
- if (!results.length)
1316
- return;
1317
- console.log("");
1318
- for (const r of results)
1319
- console.log(r.lines.join("\n"));
1320
- if (results.some((r) => r.ok))
1321
- console.log(`\nNew ${results.every((r) => !r.ok || r.id === "codex-compact") ? "Codex" : results.some((r) => r.ok && r.id === "codex-compact") ? "Claude Code and Codex" : "Claude Code"} sessions pick these up. Undo: ${selfCommand("fix undo")}; ${selfCommand("fix")} later shows what each saved since.`);
1406
+ printApplied(results);
1322
1407
  return;
1323
1408
  }
1324
1409
  if (args.command === "cache-ttl") {
@@ -1405,7 +1490,9 @@ async function main() {
1405
1490
  if (args.share && args.json)
1406
1491
  usageError("--share and --json do not go together: --share prints a few lines to paste.");
1407
1492
  const reading = progressLine("Reading your usage across tools");
1408
- const report = spendReport(args.days ?? 30, { onProgress: reading.tick });
1493
+ // The progress summaries' estimate: none after the variable turned them off (fix's record), none at all when set with no record.
1494
+ const ps = progressSummariesState({ cwd: process.cwd() });
1495
+ const report = spendReport(args.days ?? 30, { onProgress: reading.tick, progress: { forkGateOff: ps.forkGateOff, offSince: ps.offSince, ...(ps.set && disablesSummaries(ps.set.value) ? { set: ps.set.where } : {}) } });
1409
1496
  reading.clear();
1410
1497
  if (args.json)
1411
1498
  console.log(JSON.stringify(report, null, 2));
@@ -1485,7 +1572,7 @@ async function main() {
1485
1572
  }
1486
1573
  console.log(args.json ? JSON.stringify(result.plan, null, 2) : renderCachePlan(result.plan));
1487
1574
  if (args.out) {
1488
- writeFileSync(args.out, JSON.stringify(result.apply(), null, 2));
1575
+ writeOut(args.out, JSON.stringify(result.apply(), null, 2));
1489
1576
  console.error(result.plan.plan.length
1490
1577
  ? `context-doctor: request with the planned breakpoints written to ${args.out}`
1491
1578
  : `context-doctor: nothing to place; the request was written unchanged to ${args.out}`);
@@ -1699,7 +1786,7 @@ async function main() {
1699
1786
  }
1700
1787
  const output = JSON.stringify(result.conversation, null, 2);
1701
1788
  if (args.out) {
1702
- writeFileSync(args.out, output);
1789
+ writeOut(args.out, output);
1703
1790
  }
1704
1791
  else if (args.json) {
1705
1792
  console.log(JSON.stringify(result, null, 2));
@@ -77,8 +77,12 @@ export declare function idleCompactMinTokens(env?: NodeJS.ProcessEnv): number;
77
77
  export declare function autoCompactsAt(model: string | undefined, home?: string, env?: NodeJS.ProcessEnv): number | undefined;
78
78
  /** Just past Claude Code's one-hour cache, as Claude Code's own idle clearing uses. */
79
79
  export declare const COLD_IDLE_MS: number;
80
+ /** Margin past a cache's lifetime before a return counts as cold. */
81
+ export declare const COLD_MARGIN_MS: number;
80
82
  /** Below this, a rebuilt cache is cheap and compaction is not worth the interruption. */
81
83
  export declare const COLD_MIN_TOKENS = 150000;
84
+ /** What a compacted session restarts from: system prompt and tools plus the summary. */
85
+ export declare const AFTER_COMPACT_TOKENS = 45000;
82
86
  export interface ColdResume {
83
87
  idleMs: number;
84
88
  /** Context size at the last request, from the API's own usage. */
@@ -92,6 +96,8 @@ export interface ColdResume {
92
96
  perMessageUsd?: number;
93
97
  /** `resumeUsd` is Claude Code's own estimate (SessionStart), which honours a managed modelPricing. */
94
98
  claudeCodePriced?: boolean;
99
+ /** How long the cache the last reply left behind lives, as the gate counted it. */
100
+ ttlMs?: number;
95
101
  }
96
102
  /**
97
103
  * What Claude Code's SessionStart hook says on a resume (2.1.29x):
@@ -30,7 +30,7 @@ import { homedir } from "node:os";
30
30
  import { join } from "node:path";
31
31
  import { forEachLine, replyCounter, textOf } from "./session.js";
32
32
  import { pick, rowsOf, slimUsage } from "./scan.js";
33
- import { cacheWriteSplit, formatUsd, rateCard, ratesAt, writeMultiplier } from "./pricing.js";
33
+ import { cacheWriteSplit, formatUsd, rateCard, ratesAt, writeMultiplier, writePerM } from "./pricing.js";
34
34
  import { contextWindowFor, formatTokens, isCodeLike, realModel } from "./tokens.js";
35
35
  import { claudeDir } from "./claudedir.js";
36
36
  /**
@@ -145,7 +145,7 @@ export function autoCompactsAt(model, home = homedir(), env = process.env) {
145
145
  /** Just past Claude Code's one-hour cache, as Claude Code's own idle clearing uses. */
146
146
  export const COLD_IDLE_MS = 65 * 60_000;
147
147
  /** Margin past a cache's lifetime before a return counts as cold. */
148
- const COLD_MARGIN_MS = 5 * 60_000;
148
+ export const COLD_MARGIN_MS = 5 * 60_000;
149
149
  const HOUR_MS = 3_600_000;
150
150
  const FIVE_MIN_MS = 5 * 60_000;
151
151
  /**
@@ -173,7 +173,7 @@ function writtenTtlMs(u) {
173
173
  /** Below this, a rebuilt cache is cheap and compaction is not worth the interruption. */
174
174
  export const COLD_MIN_TOKENS = 150_000;
175
175
  /** What a compacted session restarts from: system prompt and tools plus the summary. */
176
- const AFTER_COMPACT_TOKENS = 45_000;
176
+ export const AFTER_COMPACT_TOKENS = 45_000;
177
177
  /** Output tokens a compaction summary costs, at the model's output price. */
178
178
  const SUMMARY_OUTPUT_TOKENS = 8_000;
179
179
  export function resumeVerdict(input, now = Date.now()) {
@@ -273,8 +273,9 @@ export function detectColdResume(path, now = Date.now(), idleMs, minTokens = COL
273
273
  tokens,
274
274
  model,
275
275
  lastReplyAt,
276
- resumeUsd: p ? (tokens * sessionWriteMultiplier(path) * p.inputPerM) / 1e6 : undefined,
276
+ resumeUsd: p ? (tokens * writePerM(p, sessionWriteMultiplier(path))) / 1e6 : undefined,
277
277
  perMessageUsd: p ? (tokens * p.cacheReadPerM) / 1e6 : undefined,
278
+ ttlMs: ttl ?? HOUR_MS,
278
279
  };
279
280
  }
280
281
  }
@@ -423,7 +424,7 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
423
424
  break;
424
425
  const card = c.card ?? b.card;
425
426
  const cold = c.at - prev.at > prev.ttl;
426
- const per = (p) => (cold ? mix * p.inputPerM : p.cacheReadPerM);
427
+ const per = (p) => (cold ? writePerM(p, mix) : p.cacheReadPerM);
427
428
  // A long-prompt tier: the smaller prompt may bill all of it at the lower rates.
428
429
  const after = Math.max(0, c.total - removed);
429
430
  const hi = ratesAt(card, c.total), lo = ratesAt(card, after);
@@ -433,7 +434,7 @@ export function coldResumeEvents(path, idleMs, minTokens = COLD_MIN_TOKENS, runR
433
434
  }
434
435
  // The compaction re-reads the context just rebuilt and writes a summary;
435
436
  // the next request writes the fresh context.
436
- const cost = b.total * price.cacheReadPerM + SUMMARY_OUTPUT_TOKENS * price.outputPerM + mix * AFTER_COMPACT_TOKENS * ratesAt(b.card, AFTER_COMPACT_TOKENS).inputPerM;
437
+ const cost = b.total * price.cacheReadPerM + SUMMARY_OUTPUT_TOKENS * price.outputPerM + AFTER_COMPACT_TOKENS * writePerM(ratesAt(b.card, AFTER_COMPACT_TOKENS), mix);
437
438
  events.push({ at: b.at, tokens: b.total, messagesAfter: n, netUsd: (saved - cost) / 1e6 });
438
439
  }
439
440
  return events;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * A compaction's own request, estimated: the one request of a session that no
3
+ * transcript row carries usage for.
4
+ *
5
+ * Compacting sends the whole conversation once more with an instruction to
6
+ * summarize it, and the answer is the summary the session restarts from.
7
+ * Claude Code bills it and counts it in its own cost (the mods API says the
8
+ * session's cost ledger holds it), but writes only a `compact_boundary` row
9
+ * (`compactMetadata.preTokens`: the context it read) and the summary as a user
10
+ * row (`isCompactSummary`): no usage (2.1.321). So `spend`, the budget and a
11
+ * session's price left every compaction out, and the mod's comparison with
12
+ * Claude Code's own cost showed the gap.
13
+ *
14
+ * Estimated from what the transcript does record, at the model of the reply
15
+ * before it (rateCard, as every request: the organization's rates, the day's
16
+ * price, its fast mode and US-only):
17
+ * - the context it read, `preTokens`: at the cache-read rate when the cache
18
+ * the last reply left was still alive (an automatic compaction mid-turn,
19
+ * Claude Code's idle compaction before expiry), else written again at the
20
+ * session's lifetime (a /compact after the cache went cold);
21
+ * - its output, the summary: the summary row's text, in tokens.
22
+ * Not counted: the request's own instruction (a few hundred tokens) and any
23
+ * thinking it did. The next request's re-write of the new context is in that
24
+ * request's own usage, as before.
25
+ */
26
+ import { type RecordedUsage, type RequestCost } from "./pricing.js";
27
+ /** The summary's output when no summary row follows the boundary: compactwindow.ts's measured figure. */
28
+ export declare const SUMMARY_TOKENS_UNSEEN = 20000;
29
+ /** Per thread ("0" the main conversation, "1" a sidechain): the last reply's model, time, cache lifetime and billing. */
30
+ interface Thread {
31
+ m?: string;
32
+ at?: number;
33
+ ttl?: number;
34
+ b?: Pick<RecordedUsage, "speed" | "inference_geo">;
35
+ }
36
+ /** What a reader keeps between rows (and, in the budget's ledger, between reads). */
37
+ export interface CompactTrack {
38
+ t: Record<string, Thread>;
39
+ /** A boundary met whose summary row has not been: its uuid, time, context, thread, session. */
40
+ p?: {
41
+ u?: string;
42
+ at: number;
43
+ pre: number;
44
+ th: string;
45
+ s?: string;
46
+ };
47
+ }
48
+ export declare const newTrack: () => CompactTrack;
49
+ /** A ledger's kept state, when it is one this version wrote. */
50
+ export declare function isTrack(v: unknown): v is CompactTrack;
51
+ /** One compaction's request, priced. */
52
+ export interface CompactionRequest {
53
+ uuid?: string;
54
+ sessionId?: string;
55
+ sidechain: boolean;
56
+ ts: number;
57
+ model: string;
58
+ usage: RecordedUsage;
59
+ cost: RequestCost;
60
+ /** The context it read from a live cache (false: written again). */
61
+ warm: boolean;
62
+ }
63
+ /** The rows a reader must hand on: replies with usage, compaction boundaries, summary rows. */
64
+ export declare function isCompactionRow(line: string): boolean;
65
+ /**
66
+ * Feed one parsed row; a compaction's request when this row completes one
67
+ * (its summary row, or a reply that came with no summary row between). A
68
+ * boundary still waiting for its summary at the end of what was read is kept
69
+ * in `st` and priced when the summary is read.
70
+ */
71
+ export declare function trackCompaction(st: CompactTrack, e: any): CompactionRequest | undefined;
72
+ /** A summary row as an extractor keeps it: its length, not its text. */
73
+ export declare function slimSummary(e: any): Record<string, unknown>;
74
+ export {};