context-doctor 0.48.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 (74) hide show
  1. package/README.md +15 -14
  2. package/dist/abclaude.js +1 -1
  3. package/dist/budget.d.ts +5 -2
  4. package/dist/budget.js +21 -7
  5. package/dist/cache.js +3 -3
  6. package/dist/cachemisses.d.ts +3 -0
  7. package/dist/cachemisses.js +8 -0
  8. package/dist/cachettl.js +6 -2
  9. package/dist/ccost.d.ts +160 -0
  10. package/dist/ccost.js +304 -0
  11. package/dist/cli.js +135 -32
  12. package/dist/cline.d.ts +41 -0
  13. package/dist/cline.js +174 -0
  14. package/dist/coldresume.d.ts +11 -0
  15. package/dist/coldresume.js +3 -3
  16. package/dist/coldreturns.d.ts +145 -0
  17. package/dist/coldreturns.js +282 -0
  18. package/dist/compactcost.d.ts +10 -4
  19. package/dist/compactcost.js +12 -7
  20. package/dist/compactwindow.js +2 -2
  21. package/dist/copilotusage.d.ts +78 -0
  22. package/dist/copilotusage.js +193 -0
  23. package/dist/doctor.d.ts +6 -0
  24. package/dist/doctor.js +17 -4
  25. package/dist/fix.d.ts +28 -2
  26. package/dist/fix.js +49 -5
  27. package/dist/limits.d.ts +222 -14
  28. package/dist/limits.js +684 -33
  29. package/dist/mcp.js +1 -1
  30. package/dist/mcpdefer.d.ts +47 -0
  31. package/dist/mcpdefer.js +91 -0
  32. package/dist/mod/api.d.ts +72 -2
  33. package/dist/mod/api.js +5 -1
  34. package/dist/mod/logic.d.ts +281 -0
  35. package/dist/mod/logic.js +336 -0
  36. package/dist/mod/register.d.ts +35 -2
  37. package/dist/mod/register.js +283 -6
  38. package/dist/modmeasure.d.ts +6 -4
  39. package/dist/modmeasure.js +8 -4
  40. package/dist/opencode.d.ts +57 -0
  41. package/dist/opencode.js +234 -0
  42. package/dist/orgrates.d.ts +7 -0
  43. package/dist/orgrates.js +19 -0
  44. package/dist/overhead.d.ts +3 -0
  45. package/dist/overhead.js +5 -1
  46. package/dist/pricing.d.ts +59 -2
  47. package/dist/pricing.js +125 -10
  48. package/dist/proxy.d.ts +8 -1
  49. package/dist/proxy.js +13 -1
  50. package/dist/savings.d.ts +5 -1
  51. package/dist/savings.js +11 -5
  52. package/dist/scan.d.ts +3 -1
  53. package/dist/scan.js +8 -1
  54. package/dist/sessionprice.d.ts +5 -0
  55. package/dist/sessionprice.js +5 -1
  56. package/dist/spend.d.ts +86 -3
  57. package/dist/spend.js +240 -23
  58. package/dist/spendplace.d.ts +40 -0
  59. package/dist/spendplace.js +93 -0
  60. package/dist/spendteam.d.ts +160 -0
  61. package/dist/spendteam.js +286 -0
  62. package/dist/starts.d.ts +106 -0
  63. package/dist/starts.js +406 -0
  64. package/dist/statusline.d.ts +2 -2
  65. package/dist/statusline.js +2 -2
  66. package/dist/subagentmodel.js +9 -7
  67. package/dist/subagentpay.d.ts +31 -2
  68. package/dist/subagentpay.js +232 -68
  69. package/dist/subagents.js +3 -3
  70. package/dist/tasks.js +3 -2
  71. package/dist/tooloutput.js +5 -5
  72. package/dist/usagepane.d.ts +77 -0
  73. package/dist/usagepane.js +287 -0
  74. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -30,6 +30,7 @@ import { autopilotOff, autopilotOn, autopilotPauseResult, autopilotPaths, autopi
30
30
  import { estimateSavings, renderSavings, renderShare, savingsRows } from "./savings.js";
31
31
  import { prescan } from "./scan.js";
32
32
  import { REQUEST_ROWS } from "./coldresume.js";
33
+ import { coldReturns } from "./coldreturns.js";
33
34
  import { replaySubagentModels, shares, SUBAGENT_MODEL_ENV, SUBAGENT_MODEL_FORCE_ENV, SUBAGENT_ROWS } from "./subagentmodel.js";
34
35
  import { BASH_OUTPUT_ENV, BASH_OUTPUT_KEY, replayToolOutput, TOOL_OUTPUT_ROWS } from "./tooloutput.js";
35
36
  import { CODEX_COMPACT_ROWS, codexRollouts, currentCodexCompact, replayCodexCompact } from "./codexcompact.js";
@@ -55,6 +56,7 @@ import { analyzeCacheUsage, renderCacheReport } from "./cache.js";
55
56
  import { renderToolTimings } from "./timing.js";
56
57
  import { packContextSemantic, readSources, renderPack } from "./pack.js";
57
58
  import { measureBaselines, measureMcpSizes, overheadReport, renderOverhead } from "./overhead.js";
59
+ import { deferrableConfigured, measureStarts, START_ROWS } from "./starts.js";
58
60
  import { applySplit, planSplit, renderSplit } from "./split.js";
59
61
  import { ciReport, renderCiMarkdown, renderCiText } from "./ci.js";
60
62
  import { renderReads, repeatedReads } from "./reads.js";
@@ -64,7 +66,7 @@ import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses
64
66
  import { renderPayback, subagentPayback, SUBAGENT_CANDIDATE } from "./subagentpay.js";
65
67
  import { compactionQuality, renderCompactionQuality, QUALITY_ROWS } from "./compactquality.js";
66
68
  import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
67
- import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits } from "./limits.js";
69
+ import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits, renderLimitsReport } from "./limits.js";
68
70
  import { currentTranscript, findSession, recall, renderRecall } from "./recall.js";
69
71
  import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
70
72
  import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPrune } from "./prune.js";
@@ -77,7 +79,10 @@ import { effectiveEnv, settingsSources, shellSet, underClaudeCode } from "./effe
77
79
  import { SettingsError } from "./settingsedit.js";
78
80
  import { currentTtl, estimateCacheTtl, renderCacheTtl, setCacheTtl, settingKey, subagentTranscripts, ttlUnsupported, CACHE_TTL_SINCE } from "./cachettl.js";
79
81
  import { claudeDir } from "./claudedir.js";
80
- 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";
81
86
  import { clearBudget, parseBudget, periodSpend, promptHookInstalled, readBudget, renderBudgetStatus, writeBudget } from "./budget.js";
82
87
  /**
83
88
  * The commands that print JSON with --json. Any other command refuses the
@@ -152,17 +157,28 @@ Measure:
152
157
  cost, and whether a CLAUDE.md summary or pack pays
153
158
  context-doctor compactions [--days n] Do sessions work worse right after compacting? Re-reads,
154
159
  tool errors and your corrections, before vs after
155
- context-doctor limits [--days n] Your plan's limits in their own unit: the 5-hour and
156
- weekly windows (Claude Pro/Max, via the status line)
157
- and Codex's, the pace, when each runs out, and what
158
- 1M tokens of each kind cost in %, fitted on your own
159
- readings with the fit's error
160
- 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]]
161
169
  One bill across every tool here: Claude Code (with
162
- its subagents), Codex, Gemini CLI and Cursor (an
163
- estimate: no cache split), by project, model and
164
- day, and what drives it, as billed at list rates.
165
- --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
166
182
  context-doctor cache-misses [--days n] Requests that re-wrote the prompt cache while it was
167
183
  still warm: priced, by model and context size, with
168
184
  the cause where the transcript shows one
@@ -273,9 +289,10 @@ Internal (Claude Code and MCP clients run these for you):
273
289
  context-doctor statusline Claude Code status bar line: live context size, cache
274
290
  share, cost (wired by \`install --statusline\`; reads
275
291
  the status JSON on stdin)
276
- 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,
277
293
  terminal): limit readings, Claude Code's cost beside
278
- 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)
279
296
  context-doctor mcp [--http] The MCP server (same as context-doctor-mcp), for clients
280
297
  that launch \`npx -y context-doctor mcp\`
281
298
 
@@ -377,7 +394,7 @@ Start here
377
394
  context-doctor fix what to change, ranked by what it saves you; applied only on a yes
378
395
  context-doctor install wire the MCP server, skill and hooks into the apps it finds
379
396
  context-doctor savings what your recent sessions cost, and what each fix would save
380
- 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
381
398
  context-doctor doctor check the installation
382
399
 
383
400
  All commands: context-doctor --help
@@ -397,10 +414,12 @@ async function measureFixInputs(days) {
397
414
  // With autopilot already on, its replay (most of the time) answers nothing `fix` asks.
398
415
  const replaying = progressLine(autopilotOnNow ? "Reading your Claude Code sessions" : "Replaying your Claude Code sessions");
399
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");
400
419
  // Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
401
420
  prescan([
402
- { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS, TOOL_OUTPUT_ROWS] },
403
- { 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] : [])] },
404
423
  ...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
405
424
  { paths: codexRollouts(Date.now() - days * 86_400_000), extractors: [CODEX_COMPACT_ROWS] },
406
425
  ], replaying.tick);
@@ -457,6 +476,9 @@ async function measureFixInputs(days) {
457
476
  // Codex's auto-compact limit: its rollouts replayed at earlier limits; a limit the user set is theirs.
458
477
  const codexCompact = replayCodexCompact({ days });
459
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;
460
482
  const ts = effectiveEnv("ENABLE_TOOL_SEARCH", sources);
461
483
  const toolSearchOff = ts && /^(false|0|no|off)$/i.test(ts.value.trim()) ? ts.value : undefined;
462
484
  const servers = claudeMcpConfigs(cwd).filter((c) => !/context-doctor/i.test(c.name));
@@ -473,6 +495,7 @@ async function measureFixInputs(days) {
473
495
  userSettings = JSON.parse(readFileSync(join(claudeDir(), "settings.json"), "utf8")) ?? {};
474
496
  }
475
497
  catch { /* none */ }
498
+ const deferrable = configured ? deferrableConfigured(measureStarts({ days, cwd })) : [];
476
499
  let recordProblem;
477
500
  try {
478
501
  loadFixRecords();
@@ -494,6 +517,7 @@ async function measureFixInputs(days) {
494
517
  toolSearchOff,
495
518
  mcpServers: toolSearchOff ? servers.length : 0,
496
519
  prune: prunePlan,
520
+ ...(deferrable.length ? { mcpDefer: { servers: deferrable, days } } : {}),
497
521
  subagentModel,
498
522
  subagentModelSet,
499
523
  // The newest ab --via claude-code comparison of Sonnet 5.5 with another model: the subagent-model line quotes it.
@@ -509,6 +533,7 @@ async function measureFixInputs(days) {
509
533
  // The installs a setting is too new for are named on its fix.
510
534
  claudeCodeInstalls: claudeCodeInstallsFromEnv(),
511
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 } : {}),
512
537
  },
513
538
  };
514
539
  }
@@ -563,6 +588,11 @@ const FLAGS = [
563
588
  { names: ["--dry-run"], set: (a) => { a.dryRun = true; } },
564
589
  { names: ["--copy"], set: (a) => { a.copy = true; } },
565
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; } },
566
596
  { names: ["--block"], set: (a) => { a.block = true; } },
567
597
  { names: ["--allow-dirty"], set: (a) => { a.allowDirty = true; } },
568
598
  { names: ["--statusline"], set: (a) => { a.statusLine = true; } },
@@ -779,7 +809,7 @@ async function applyChosenFixes(chosen, fixes, inputs, prunePlan, port) {
779
809
  continue;
780
810
  }
781
811
  const kind = id === "cache-ttl" ? "main" : id === "cache-ttl-subagents" ? "subagents" : undefined;
782
- 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 });
783
813
  results.push({ id, ...r });
784
814
  }
785
815
  return results;
@@ -871,8 +901,8 @@ async function main() {
871
901
  return;
872
902
  }
873
903
  if (args.command === "mod") {
874
- if (args.file !== "measure" && args.file !== "event")
875
- 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 ?? ""}".`);
876
906
  if (process.stdin.isTTY) {
877
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.");
878
908
  return;
@@ -1019,7 +1049,7 @@ async function main() {
1019
1049
  }
1020
1050
  const profile = profileConversation(sessionConversation, args.model ?? parsed.model);
1021
1051
  if (args.json) {
1022
- 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));
1023
1053
  // --json is what CI pipes, so the gate must hold here too (as it does for
1024
1054
  // analyze); it used to run only after the text report and never failed.
1025
1055
  applyBudgetGate(checkBudget(loadConfig(process.cwd(), (m) => console.error(`context-doctor: ${m}`)).config.budget, profile).overBudget, args.failOverBudget);
@@ -1065,6 +1095,16 @@ async function main() {
1065
1095
  console.log("");
1066
1096
  console.log(subs);
1067
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
+ }
1068
1108
  applyBudgetGate(printBudgetStatus(profile, loadConfig(process.cwd(), (m) => console.error(`context-doctor: ${m}`))), args.failOverBudget);
1069
1109
  }
1070
1110
  return;
@@ -1151,7 +1191,8 @@ async function main() {
1151
1191
  ], report.days);
1152
1192
  if (args.json) {
1153
1193
  const { largest: _largest, ...missSummary } = misses;
1154
- 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));
1155
1196
  }
1156
1197
  else if (args.share) {
1157
1198
  const text = renderShare(report);
@@ -1160,7 +1201,7 @@ async function main() {
1160
1201
  console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
1161
1202
  }
1162
1203
  else {
1163
- 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));
1164
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).`);
1165
1206
  }
1166
1207
  return;
@@ -1398,7 +1439,7 @@ async function main() {
1398
1439
  chosen = ids;
1399
1440
  }
1400
1441
  if (!args.json)
1401
- 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));
1402
1443
  if (args.apply === undefined && !args.json && process.stdin.isTTY && process.stdout.isTTY && available.length && !inputs.recordProblem) {
1403
1444
  const rl = (await import("node:readline/promises")).createInterface({ input: process.stdin, output: process.stdout });
1404
1445
  console.log("");
@@ -1415,7 +1456,7 @@ async function main() {
1415
1456
  process.exitCode = 1;
1416
1457
  if (args.json) {
1417
1458
  // qualityFree is the bare screen's grouping, not part of fix's JSON.
1418
- 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));
1419
1460
  if (args.apply !== undefined && chosen.length === 0)
1420
1461
  console.error("--apply: no fix available to apply.");
1421
1462
  return;
@@ -1497,21 +1538,82 @@ async function main() {
1497
1538
  return;
1498
1539
  }
1499
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.");
1500
1543
  const reading = progressLine("Reading your limits and usage");
1501
1544
  const report = limitsReport(args.days ?? 30);
1502
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
+ }
1503
1553
  console.log(args.json ? JSON.stringify(report, null, 2) : renderLimits(report));
1504
1554
  return;
1505
1555
  }
1506
1556
  if (args.command === "spend") {
1507
- if (args.file !== undefined)
1508
- 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.");
1509
1586
  if (args.share && args.json)
1510
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
+ }
1511
1613
  const reading = progressLine("Reading your usage across tools");
1512
1614
  // The progress summaries' estimate: none after the variable turned them off (fix's record), none at all when set with no record.
1513
1615
  const ps = progressSummariesState({ cwd: process.cwd() });
1514
- 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 } : {}) } });
1515
1617
  reading.clear();
1516
1618
  if (args.json)
1517
1619
  console.log(JSON.stringify(report, null, 2));
@@ -1566,10 +1668,11 @@ async function main() {
1566
1668
  }
1567
1669
  if (args.command === "subagents") {
1568
1670
  const reading = progressLine("Reading your sessions' subagents");
1569
- 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));
1570
1673
  reading.clear();
1571
1674
  // The medians the subagent price (PreToolUse) quotes, refreshed here.
1572
- const costs = measureSubagentCosts(args.days ?? 30);
1675
+ const costs = withOrgRatesHeld(() => measureSubagentCosts(args.days ?? 30));
1573
1676
  if (costs.n > 0)
1574
1677
  saveSubagentCosts(costs);
1575
1678
  console.log(args.json ? JSON.stringify({ ...report, medians: costs }, null, 2) : [renderPayback(report, args.limit ?? 8), ...renderCostMedians(costs)].join("\n"));
@@ -1692,8 +1795,8 @@ async function main() {
1692
1795
  // One read of each Claude Code transcript for both counts (scan.ts); subagents hold MCP calls too.
1693
1796
  const mains = claudeTranscripts(args.days ?? 30);
1694
1797
  prescan([
1695
- { paths: mains, extractors: [REQUEST_ROWS, MCP_ROWS] },
1696
- { 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] },
1697
1800
  ], sessions.tick);
1698
1801
  const report = overheadReport({
1699
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. */
@@ -68,7 +68,7 @@ export function isIdleCompactNotice(e) {
68
68
  * reader meets it as a repeat of that reply and skips it.
69
69
  */
70
70
  export const REQUEST_ROWS = {
71
- id: "requests.2",
71
+ id: "requests.3",
72
72
  init: () => ({ ids: {}, user: false }),
73
73
  line(raw, row, out, st) {
74
74
  let e;
@@ -108,7 +108,7 @@ export const REQUEST_ROWS = {
108
108
  if (m.usage)
109
109
  st.ids[m.id] = (st.ids[m.id] ?? 0) | thread;
110
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"]));
111
+ out.push(pick({ ...e, message: m && typeof m === "object" && !Array.isArray(m) ? pick({ ...m, usage: slimUsage(m.usage, { iterations: true }) }, ["id", "model", "usage"]) : m }, ["type", "isSidechain", "uuid", "timestamp", "message"]));
112
112
  },
113
113
  };
114
114
  /** The context at which Claude Code's idle compaction acts, as it reads the environment. */
@@ -158,7 +158,7 @@ const FIVE_MIN_MS = 5 * 60_000;
158
158
  * at 65 minutes missed every return between 10 and 65 minutes to those
159
159
  * sessions, cold as they were. Undefined when nothing says.
160
160
  */
161
- function writtenTtlMs(u) {
161
+ export function writtenTtlMs(u) {
162
162
  // Only an explicit split says: cacheWriteSplit books unsplit writes as
163
163
  // 5-minute for pricing, which would make every old transcript look short-lived.
164
164
  const split = u?.cache_creation;