context-doctor 0.47.0 → 0.49.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 (84) hide show
  1. package/README.md +17 -14
  2. package/dist/ab.d.ts +51 -3
  3. package/dist/ab.js +68 -26
  4. package/dist/abclaude.d.ts +167 -0
  5. package/dist/abclaude.js +511 -0
  6. package/dist/abstore.d.ts +46 -0
  7. package/dist/abstore.js +58 -0
  8. package/dist/budget.d.ts +5 -2
  9. package/dist/budget.js +21 -7
  10. package/dist/cache.js +3 -3
  11. package/dist/cachemisses.d.ts +3 -0
  12. package/dist/cachemisses.js +8 -0
  13. package/dist/cachettl.js +6 -2
  14. package/dist/ccost.d.ts +160 -0
  15. package/dist/ccost.js +304 -0
  16. package/dist/cli.js +154 -32
  17. package/dist/cline.d.ts +41 -0
  18. package/dist/cline.js +174 -0
  19. package/dist/coldresume.d.ts +11 -0
  20. package/dist/coldresume.js +3 -3
  21. package/dist/coldreturns.d.ts +145 -0
  22. package/dist/coldreturns.js +282 -0
  23. package/dist/compactcost.d.ts +10 -4
  24. package/dist/compactcost.js +12 -7
  25. package/dist/compactwindow.js +2 -2
  26. package/dist/copilotusage.d.ts +78 -0
  27. package/dist/copilotusage.js +193 -0
  28. package/dist/doctor.d.ts +6 -0
  29. package/dist/doctor.js +17 -4
  30. package/dist/fix.d.ts +35 -4
  31. package/dist/fix.js +55 -8
  32. package/dist/install.js +2 -0
  33. package/dist/limits.d.ts +222 -14
  34. package/dist/limits.js +684 -33
  35. package/dist/mcp.d.ts +4 -0
  36. package/dist/mcp.js +142 -98
  37. package/dist/mcpclient.js +73 -42
  38. package/dist/mcpdefer.d.ts +47 -0
  39. package/dist/mcpdefer.js +91 -0
  40. package/dist/mod/api.d.ts +72 -2
  41. package/dist/mod/api.js +5 -1
  42. package/dist/mod/logic.d.ts +281 -0
  43. package/dist/mod/logic.js +336 -0
  44. package/dist/mod/register.d.ts +35 -2
  45. package/dist/mod/register.js +283 -6
  46. package/dist/modelids.d.ts +58 -0
  47. package/dist/modelids.js +133 -1
  48. package/dist/modmeasure.d.ts +6 -4
  49. package/dist/modmeasure.js +8 -4
  50. package/dist/opencode.d.ts +57 -0
  51. package/dist/opencode.js +234 -0
  52. package/dist/orgrates.d.ts +7 -0
  53. package/dist/orgrates.js +19 -0
  54. package/dist/overhead.d.ts +3 -0
  55. package/dist/overhead.js +5 -1
  56. package/dist/pricing.d.ts +59 -2
  57. package/dist/pricing.js +139 -12
  58. package/dist/proxy.d.ts +8 -1
  59. package/dist/proxy.js +13 -1
  60. package/dist/savings.d.ts +5 -1
  61. package/dist/savings.js +11 -5
  62. package/dist/scan.d.ts +3 -1
  63. package/dist/scan.js +8 -1
  64. package/dist/sessionprice.d.ts +5 -0
  65. package/dist/sessionprice.js +5 -1
  66. package/dist/spend.d.ts +86 -3
  67. package/dist/spend.js +240 -23
  68. package/dist/spendplace.d.ts +40 -0
  69. package/dist/spendplace.js +93 -0
  70. package/dist/spendteam.d.ts +160 -0
  71. package/dist/spendteam.js +286 -0
  72. package/dist/starts.d.ts +106 -0
  73. package/dist/starts.js +406 -0
  74. package/dist/statusline.d.ts +2 -2
  75. package/dist/statusline.js +2 -2
  76. package/dist/subagentmodel.js +9 -7
  77. package/dist/subagentpay.d.ts +31 -2
  78. package/dist/subagentpay.js +232 -68
  79. package/dist/subagents.js +3 -3
  80. package/dist/tasks.js +3 -2
  81. package/dist/tooloutput.js +5 -5
  82. package/dist/usagepane.d.ts +77 -0
  83. package/dist/usagepane.js +287 -0
  84. package/package.json +6 -3
package/dist/cli.js CHANGED
@@ -23,12 +23,14 @@ import { claudeCodeInstallsFromEnv, claudePluginEnabled, runInstall, runUninstal
23
23
  import { listSessions, parseSessionFile, pickCurrentSession, isClaudeSession } from "./session.js";
24
24
  import { runHook } from "./hook.js";
25
25
  import { abCommand } from "./ab.js";
26
+ import { latestModelComparison } from "./abstore.js";
26
27
  import { buildImpactReport } from "./impact.js";
27
28
  import { measureTokenizer, renderTokenizer } from "./tokenizer-measure.js";
28
29
  import { autopilotOff, autopilotOn, autopilotPauseResult, autopilotPaths, autopilotStatus, DEFAULT_AUTOPILOT_PORT } from "./autopilot.js";
29
30
  import { estimateSavings, renderSavings, renderShare, savingsRows } from "./savings.js";
30
31
  import { prescan } from "./scan.js";
31
32
  import { REQUEST_ROWS } from "./coldresume.js";
33
+ import { coldReturns } from "./coldreturns.js";
32
34
  import { replaySubagentModels, shares, SUBAGENT_MODEL_ENV, SUBAGENT_MODEL_FORCE_ENV, SUBAGENT_ROWS } from "./subagentmodel.js";
33
35
  import { BASH_OUTPUT_ENV, BASH_OUTPUT_KEY, replayToolOutput, TOOL_OUTPUT_ROWS } from "./tooloutput.js";
34
36
  import { CODEX_COMPACT_ROWS, codexRollouts, currentCodexCompact, replayCodexCompact } from "./codexcompact.js";
@@ -54,6 +56,7 @@ import { analyzeCacheUsage, renderCacheReport } from "./cache.js";
54
56
  import { renderToolTimings } from "./timing.js";
55
57
  import { packContextSemantic, readSources, renderPack } from "./pack.js";
56
58
  import { measureBaselines, measureMcpSizes, overheadReport, renderOverhead } from "./overhead.js";
59
+ import { deferrableConfigured, measureStarts, START_ROWS } from "./starts.js";
57
60
  import { applySplit, planSplit, renderSplit } from "./split.js";
58
61
  import { ciReport, renderCiMarkdown, renderCiText } from "./ci.js";
59
62
  import { renderReads, repeatedReads } from "./reads.js";
@@ -63,7 +66,7 @@ import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses
63
66
  import { renderPayback, subagentPayback, SUBAGENT_CANDIDATE } from "./subagentpay.js";
64
67
  import { compactionQuality, renderCompactionQuality, QUALITY_ROWS } from "./compactquality.js";
65
68
  import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
66
- import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits } from "./limits.js";
69
+ import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits, renderLimitsReport } from "./limits.js";
67
70
  import { currentTranscript, findSession, recall, renderRecall } from "./recall.js";
68
71
  import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
69
72
  import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPrune } from "./prune.js";
@@ -76,7 +79,10 @@ import { effectiveEnv, settingsSources, shellSet, underClaudeCode } from "./effe
76
79
  import { SettingsError } from "./settingsedit.js";
77
80
  import { currentTtl, estimateCacheTtl, renderCacheTtl, setCacheTtl, settingKey, subagentTranscripts, ttlUnsupported, CACHE_TTL_SINCE } from "./cachettl.js";
78
81
  import { claudeDir } from "./claudedir.js";
79
- import { renderSpend, renderSpendShare, spendReport } from "./spend.js";
82
+ import { claudeCodeSession, collectSpend, renderSpend, renderSpendShare, sessionPriceEnded, spendBasis, spendReport } from "./spend.js";
83
+ import { buildExport, defaultDeveloper, exportFileName, mergeExports, readExports, renderExportDone, renderMerge } from "./spendteam.js";
84
+ import { renderSessionComparison } from "./ccost.js";
85
+ import { withOrgRatesHeld } from "./orgrates.js";
80
86
  import { clearBudget, parseBudget, periodSpend, promptHookInstalled, readBudget, renderBudgetStatus, writeBudget } from "./budget.js";
81
87
  /**
82
88
  * The commands that print JSON with --json. Any other command refuses the
@@ -151,17 +157,28 @@ Measure:
151
157
  cost, and whether a CLAUDE.md summary or pack pays
152
158
  context-doctor compactions [--days n] Do sessions work worse right after compacting? Re-reads,
153
159
  tool errors and your corrections, before vs after
154
- context-doctor limits [--days n] Your plan's limits in their own unit: the 5-hour and
155
- weekly windows (Claude Pro/Max, via the status line)
156
- and Codex's, the pace, when each runs out, and what
157
- 1M tokens of each kind cost in %, fitted on your own
158
- readings with the fit's error
159
- context-doctor spend [--days n] [--share [--copy]]
160
+ context-doctor limits [--days n] [--report [--copy]]
161
+ Your plan's limits in their own unit: the weekly and
162
+ 5-hour windows (Claude Pro, Max and Ultra; Ultra has
163
+ no 5-hour window; recorded by the plugin's mod, the
164
+ status line or the proxy) and Codex's, the pace, when
165
+ each runs out, $ and tokens per 1% of each weekly
166
+ window, by entrypoint and model, and when that moved.
167
+ --report: a block to paste into a bug report
168
+ context-doctor spend [--days n] [--by repo|branch] [--share [--copy]]
160
169
  One bill across every tool here: Claude Code (with
161
- its subagents), Codex, Gemini CLI and Cursor (an
162
- estimate: no cache split), by project, model and
163
- day, and what drives it, as billed at list rates.
164
- --share: totals only, to paste
170
+ its subagents), Codex, Gemini CLI, Cursor (an
171
+ estimate: no cache split), Copilot CLI, OpenCode
172
+ and Cline, by project (or --by repository or
173
+ branch), model and day, and what drives it, as
174
+ billed at list rates. --share: totals only, to paste
175
+ context-doctor spend --export [file] [--as <name>] [--anonymize] [--by branch]
176
+ A file of totals for your team (by day, tool, model,
177
+ repository; no prompt, path or project); --as: your
178
+ name in it (default: your OS user name)
179
+ context-doctor spend merge <folder> Add up the exports people put in a shared folder:
180
+ by developer, repository and tool, with a month-end
181
+ forecast
165
182
  context-doctor cache-misses [--days n] Requests that re-wrote the prompt cache while it was
166
183
  still warm: priced, by model and context size, with
167
184
  the cause where the transcript shows one
@@ -184,6 +201,13 @@ Measure:
184
201
  side. Bills ANTHROPIC_API_KEY: prints the estimate,
185
202
  sends nothing without --yes, never passes --budget usd.
186
203
  --list shows the tasks; --model (default claude-opus-5-5)
204
+ context-doctor ab --via claude-code [--model m] [--compare m2] [--repeat n] [--yes]
205
+ The same tasks through your own Claude Code (claude -p,
206
+ your sign-in: on a plan, its limits, not dollars), one
207
+ arm per model: --model (default claude-sonnet-5-5) vs
208
+ --compare (default claude-opus-5-5). Each run confined
209
+ to a temp copy under Claude Code's sandbox; --timeout s
210
+ per run (default 600). fix quotes the result
187
211
 
188
212
  Fix automatically:
189
213
  context-doctor autopilot on|off|pause|resume|status
@@ -265,9 +289,10 @@ Internal (Claude Code and MCP clients run these for you):
265
289
  context-doctor statusline Claude Code status bar line: live context size, cache
266
290
  share, cost (wired by \`install --statusline\`; reads
267
291
  the status JSON on stdin)
268
- context-doctor mod measure|event Run by the plugin's mod after each turn (Desktop, VS Code,
292
+ context-doctor mod measure|event|usage Run by the plugin's mod after each turn (Desktop, VS Code,
269
293
  terminal): limit readings, Claude Code's cost beside
270
- ours, the band's figures (JSON on stdin and stdout)
294
+ ours, the band's and the usage pane's figures (JSON on
295
+ stdin and stdout)
271
296
  context-doctor mcp [--http] The MCP server (same as context-doctor-mcp), for clients
272
297
  that launch \`npx -y context-doctor mcp\`
273
298
 
@@ -319,6 +344,11 @@ Options:
319
344
  --check <cmd> (experiment) Command whose exit code is the pass/fail for each arm
320
345
  --existing <id> (experiment) Session id to fork the second arm from (never mutated)
321
346
  --budget <usd> (experiment) Spend cap per arm (default 1)
347
+ --via <api|claude-code> (ab) The Messages API on ANTHROPIC_API_KEY (default), or claude -p on
348
+ your own Claude Code sign-in, one arm per model
349
+ --compare <model> (ab --via claude-code) Model(s) to run against --model (default
350
+ claude-opus-5-5; "none" for --model alone)
351
+ --timeout <s> (ab --via claude-code) Seconds before a run is killed (default 600)
322
352
  --dry-run (experiment) Print the claude commands and stop
323
353
  --allow-dirty (experiment) Skip the clean-tree check (uncommitted changes will be lost)
324
354
  --statusline (install) Also set Claude Code's statusLine to context-doctor (never
@@ -364,7 +394,7 @@ Start here
364
394
  context-doctor fix what to change, ranked by what it saves you; applied only on a yes
365
395
  context-doctor install wire the MCP server, skill and hooks into the apps it finds
366
396
  context-doctor savings what your recent sessions cost, and what each fix would save
367
- context-doctor spend one bill across Claude Code, Codex, Gemini CLI and Cursor
397
+ context-doctor spend one bill across Claude Code, Codex, Gemini CLI, Cursor and more
368
398
  context-doctor doctor check the installation
369
399
 
370
400
  All commands: context-doctor --help
@@ -384,10 +414,12 @@ async function measureFixInputs(days) {
384
414
  // With autopilot already on, its replay (most of the time) answers nothing `fix` asks.
385
415
  const replaying = progressLine(autopilotOnNow ? "Reading your Claude Code sessions" : "Replaying your Claude Code sessions");
386
416
  const setWindow = currentCompactWindow();
417
+ // The starts are measured only when a server of the user's own could have gone whole into them (mcp-defer).
418
+ const configured = claudeMcpConfigs(cwd).some((c) => c.scope !== ".mcp.json");
387
419
  // Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
388
420
  prescan([
389
- { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS, TOOL_OUTPUT_ROWS] },
390
- { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS, PROGRESS_ROWS] },
421
+ { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS, TOOL_OUTPUT_ROWS, ...(configured ? [START_ROWS] : [])] },
422
+ { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS, PROGRESS_ROWS, ...(configured ? [START_ROWS] : [])] },
391
423
  ...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
392
424
  { paths: codexRollouts(Date.now() - days * 86_400_000), extractors: [CODEX_COMPACT_ROWS] },
393
425
  ], replaying.tick);
@@ -444,6 +476,9 @@ async function measureFixInputs(days) {
444
476
  // Codex's auto-compact limit: its rollouts replayed at earlier limits; a limit the user set is theirs.
445
477
  const codexCompact = replayCodexCompact({ days });
446
478
  const cxSet = currentCodexCompact();
479
+ // Keeping the cache warm while away: the cap that nets most on the cold returns replayed.
480
+ const cold = coldReturns(days, claudeTranscripts(days));
481
+ const keepWarm = cold.best ? { hours: cold.best.hours, netUsd: cold.best.netUsd, pingUsd: cold.best.pingUsd, keptWarm: cold.best.keptWarm, returns: cold.returns } : undefined;
447
482
  const ts = effectiveEnv("ENABLE_TOOL_SEARCH", sources);
448
483
  const toolSearchOff = ts && /^(false|0|no|off)$/i.test(ts.value.trim()) ? ts.value : undefined;
449
484
  const servers = claudeMcpConfigs(cwd).filter((c) => !/context-doctor/i.test(c.name));
@@ -460,6 +495,7 @@ async function measureFixInputs(days) {
460
495
  userSettings = JSON.parse(readFileSync(join(claudeDir(), "settings.json"), "utf8")) ?? {};
461
496
  }
462
497
  catch { /* none */ }
498
+ const deferrable = configured ? deferrableConfigured(measureStarts({ days, cwd })) : [];
463
499
  let recordProblem;
464
500
  try {
465
501
  loadFixRecords();
@@ -481,8 +517,11 @@ async function measureFixInputs(days) {
481
517
  toolSearchOff,
482
518
  mcpServers: toolSearchOff ? servers.length : 0,
483
519
  prune: prunePlan,
520
+ ...(deferrable.length ? { mcpDefer: { servers: deferrable, days } } : {}),
484
521
  subagentModel,
485
522
  subagentModelSet,
523
+ // The newest ab --via claude-code comparison of Sonnet 5.5 with another model: the subagent-model line quotes it.
524
+ abComparison: latestModelComparison(),
486
525
  toolOutput,
487
526
  toolOutputSet,
488
527
  progressSummaries,
@@ -494,6 +533,7 @@ async function measureFixInputs(days) {
494
533
  // The installs a setting is too new for are named on its fix.
495
534
  claudeCodeInstalls: claudeCodeInstallsFromEnv(),
496
535
  coldResume: { netUsd: Math.max(0, report.coldResumeNetUsd), returns: report.coldResumes, hooked: claudePluginEnabled() || /context-doctor|cli\.js"?\s+hook/.test(JSON.stringify(userSettings.hooks?.UserPromptSubmit ?? [])) },
536
+ ...(keepWarm ? { keepWarm } : {}),
497
537
  },
498
538
  };
499
539
  }
@@ -541,10 +581,18 @@ const FLAGS = [
541
581
  { names: ["--repeat"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.repeat = v; } },
542
582
  { names: ["--max-turns"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.maxTurns = v; } },
543
583
  { names: ["--concurrency"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.concurrency = v; } },
584
+ { names: ["--via"], value: "text", set: (a, v) => { a.via = v; } },
585
+ { names: ["--compare"], value: "text", set: (a, v) => { (a.compare ??= []).push(v); } },
586
+ { names: ["--timeout"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.timeoutS = v; } },
544
587
  { names: ["--yes"], set: (a) => { a.yes = true; } },
545
588
  { names: ["--dry-run"], set: (a) => { a.dryRun = true; } },
546
589
  { names: ["--copy"], set: (a) => { a.copy = true; } },
547
590
  { names: ["--share"], set: (a) => { a.share = true; } },
591
+ { names: ["--report"], set: (a) => { a.report = true; } },
592
+ { names: ["--by"], value: "text", set: (a, v) => { a.by = v; } },
593
+ { names: ["--export"], set: (a) => { a.exportSpend = true; } },
594
+ { names: ["--anonymize"], set: (a) => { a.anonymize = true; } },
595
+ { names: ["--as"], value: "text", set: (a, v) => { a.as = v; } },
548
596
  { names: ["--block"], set: (a) => { a.block = true; } },
549
597
  { names: ["--allow-dirty"], set: (a) => { a.allowDirty = true; } },
550
598
  { names: ["--statusline"], set: (a) => { a.statusLine = true; } },
@@ -761,7 +809,7 @@ async function applyChosenFixes(chosen, fixes, inputs, prunePlan, port) {
761
809
  continue;
762
810
  }
763
811
  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 });
812
+ 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, mcpDefer: inputs.mcpDefer });
765
813
  results.push({ id, ...r });
766
814
  }
767
815
  return results;
@@ -853,8 +901,8 @@ async function main() {
853
901
  return;
854
902
  }
855
903
  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 ?? ""}".`);
904
+ if (args.file !== "measure" && args.file !== "event" && args.file !== "usage")
905
+ usageError(`Usage: context-doctor mod measure|event|usage (the plugin's mod runs these, with JSON on stdin); got "${args.file ?? ""}".`);
858
906
  if (process.stdin.isTTY) {
859
907
  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
908
  return;
@@ -866,6 +914,7 @@ async function main() {
866
914
  process.exitCode = await abCommand({
867
915
  levers: args.levers, tasks: args.abTasks, model: args.model, repeat: args.repeat, maxTurns: args.maxTurns,
868
916
  concurrency: args.concurrency, budgetUsd: args.budgetUsd, yes: args.yes === true, json: args.json, out: args.out, list: args.list,
917
+ via: args.via, compare: args.compare, timeoutS: args.timeoutS,
869
918
  });
870
919
  return;
871
920
  }
@@ -1000,7 +1049,7 @@ async function main() {
1000
1049
  }
1001
1050
  const profile = profileConversation(sessionConversation, args.model ?? parsed.model);
1002
1051
  if (args.json) {
1003
- console.log(JSON.stringify({ session: { path: parsed.path, title: parsed.title, ...(picked ? { picked: picked.how } : {}), toolTimings: parsed.toolTimings ?? [], subagents: subagentReport(path) }, profile }, null, 2));
1052
+ console.log(JSON.stringify({ session: { path: parsed.path, title: parsed.title, ...(picked ? { picked: picked.how } : {}), toolTimings: parsed.toolTimings ?? [], subagents: subagentReport(path), claudeCode: claudeCodeSession(path) ?? null }, profile }, null, 2));
1004
1053
  // --json is what CI pipes, so the gate must hold here too (as it does for
1005
1054
  // analyze); it used to run only after the text report and never failed.
1006
1055
  applyBudgetGate(checkBudget(loadConfig(process.cwd(), (m) => console.error(`context-doctor: ${m}`)).config.budget, profile).overBudget, args.failOverBudget);
@@ -1046,6 +1095,16 @@ async function main() {
1046
1095
  console.log("");
1047
1096
  console.log(subs);
1048
1097
  }
1098
+ // Claude Code's own figure for it (its cost-state), beside ours.
1099
+ const cc = renderSessionComparison(claudeCodeSession(path));
1100
+ // A price that ended is never applied silently: which, and the one used.
1101
+ const ended = sessionPriceEnded(path);
1102
+ if (ended)
1103
+ cc.push(ended);
1104
+ if (cc.length) {
1105
+ console.log("");
1106
+ console.log(cc.join("\n"));
1107
+ }
1049
1108
  applyBudgetGate(printBudgetStatus(profile, loadConfig(process.cwd(), (m) => console.error(`context-doctor: ${m}`))), args.failOverBudget);
1050
1109
  }
1051
1110
  return;
@@ -1132,7 +1191,8 @@ async function main() {
1132
1191
  ], report.days);
1133
1192
  if (args.json) {
1134
1193
  const { largest: _largest, ...missSummary } = misses;
1135
- console.log(JSON.stringify({ ...report, cacheMisses: missSummary, limitFit: limitFit ?? null, outputAndPolling: lens }, null, 2));
1194
+ const { largest: _coldLargest, ...coldSummary } = misses.coldReturns;
1195
+ console.log(JSON.stringify({ ...report, cacheMisses: { ...missSummary, coldReturns: coldSummary }, limitFit: limitFit ?? null, outputAndPolling: lens }, null, 2));
1136
1196
  }
1137
1197
  else if (args.share) {
1138
1198
  const text = renderShare(report);
@@ -1141,7 +1201,7 @@ async function main() {
1141
1201
  console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
1142
1202
  }
1143
1203
  else {
1144
- console.log(renderSavings(report, on, cwLine, cacheMissesSignificant(misses) ? cacheMissesLine(misses) : undefined, limitLines, renderLens(lens)));
1204
+ console.log(renderSavings(report, on, cwLine, cacheMissesSignificant(misses) ? cacheMissesLine(misses) : undefined, limitLines, renderLens(lens), misses.coldReturns.best));
1145
1205
  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).`);
1146
1206
  }
1147
1207
  return;
@@ -1379,7 +1439,7 @@ async function main() {
1379
1439
  chosen = ids;
1380
1440
  }
1381
1441
  if (!args.json)
1382
- console.log(renderFixPlan(inputs.days, inputs.billedUsd, fixes, since, selfCommand, inputs.coldResume, inputs.recordProblem, inputs.codexCompact?.billedUsd));
1442
+ console.log(renderFixPlan(inputs.days, inputs.billedUsd, fixes, since, selfCommand, inputs.coldResume, inputs.recordProblem, inputs.codexCompact?.billedUsd, inputs.keepWarm));
1383
1443
  if (args.apply === undefined && !args.json && process.stdin.isTTY && process.stdout.isTTY && available.length && !inputs.recordProblem) {
1384
1444
  const rl = (await import("node:readline/promises")).createInterface({ input: process.stdin, output: process.stdout });
1385
1445
  console.log("");
@@ -1396,7 +1456,7 @@ async function main() {
1396
1456
  process.exitCode = 1;
1397
1457
  if (args.json) {
1398
1458
  // 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));
1459
+ console.log(JSON.stringify({ days: inputs.days, billedUsd: inputs.billedUsd, ...(inputs.codexCompact ? { codexBilledUsd: inputs.codexCompact.billedUsd } : {}), fixes: fixes.map(({ qualityFree: _q, ...f }) => f), since, ...(inputs.keepWarm ? { keepWarm: inputs.keepWarm } : {}), ...(args.apply !== undefined ? { applied: results } : {}), ...(inputs.recordProblem ? { recordProblem: inputs.recordProblem } : {}) }, null, 2));
1400
1460
  if (args.apply !== undefined && chosen.length === 0)
1401
1461
  console.error("--apply: no fix available to apply.");
1402
1462
  return;
@@ -1478,21 +1538,82 @@ async function main() {
1478
1538
  return;
1479
1539
  }
1480
1540
  if (args.command === "limits") {
1541
+ if (args.report && args.json)
1542
+ usageError("--report and --json do not go together: --report prints a block to paste.");
1481
1543
  const reading = progressLine("Reading your limits and usage");
1482
1544
  const report = limitsReport(args.days ?? 30);
1483
1545
  reading.clear();
1546
+ if (args.report) {
1547
+ const text = renderLimitsReport(report);
1548
+ console.log(text);
1549
+ if (args.copy)
1550
+ console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
1551
+ return;
1552
+ }
1484
1553
  console.log(args.json ? JSON.stringify(report, null, 2) : renderLimits(report));
1485
1554
  return;
1486
1555
  }
1487
1556
  if (args.command === "spend") {
1488
- if (args.file !== undefined)
1489
- usageError(`Usage: context-doctor spend [--days n] [--limit n] [--share [--copy]] [--json]; got "${args.file}".`);
1557
+ const spendUsage = "Usage: context-doctor spend [--days n] [--limit n] [--by project|repo|branch] [--share [--copy]] [--json] | spend --export [file] [--as <name>] [--anonymize] [--by branch] | spend merge <folder> [--json]";
1558
+ const extra = (args.positionals ?? []).slice(args.file === "merge" || args.exportSpend ? 2 : 1);
1559
+ if (extra.length)
1560
+ usageError(`${spendUsage}; got "${extra.join(" ")}" too.`);
1561
+ if (args.file === "merge") {
1562
+ const folder = args.positionals?.[1];
1563
+ if (!folder)
1564
+ usageError("Usage: context-doctor spend merge <folder>: the folder your team's spend exports are in.");
1565
+ if (args.exportSpend || args.share || args.by !== undefined || args.anonymize || args.as !== undefined)
1566
+ usageError("spend merge takes a folder, and --json or --limit n.");
1567
+ let found;
1568
+ try {
1569
+ found = readExports(folder);
1570
+ }
1571
+ catch (e) {
1572
+ const code = e.code;
1573
+ console.error(`context-doctor: could not read ${folder}: ${code === "ENOENT" ? "no such folder" : code === "ENOTDIR" ? "not a folder" : e.message}`);
1574
+ process.exit(1);
1575
+ }
1576
+ const merged = mergeExports(found.exports, found.skipped);
1577
+ console.log(args.json ? JSON.stringify(merged, null, 2) : renderMerge(merged, folder, args.limit ?? 8));
1578
+ if (!merged.files)
1579
+ process.exitCode = 1;
1580
+ return;
1581
+ }
1582
+ if (!args.exportSpend && args.file !== undefined)
1583
+ usageError(`${spendUsage}; got "${args.file}".`);
1584
+ if ((args.anonymize || args.as !== undefined) && !args.exportSpend)
1585
+ usageError("--anonymize and --as go with --export: context-doctor spend --export --as <name> --anonymize.");
1490
1586
  if (args.share && args.json)
1491
1587
  usageError("--share and --json do not go together: --share prints a few lines to paste.");
1588
+ if (args.exportSpend && (args.share || args.json))
1589
+ usageError("--export writes a file of totals; it takes no --share or --json (the file is JSON).");
1590
+ const by = args.by;
1591
+ if (by !== undefined && by !== "project" && by !== "repo" && by !== "branch")
1592
+ usageError(`--by takes project, repo or branch; got "${by}".${didYouMean(by, ["project", "repo", "branch"])}`);
1593
+ if (by !== undefined && args.share)
1594
+ usageError("--by and --share do not go together: --share carries no project, repository or branch.");
1595
+ if (args.exportSpend) {
1596
+ const developer = (args.as ?? defaultDeveloper()).trim();
1597
+ if (!developer || developer.length > 64)
1598
+ usageError("--as takes a name of 1 to 64 characters: what your team calls you in the merged view.");
1599
+ const reading = progressLine("Reading your usage across tools");
1600
+ const c = collectSpend(args.days ?? 30, { onProgress: reading.tick, by: by === "branch" ? "branch" : "repo", progress: false });
1601
+ reading.clear();
1602
+ const e = buildExport(c.items, { developer, days: c.days, since: c.since, until: c.until, basis: spendBasis(), anonymize: args.anonymize, branches: by === "branch" });
1603
+ const file = args.file ?? exportFileName(e);
1604
+ const text = JSON.stringify(e, null, 1) + "\n";
1605
+ if (file === "-") {
1606
+ process.stdout.write(text);
1607
+ return;
1608
+ }
1609
+ writeOut(file, text);
1610
+ console.log(renderExportDone(e, file));
1611
+ return;
1612
+ }
1492
1613
  const reading = progressLine("Reading your usage across tools");
1493
1614
  // The progress summaries' estimate: none after the variable turned them off (fix's record), none at all when set with no record.
1494
1615
  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 } : {}) } });
1616
+ const report = spendReport(args.days ?? 30, { onProgress: reading.tick, ...(by ? { by } : {}), progress: { forkGateOff: ps.forkGateOff, offSince: ps.offSince, ...(ps.set && disablesSummaries(ps.set.value) ? { set: ps.set.where } : {}) } });
1496
1617
  reading.clear();
1497
1618
  if (args.json)
1498
1619
  console.log(JSON.stringify(report, null, 2));
@@ -1547,10 +1668,11 @@ async function main() {
1547
1668
  }
1548
1669
  if (args.command === "subagents") {
1549
1670
  const reading = progressLine("Reading your sessions' subagents");
1550
- const report = subagentPayback(args.days ?? 30, undefined, reading.tick);
1671
+ // Every request is priced (rateCard): the organization's rates read once for the run.
1672
+ const report = withOrgRatesHeld(() => subagentPayback(args.days ?? 30, undefined, reading.tick));
1551
1673
  reading.clear();
1552
1674
  // The medians the subagent price (PreToolUse) quotes, refreshed here.
1553
- const costs = measureSubagentCosts(args.days ?? 30);
1675
+ const costs = withOrgRatesHeld(() => measureSubagentCosts(args.days ?? 30));
1554
1676
  if (costs.n > 0)
1555
1677
  saveSubagentCosts(costs);
1556
1678
  console.log(args.json ? JSON.stringify({ ...report, medians: costs }, null, 2) : [renderPayback(report, args.limit ?? 8), ...renderCostMedians(costs)].join("\n"));
@@ -1673,8 +1795,8 @@ async function main() {
1673
1795
  // One read of each Claude Code transcript for both counts (scan.ts); subagents hold MCP calls too.
1674
1796
  const mains = claudeTranscripts(args.days ?? 30);
1675
1797
  prescan([
1676
- { paths: mains, extractors: [REQUEST_ROWS, MCP_ROWS] },
1677
- { paths: mains.flatMap((p) => subagentFiles(p).map((f) => f.file)), extractors: [MCP_ROWS] },
1798
+ { paths: mains, extractors: [REQUEST_ROWS, MCP_ROWS, START_ROWS] },
1799
+ { paths: mains.flatMap((p) => subagentFiles(p).map((f) => f.file)), extractors: [MCP_ROWS, REQUEST_ROWS, START_ROWS] },
1678
1800
  ], sessions.tick);
1679
1801
  const report = overheadReport({
1680
1802
  days: args.days,
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Cline's record of what it sent. Checked 2026-11-15 against ccusage's Cline
3
+ * loader (rust/adapters/cline) and its docs:
4
+ *
5
+ * - The editor extension keeps each task in its `globalStorage` folder
6
+ * (`saoudrizwan.claude-dev`, under VS Code, VS Code Insiders, Cursor,
7
+ * Windsurf or VSCodium): `tasks/<task>/ui_messages.json`, a JSON array.
8
+ * A request is a `say: "api_req_started"` message whose `text` is JSON
9
+ * with `tokensIn` (uncached), `tokensOut`, `cacheReads`, `cacheWrites`;
10
+ * its model is `modelInfo.modelId`. One marked `partial` is still being
11
+ * written; `deleted_api_reqs` and `subagent_usage` are roll-ups of
12
+ * requests counted elsewhere: none is counted.
13
+ * - Older Cline CLI versions keep tasks the same way in `~/.cline/data/tasks`.
14
+ * - The Cline CLI keeps sessions in `~/.cline/data/sessions/<id>/<id>.messages.json`:
15
+ * assistant messages with `modelInfo.id` and `metrics` (`inputTokens`
16
+ * including both cache counts, `outputTokens`, `cacheReadTokens`,
17
+ * `cacheWriteTokens`).
18
+ *
19
+ * `CLINE_DATA_DIR` (a comma list) replaces the places searched. A request
20
+ * from an older extension with no `modelInfo` takes the task's model at that
21
+ * time from `task_metadata.json` (`model_usage`), else is counted unpriced.
22
+ * The folder a task ran in is `cwdOnTaskInitialization` in the extension's
23
+ * `state/taskHistory.json`, when that file is there. Nothing else is read:
24
+ * the `text` of a request also holds the prompt, which is never kept.
25
+ */
26
+ /** One Cline request. */
27
+ export interface ClineCall {
28
+ ts: number;
29
+ /** "task:<id>" (the extension, the older CLI) or "cli:<id>" (a CLI session). */
30
+ session: string;
31
+ model?: string;
32
+ input: number;
33
+ read: number;
34
+ write: number;
35
+ output: number;
36
+ cwd?: string;
37
+ }
38
+ /** Every folder Cline may keep data in, those that exist. Each OS's spot is checked on every OS, as the files may have been copied. */
39
+ export declare function clineRoots(home?: string): string[];
40
+ /** Every Cline request between `since` and `until`, from every place it keeps data. A file that cannot be read is skipped. */
41
+ export declare function clineCalls(since: number, until?: number, home?: string): ClineCall[];
package/dist/cline.js ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Cline's record of what it sent. Checked 2026-11-15 against ccusage's Cline
3
+ * loader (rust/adapters/cline) and its docs:
4
+ *
5
+ * - The editor extension keeps each task in its `globalStorage` folder
6
+ * (`saoudrizwan.claude-dev`, under VS Code, VS Code Insiders, Cursor,
7
+ * Windsurf or VSCodium): `tasks/<task>/ui_messages.json`, a JSON array.
8
+ * A request is a `say: "api_req_started"` message whose `text` is JSON
9
+ * with `tokensIn` (uncached), `tokensOut`, `cacheReads`, `cacheWrites`;
10
+ * its model is `modelInfo.modelId`. One marked `partial` is still being
11
+ * written; `deleted_api_reqs` and `subagent_usage` are roll-ups of
12
+ * requests counted elsewhere: none is counted.
13
+ * - Older Cline CLI versions keep tasks the same way in `~/.cline/data/tasks`.
14
+ * - The Cline CLI keeps sessions in `~/.cline/data/sessions/<id>/<id>.messages.json`:
15
+ * assistant messages with `modelInfo.id` and `metrics` (`inputTokens`
16
+ * including both cache counts, `outputTokens`, `cacheReadTokens`,
17
+ * `cacheWriteTokens`).
18
+ *
19
+ * `CLINE_DATA_DIR` (a comma list) replaces the places searched. A request
20
+ * from an older extension with no `modelInfo` takes the task's model at that
21
+ * time from `task_metadata.json` (`model_usage`), else is counted unpriced.
22
+ * The folder a task ran in is `cwdOnTaskInitialization` in the extension's
23
+ * `state/taskHistory.json`, when that file is there. Nothing else is read:
24
+ * the `text` of a request also holds the prompt, which is never kept.
25
+ */
26
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
27
+ import { homedir } from "node:os";
28
+ import { join } from "node:path";
29
+ const EDITORS = ["Code", "Code - Insiders", "Cursor", "Windsurf", "VSCodium"];
30
+ /** Every folder Cline may keep data in, those that exist. Each OS's spot is checked on every OS, as the files may have been copied. */
31
+ export function clineRoots(home = homedir()) {
32
+ const own = home === homedir();
33
+ if (own && process.env.CLINE_DATA_DIR)
34
+ return process.env.CLINE_DATA_DIR.split(",").map((s) => s.trim()).filter((s) => s && existsSync(s));
35
+ const bases = [
36
+ join(home, "Library", "Application Support"),
37
+ own && process.env.XDG_CONFIG_HOME ? process.env.XDG_CONFIG_HOME : join(home, ".config"),
38
+ own && process.env.APPDATA ? process.env.APPDATA : join(home, "AppData", "Roaming"),
39
+ ];
40
+ const roots = [...new Set(bases)].flatMap((b) => EDITORS.map((e) => join(b, e, "User", "globalStorage", "saoudrizwan.claude-dev")));
41
+ roots.push(join(home, ".cline"));
42
+ return roots.filter((r) => existsSync(r));
43
+ }
44
+ const count = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
45
+ const text = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
46
+ const isUnknown = (m) => !m || m.toLowerCase() === "unknown";
47
+ function readJson(file) {
48
+ try {
49
+ return JSON.parse(readFileSync(file, "utf8"));
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ }
55
+ function list(dir) {
56
+ try {
57
+ return readdirSync(dir);
58
+ }
59
+ catch {
60
+ return [];
61
+ }
62
+ }
63
+ function newer(file, since) {
64
+ try {
65
+ return statSync(file).mtimeMs >= since;
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ }
71
+ /** The extension's task folders: task id to the folder it started in. */
72
+ function taskFolders(root) {
73
+ const out = new Map();
74
+ const h = readJson(join(root, "state", "taskHistory.json"));
75
+ for (const t of Array.isArray(h) ? h : [])
76
+ if (text(t?.id) && text(t?.cwdOnTaskInitialization))
77
+ out.set(t.id, t.cwdOnTaskInitialization);
78
+ return out;
79
+ }
80
+ /** One task's requests (ui_messages.json). */
81
+ function taskCalls(dir, id, cwd) {
82
+ const msgs = readJson(join(dir, "ui_messages.json"));
83
+ if (!Array.isArray(msgs))
84
+ return [];
85
+ // The model in use at each time, for a request that does not name its own.
86
+ const meta = readJson(join(dir, "task_metadata.json"));
87
+ const uses = (Array.isArray(meta?.model_usage) ? meta.model_usage : []).filter((u) => typeof u?.ts === "number" && text(u?.model_id)).sort((a, b) => a.ts - b.ts);
88
+ const out = [];
89
+ for (const m of msgs) {
90
+ if (m?.type !== "say" || m.say !== "api_req_started" || m.partial === true || typeof m.ts !== "number" || typeof m.text !== "string")
91
+ continue;
92
+ let t;
93
+ try {
94
+ t = JSON.parse(m.text);
95
+ }
96
+ catch {
97
+ continue;
98
+ }
99
+ if (typeof t?.tokensIn !== "number" || typeof t?.tokensOut !== "number")
100
+ continue;
101
+ const c = { ts: m.ts, session: `task:${id}`, input: count(t.tokensIn), read: count(t.cacheReads), write: count(t.cacheWrites), output: count(t.tokensOut) };
102
+ if (c.input + c.read + c.write + c.output === 0)
103
+ continue;
104
+ let model = text(m.modelInfo?.modelId);
105
+ if (isUnknown(model))
106
+ model = text([...uses].reverse().find((u) => u.ts <= m.ts)?.model_id);
107
+ if (!isUnknown(model))
108
+ c.model = model;
109
+ if (cwd)
110
+ c.cwd = cwd;
111
+ out.push(c);
112
+ }
113
+ return out;
114
+ }
115
+ /** One CLI session's requests (<id>.messages.json). */
116
+ function sessionCalls(file, id) {
117
+ const doc = readJson(file);
118
+ const msgs = Array.isArray(doc?.messages) ? doc.messages : [];
119
+ const cwd = text(doc?.cwd) ?? text(doc?.workspaceRoot);
120
+ const out = [];
121
+ for (const m of msgs) {
122
+ if (m?.role !== "assistant" || !m.metrics || typeof m.metrics !== "object")
123
+ continue;
124
+ const ts = typeof m.ts === "number" ? m.ts : Date.parse(String(m.timestamp ?? ""));
125
+ if (!Number.isFinite(ts) || ts <= 0)
126
+ continue;
127
+ const x = m.metrics;
128
+ if (typeof x.inputTokens !== "number" || typeof x.outputTokens !== "number")
129
+ continue;
130
+ const read = count(x.cacheReadTokens), write = count(x.cacheWriteTokens);
131
+ const c = { ts, session: `cli:${id}`, input: Math.max(0, count(x.inputTokens) - read - write), read, write, output: count(x.outputTokens) };
132
+ if (c.input + c.read + c.write + c.output === 0)
133
+ continue;
134
+ const model = text(m.modelInfo?.id);
135
+ if (!isUnknown(model))
136
+ c.model = model;
137
+ if (cwd)
138
+ c.cwd = cwd;
139
+ out.push(c);
140
+ }
141
+ return out;
142
+ }
143
+ /** Every Cline request between `since` and `until`, from every place it keeps data. A file that cannot be read is skipped. */
144
+ export function clineCalls(since, until = Infinity, home = homedir()) {
145
+ const out = [];
146
+ const seen = new Set();
147
+ const keep = (cs) => {
148
+ for (const c of cs) {
149
+ const k = `${c.session}\u0000${c.ts}\u0000${c.input}\u0000${c.output}`;
150
+ if (c.ts < since || c.ts > until || seen.has(k))
151
+ continue;
152
+ seen.add(k);
153
+ out.push(c);
154
+ }
155
+ };
156
+ for (const root of clineRoots(home)) {
157
+ const folders = taskFolders(root);
158
+ for (const tasks of [join(root, "tasks"), join(root, "data", "tasks")]) {
159
+ for (const id of list(tasks)) {
160
+ const dir = join(tasks, id);
161
+ if (newer(join(dir, "ui_messages.json"), since))
162
+ keep(taskCalls(dir, id, folders.get(id)));
163
+ }
164
+ }
165
+ for (const sessions of [join(root, "sessions"), join(root, "data", "sessions")]) {
166
+ for (const id of list(sessions)) {
167
+ const file = join(sessions, id, `${id}.messages.json`);
168
+ if (newer(file, since))
169
+ keep(sessionCalls(file, id));
170
+ }
171
+ }
172
+ }
173
+ return out.sort((a, b) => a.ts - b.ts);
174
+ }
@@ -79,6 +79,17 @@ export declare function autoCompactsAt(model: string | undefined, home?: string,
79
79
  export declare const COLD_IDLE_MS: number;
80
80
  /** Margin past a cache's lifetime before a return counts as cold. */
81
81
  export declare const COLD_MARGIN_MS: number;
82
+ /**
83
+ * How long the cache entry a reply left behind lives: one hour when the reply
84
+ * wrote the 1-hour cache, five minutes when it wrote only the 5-minute one,
85
+ * and otherwise whatever the last write before it used (a read refreshes an
86
+ * entry at its own lifetime). Claude Code's main thread wrote the 1-hour cache
87
+ * until 2.1.295, which often writes the 5-minute one (in the author's last 3
88
+ * days, 1,307 main-thread replies wrote only 5-minute entries): a gate fixed
89
+ * at 65 minutes missed every return between 10 and 65 minutes to those
90
+ * sessions, cold as they were. Undefined when nothing says.
91
+ */
92
+ export declare function writtenTtlMs(u: any): number | undefined;
82
93
  /** Below this, a rebuilt cache is cheap and compaction is not worth the interruption. */
83
94
  export declare const COLD_MIN_TOKENS = 150000;
84
95
  /** What a compacted session restarts from: system prompt and tools plus the summary. */