context-doctor 0.46.0 → 0.48.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 (68) hide show
  1. package/README.md +9 -4
  2. package/dist/ab.d.ts +51 -3
  3. package/dist/ab.js +71 -28
  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/autopilot.js +9 -5
  9. package/dist/blob.js +66 -12
  10. package/dist/budget.d.ts +8 -2
  11. package/dist/budget.js +30 -7
  12. package/dist/ci.js +2 -1
  13. package/dist/claudeplugin.d.ts +97 -0
  14. package/dist/claudeplugin.js +142 -0
  15. package/dist/cli.js +128 -36
  16. package/dist/compactcost.d.ts +74 -0
  17. package/dist/compactcost.js +115 -0
  18. package/dist/cursor.js +2 -0
  19. package/dist/doctor.js +90 -18
  20. package/dist/extract.js +4 -3
  21. package/dist/fanout.d.ts +15 -0
  22. package/dist/fanout.js +30 -9
  23. package/dist/firstfix.d.ts +43 -0
  24. package/dist/firstfix.js +80 -0
  25. package/dist/fix.d.ts +53 -4
  26. package/dist/fix.js +101 -13
  27. package/dist/httpguard.d.ts +13 -0
  28. package/dist/httpguard.js +22 -0
  29. package/dist/install.d.ts +21 -9
  30. package/dist/install.js +213 -40
  31. package/dist/limits.d.ts +5 -0
  32. package/dist/limits.js +26 -2
  33. package/dist/mcp.d.ts +4 -0
  34. package/dist/mcp.js +142 -97
  35. package/dist/mcpclient.js +73 -42
  36. package/dist/missledger.js +5 -3
  37. package/dist/mod/api.d.ts +8 -2
  38. package/dist/mod/api.js +2 -2
  39. package/dist/mod/logic.d.ts +13 -1
  40. package/dist/mod/logic.js +24 -2
  41. package/dist/mod/register.d.ts +2 -0
  42. package/dist/mod/register.js +19 -5
  43. package/dist/modelids.d.ts +62 -3
  44. package/dist/modelids.js +156 -8
  45. package/dist/modelswitch.js +8 -4
  46. package/dist/modmeasure.js +13 -1
  47. package/dist/orgrates.d.ts +18 -0
  48. package/dist/orgrates.js +51 -2
  49. package/dist/pack.d.ts +13 -0
  50. package/dist/pack.js +38 -2
  51. package/dist/preferences.js +2 -1
  52. package/dist/pricing.d.ts +8 -0
  53. package/dist/pricing.js +30 -2
  54. package/dist/progresssummaries.d.ts +148 -0
  55. package/dist/progresssummaries.js +248 -0
  56. package/dist/proxy.d.ts +1 -1
  57. package/dist/proxy.js +1 -1
  58. package/dist/prune.d.ts +8 -0
  59. package/dist/prune.js +11 -1
  60. package/dist/spend.d.ts +34 -0
  61. package/dist/spend.js +48 -4
  62. package/dist/subagentmodel.d.ts +12 -0
  63. package/dist/subagentmodel.js +17 -4
  64. package/dist/subagentpay.d.ts +8 -0
  65. package/dist/subagentpay.js +8 -1
  66. package/dist/toolcwd.d.ts +14 -0
  67. package/dist/toolcwd.js +17 -0
  68. package/package.json +6 -3
package/dist/cli.js CHANGED
@@ -23,6 +23,7 @@ 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";
@@ -68,7 +69,9 @@ import { currentTranscript, findSession, recall, renderRecall } from "./recall.j
68
69
  import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
69
70
  import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPrune } from "./prune.js";
70
71
  import { lensOverSessions, renderLens, sessionLens, LENS_ROWS } from "./lens.js";
71
- import { applyFix, fixOverrides, loadFixRecords, parseFixIds, planFixes, readFixRecords, renderFixPlan, renderFixShare, savedSince, undoFixes } from "./fix.js";
72
+ import { applyFix, fixOverrides, loadFixRecords, parseFixIds, planFixes, progressSummariesState, readFixRecords, renderFixPlan, renderFixShare, savedSince, undoFixes } from "./fix.js";
73
+ import { disablesSummaries, estimateProgressSummaries, PROGRESS_ROWS } from "./progresssummaries.js";
74
+ import { firstQuestion, renderFirstScreen, splitFirstFixes } from "./firstfix.js";
72
75
  import { claudeMcpConfigs, MCP_ROWS } from "./mcpschema.js";
73
76
  import { effectiveEnv, settingsSources, shellSet, underClaudeCode } from "./effective.js";
74
77
  import { SettingsError } from "./settingsedit.js";
@@ -116,15 +119,16 @@ Start here:
116
119
  What your recent Claude Code sessions cost, and what
117
120
  /compact at cold resumes, autopilot and an earlier
118
121
  auto-compact window would save, replayed and priced
119
- as billed. --share: totals only, to paste. Also
120
- what a bare \`context-doctor\` shows
122
+ as billed. --share: totals only, to paste
121
123
  context-doctor fix [--apply ids|all] [--share] What to change, ranked by dollars on your own
122
124
  sessions (compact earlier, the cache lifetime,
123
125
  autopilot, MCP tool search, unused servers, the
124
126
  subagents' model): each applied only on a yes
125
127
  (the subagents' model only by name, never by
126
128
  "all"), \`fix undo\` reverts them, later runs show
127
- what each saved since
129
+ what each saved since. A bare \`context-doctor\`
130
+ in a terminal shows the same plan on one screen
131
+ and asks once about the fixes with no quality cost
128
132
  context-doctor doctor Self-check the installation (configs, hook, skill,
129
133
  MCP handshake) with one pasteable diagnosis
130
134
  context-doctor uninstall Undo install
@@ -181,6 +185,13 @@ Measure:
181
185
  side. Bills ANTHROPIC_API_KEY: prints the estimate,
182
186
  sends nothing without --yes, never passes --budget usd.
183
187
  --list shows the tasks; --model (default claude-opus-5-5)
188
+ context-doctor ab --via claude-code [--model m] [--compare m2] [--repeat n] [--yes]
189
+ The same tasks through your own Claude Code (claude -p,
190
+ your sign-in: on a plan, its limits, not dollars), one
191
+ arm per model: --model (default claude-sonnet-5-5) vs
192
+ --compare (default claude-opus-5-5). Each run confined
193
+ to a temp copy under Claude Code's sandbox; --timeout s
194
+ per run (default 600). fix quotes the result
184
195
 
185
196
  Fix automatically:
186
197
  context-doctor autopilot on|off|pause|resume|status
@@ -277,11 +288,13 @@ Input: a conversation JSON file (OpenAI or Anthropic message format, or a bare
277
288
  message array). Use "-" to read from stdin.
278
289
 
279
290
  Options:
280
- --model <name> Model name for window-size math (e.g. claude-sonnet-5, gpt-4o)
291
+ --model <name> (analyze, session, cursor, diff, watch, pack, cache-plan, ci, ab,
292
+ experiment) Model to count and price for (e.g. claude-sonnet-5, gpt-4o)
281
293
  --exact (analyze) Add an exact token count: Anthropic count-tokens API for
282
294
  Claude models (needs ANTHROPIC_API_KEY), tiktoken for GPT (if installed)
283
- --redact Mask message previews and file paths in the report, so it can be
284
- shared in a bug report without leaking conversation content
295
+ --redact (analyze, session, cursor) Mask message previews and file paths in
296
+ the report, so it can be shared in a bug report without leaking
297
+ conversation content
285
298
  --json ${optionText(`(${JSON_COMMANDS.join(", ")}) Machine-readable output on stdout`)}
286
299
  --fail-over-budget (analyze/session) Exit 1 when the .contextdoctorrc budget is
287
300
  exceeded — lets CI gate a pull request on context size
@@ -314,6 +327,11 @@ Options:
314
327
  --check <cmd> (experiment) Command whose exit code is the pass/fail for each arm
315
328
  --existing <id> (experiment) Session id to fork the second arm from (never mutated)
316
329
  --budget <usd> (experiment) Spend cap per arm (default 1)
330
+ --via <api|claude-code> (ab) The Messages API on ANTHROPIC_API_KEY (default), or claude -p on
331
+ your own Claude Code sign-in, one arm per model
332
+ --compare <model> (ab --via claude-code) Model(s) to run against --model (default
333
+ claude-opus-5-5; "none" for --model alone)
334
+ --timeout <s> (ab --via claude-code) Seconds before a run is killed (default 600)
317
335
  --dry-run (experiment) Print the claude commands and stop
318
336
  --allow-dirty (experiment) Skip the clean-tree check (uncommitted changes will be lost)
319
337
  --statusline (install) Also set Claude Code's statusLine to context-doctor (never
@@ -382,7 +400,7 @@ async function measureFixInputs(days) {
382
400
  // Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
383
401
  prescan([
384
402
  { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS, TOOL_OUTPUT_ROWS] },
385
- { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS] },
403
+ { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS, PROGRESS_ROWS] },
386
404
  ...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
387
405
  { paths: codexRollouts(Date.now() - days * 86_400_000), extractors: [CODEX_COMPACT_ROWS] },
388
406
  ], replaying.tick);
@@ -432,6 +450,10 @@ async function measureFixInputs(days) {
432
450
  : shellSet(BASH_OUTPUT_ENV, sources, process.env)
433
451
  ? { name: BASH_OUTPUT_ENV, value: process.env[BASH_OUTPUT_ENV], where: underClaudeCode() ? "this Claude Code session's environment" : "the environment" }
434
452
  : undefined;
453
+ // The subagents' progress summaries: estimated from their transcripts; a value of the variable the user set is theirs.
454
+ const psState = progressSummariesState({ cwd });
455
+ const psSince = Date.now() - days * 86_400_000;
456
+ const progressSummaries = estimateProgressSummaries(subagentTranscripts(psSince), { since: psSince, forkGateOff: psState.forkGateOff, offSince: psState.offSince });
435
457
  // Codex's auto-compact limit: its rollouts replayed at earlier limits; a limit the user set is theirs.
436
458
  const codexCompact = replayCodexCompact({ days });
437
459
  const cxSet = currentCodexCompact();
@@ -459,7 +481,7 @@ async function measureFixInputs(days) {
459
481
  recordProblem = e.message;
460
482
  }
461
483
  const sessions = report.sessions.length;
462
- const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact"];
484
+ const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact", "progress-summaries"];
463
485
  return {
464
486
  prunePlan,
465
487
  inputs: {
@@ -474,8 +496,12 @@ async function measureFixInputs(days) {
474
496
  prune: prunePlan,
475
497
  subagentModel,
476
498
  subagentModelSet,
499
+ // The newest ab --via claude-code comparison of Sonnet 5.5 with another model: the subagent-model line quotes it.
500
+ abComparison: latestModelComparison(),
477
501
  toolOutput,
478
502
  toolOutputSet,
503
+ progressSummaries,
504
+ ...(psState.set ? { progressSummariesSet: psState.set } : {}),
479
505
  ...(codexCompact.requests > 0 ? { codexCompact } : {}),
480
506
  ...(cxSet ? { codexCompactSet: { raw: cxSet.raw, where: cxSet.where } } : {}),
481
507
  overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
@@ -530,6 +556,9 @@ const FLAGS = [
530
556
  { names: ["--repeat"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.repeat = v; } },
531
557
  { names: ["--max-turns"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.maxTurns = v; } },
532
558
  { names: ["--concurrency"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.concurrency = v; } },
559
+ { names: ["--via"], value: "text", set: (a, v) => { a.via = v; } },
560
+ { names: ["--compare"], value: "text", set: (a, v) => { (a.compare ??= []).push(v); } },
561
+ { names: ["--timeout"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.timeoutS = v; } },
533
562
  { names: ["--yes"], set: (a) => { a.yes = true; } },
534
563
  { names: ["--dry-run"], set: (a) => { a.dryRun = true; } },
535
564
  { names: ["--copy"], set: (a) => { a.copy = true; } },
@@ -662,6 +691,18 @@ function applyBudgetGate(overBudget, failOverBudget) {
662
691
  function readInput(file) {
663
692
  return stripBom(readFileSync(file === "-" ? 0 : file, "utf8"));
664
693
  }
694
+ /** Write --out's file, or say why not and exit 1 (a folder that does not exist ended in a stack trace). */
695
+ function writeOut(path, text) {
696
+ try {
697
+ writeFileSync(path, text);
698
+ }
699
+ catch (e) {
700
+ const code = e.code;
701
+ const why = code === "ENOENT" ? "its folder does not exist" : code === "EACCES" || code === "EPERM" ? "permission denied" : code === "EISDIR" ? "it is a folder" : e.message;
702
+ console.error(`context-doctor: could not write ${path}: ${why}`);
703
+ process.exit(1);
704
+ }
705
+ }
665
706
  /**
666
707
  * A UTF-8 byte-order mark (Windows editors, PowerShell's Out-File) is not
667
708
  * part of the text: left in, JSON.parse rejects the file and a valid
@@ -724,6 +765,35 @@ function hasClaudeSessions() {
724
765
  return false;
725
766
  }
726
767
  }
768
+ /**
769
+ * Apply the chosen fixes through applyFix, in the order given: `fix`'s
770
+ * answers and `--apply`, and a bare `context-doctor`'s one question, write
771
+ * the same settings and the same records.
772
+ */
773
+ async function applyChosenFixes(chosen, fixes, inputs, prunePlan, port) {
774
+ const results = [];
775
+ for (const id of chosen) {
776
+ const f = fixes.find((x) => x.id === id);
777
+ if (!f || f.state !== "available") {
778
+ results.push({ id, ok: false, lines: [`${id}: ${f?.note ?? "not available here"}; skipped.`] });
779
+ continue;
780
+ }
781
+ 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 });
783
+ results.push({ id, ...r });
784
+ }
785
+ return results;
786
+ }
787
+ /** What each applied fix wrote, and where to undo it. */
788
+ function printApplied(results) {
789
+ if (!results.length)
790
+ return;
791
+ console.log("");
792
+ for (const r of results)
793
+ console.log(r.lines.join("\n"));
794
+ if (results.some((r) => r.ok))
795
+ 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.`);
796
+ }
727
797
  async function main() {
728
798
  const args = parseArgs(process.argv.slice(2));
729
799
  if (args.command && !COMMANDS.includes(args.command)) {
@@ -814,6 +884,7 @@ async function main() {
814
884
  process.exitCode = await abCommand({
815
885
  levers: args.levers, tasks: args.abTasks, model: args.model, repeat: args.repeat, maxTurns: args.maxTurns,
816
886
  concurrency: args.concurrency, budgetUsd: args.budgetUsd, yes: args.yes === true, json: args.json, out: args.out, list: args.list,
887
+ via: args.via, compare: args.compare, timeoutS: args.timeoutS,
817
888
  });
818
889
  return;
819
890
  }
@@ -1005,10 +1076,46 @@ async function main() {
1005
1076
  process.exitCode = 1;
1006
1077
  return;
1007
1078
  }
1008
- if (args.command === "savings" || (!args.command && process.stdout.isTTY && hasClaudeSessions())) {
1079
+ if (!args.command && !args.json && !args.share && process.stdout.isTTY && hasClaudeSessions()) {
1009
1080
  // A bare `context-doctor` in a terminal, with Claude Code history on the
1010
- // machine, answers the question people install this for: what would it
1011
- // save me? Scripts and pipes still get the help text.
1081
+ // machine: fix's plan (one scan), the quality-free fixes under one y/N
1082
+ // question, the others with their dollars and the command for each.
1083
+ // Asked only when stdin is a terminal too; scripts and pipes still get
1084
+ // the Start here screen, and `--json`/`--share` the savings report.
1085
+ const { inputs, prunePlan } = await measureFixInputs(args.days ?? 30);
1086
+ const fixes = planFixes(inputs);
1087
+ const { free } = splitFirstFixes(fixes);
1088
+ const ask = !!process.stdin.isTTY && free.length > 0 && !inputs.recordProblem;
1089
+ console.log(renderFirstScreen({ days: inputs.days, billedUsd: inputs.billedUsd, codexBilledUsd: inputs.codexCompact?.billedUsd, fixes, command: selfCommand, recordProblem: inputs.recordProblem, ask }));
1090
+ if (!ask)
1091
+ return;
1092
+ const rl = (await import("node:readline/promises")).createInterface({ input: process.stdin, output: process.stdout });
1093
+ // Ctrl-D or a closed terminal is a no, never a wait. A Ctrl-D typed during
1094
+ // the scan, while the terminal was still line-buffered, reaches readline's
1095
+ // raw mode as \x04 on macOS but as a NUL on Linux (the tty keeps a pending
1096
+ // end-of-file as \0), which readline ignores: on an empty line it is a no too.
1097
+ const typedAheadEof = (s) => { if (s === "\0" && rl.line === "")
1098
+ rl.close(); };
1099
+ process.stdin.on("keypress", typedAheadEof);
1100
+ const answer = await new Promise((resolve) => {
1101
+ rl.once("close", () => resolve(""));
1102
+ rl.question(firstQuestion(free.length, selfCommand)).then(resolve, () => resolve(""));
1103
+ });
1104
+ process.stdin.off("keypress", typedAheadEof);
1105
+ rl.close();
1106
+ if (!/^(y|yes)$/i.test(answer.trim())) {
1107
+ console.log(`Nothing changed. ${selfCommand("fix")} asks about each lever, the ones above included.`);
1108
+ return;
1109
+ }
1110
+ const results = await applyChosenFixes(free.map((f) => f.id), fixes, inputs, prunePlan, args.port);
1111
+ if (results.some((r) => !r.ok))
1112
+ process.exitCode = 1;
1113
+ printApplied(results);
1114
+ return;
1115
+ }
1116
+ if (args.command === "savings" || (!args.command && process.stdout.isTTY && hasClaudeSessions())) {
1117
+ // `savings`, and a bare `context-doctor --json` or `--share` in a terminal
1118
+ // with Claude Code history (what a bare run printed before the one-question screen).
1012
1119
  const replaying = progressLine("Replaying your Claude Code sessions through autopilot");
1013
1120
  // Each transcript read once for every report below; what an earlier run kept is not read again (scan.ts).
1014
1121
  prescan([
@@ -1055,8 +1162,6 @@ async function main() {
1055
1162
  else {
1056
1163
  console.log(renderSavings(report, on, cwLine, cacheMissesSignificant(misses) ? cacheMissesLine(misses) : undefined, limitLines, renderLens(lens)));
1057
1164
  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).`);
1058
- if (!args.command)
1059
- console.log(`All commands: ${selfCommand("--help")}`);
1060
1165
  }
1061
1166
  return;
1062
1167
  }
@@ -1304,35 +1409,20 @@ async function main() {
1304
1409
  }
1305
1410
  rl.close();
1306
1411
  }
1307
- const results = [];
1308
- for (const id of chosen) {
1309
- const f = fixes.find((x) => x.id === id);
1310
- if (!f || f.state !== "available") {
1311
- results.push({ id, ok: false, lines: [`${id}: ${f?.note ?? "not available here"}; skipped.`] });
1312
- continue;
1313
- }
1314
- const kind = id === "cache-ttl" ? "main" : id === "cache-ttl-subagents" ? "subagents" : undefined;
1315
- 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 });
1316
- results.push({ id, ...r });
1317
- }
1412
+ const results = await applyChosenFixes(chosen, fixes, inputs, prunePlan, args.port);
1318
1413
  // Naming fixes that are not there (or nothing at all, with "all") is not a silent success.
1319
1414
  if (args.apply !== undefined && (chosen.length === 0 || results.some((r) => !r.ok)))
1320
1415
  process.exitCode = 1;
1321
1416
  if (args.json) {
1322
- 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));
1417
+ // 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));
1323
1419
  if (args.apply !== undefined && chosen.length === 0)
1324
1420
  console.error("--apply: no fix available to apply.");
1325
1421
  return;
1326
1422
  }
1327
1423
  if (args.apply !== undefined && chosen.length === 0)
1328
1424
  console.error("\n--apply: no fix available to apply.");
1329
- if (!results.length)
1330
- return;
1331
- console.log("");
1332
- for (const r of results)
1333
- console.log(r.lines.join("\n"));
1334
- if (results.some((r) => r.ok))
1335
- 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.`);
1425
+ printApplied(results);
1336
1426
  return;
1337
1427
  }
1338
1428
  if (args.command === "cache-ttl") {
@@ -1419,7 +1509,9 @@ async function main() {
1419
1509
  if (args.share && args.json)
1420
1510
  usageError("--share and --json do not go together: --share prints a few lines to paste.");
1421
1511
  const reading = progressLine("Reading your usage across tools");
1422
- const report = spendReport(args.days ?? 30, { onProgress: reading.tick });
1512
+ // The progress summaries' estimate: none after the variable turned them off (fix's record), none at all when set with no record.
1513
+ 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 } : {}) } });
1423
1515
  reading.clear();
1424
1516
  if (args.json)
1425
1517
  console.log(JSON.stringify(report, null, 2));
@@ -1499,7 +1591,7 @@ async function main() {
1499
1591
  }
1500
1592
  console.log(args.json ? JSON.stringify(result.plan, null, 2) : renderCachePlan(result.plan));
1501
1593
  if (args.out) {
1502
- writeFileSync(args.out, JSON.stringify(result.apply(), null, 2));
1594
+ writeOut(args.out, JSON.stringify(result.apply(), null, 2));
1503
1595
  console.error(result.plan.plan.length
1504
1596
  ? `context-doctor: request with the planned breakpoints written to ${args.out}`
1505
1597
  : `context-doctor: nothing to place; the request was written unchanged to ${args.out}`);
@@ -1713,7 +1805,7 @@ async function main() {
1713
1805
  }
1714
1806
  const output = JSON.stringify(result.conversation, null, 2);
1715
1807
  if (args.out) {
1716
- writeFileSync(args.out, output);
1808
+ writeOut(args.out, output);
1717
1809
  }
1718
1810
  else if (args.json) {
1719
1811
  console.log(JSON.stringify(result, null, 2));
@@ -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 {};
@@ -0,0 +1,115 @@
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 { requestCost } from "./pricing.js";
27
+ import { textOf } from "./session.js";
28
+ import { realModel, tokensForLength } from "./tokens.js";
29
+ const HOUR_MS = 3_600_000;
30
+ const FIVE_MIN_MS = 300_000;
31
+ /** The summary's output when no summary row follows the boundary: compactwindow.ts's measured figure. */
32
+ export const SUMMARY_TOKENS_UNSEEN = 20_000;
33
+ export const newTrack = () => ({ t: {} });
34
+ /** A ledger's kept state, when it is one this version wrote. */
35
+ export function isTrack(v) {
36
+ return Boolean(v) && typeof v === "object" && Boolean(v.t) && typeof v.t === "object";
37
+ }
38
+ /** The rows a reader must hand on: replies with usage, compaction boundaries, summary rows. */
39
+ export function isCompactionRow(line) {
40
+ return line.includes('"compact_boundary"') || line.includes('"isCompactSummary"');
41
+ }
42
+ const thread = (e) => (e?.isSidechain === true ? "1" : "0");
43
+ function priced(st, summaryTokens) {
44
+ const p = st.p;
45
+ st.p = undefined;
46
+ if (!p)
47
+ return undefined;
48
+ const th = st.t[p.th];
49
+ if (!th?.m || !(p.pre > 0))
50
+ return undefined;
51
+ const ttl = th.ttl ?? HOUR_MS;
52
+ const warm = th.at !== undefined && p.at - th.at <= ttl;
53
+ const usage = warm
54
+ ? { input_tokens: 0, cache_read_input_tokens: p.pre, cache_creation_input_tokens: 0, output_tokens: summaryTokens, ...th.b }
55
+ : { input_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: p.pre, cache_creation: ttl >= HOUR_MS ? { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: p.pre } : { ephemeral_5m_input_tokens: p.pre, ephemeral_1h_input_tokens: 0 }, output_tokens: summaryTokens, ...th.b };
56
+ const cost = requestCost(th.m, usage, p.at);
57
+ if (!cost)
58
+ return undefined;
59
+ return { ...(p.u ? { uuid: p.u } : {}), ...(p.s ? { sessionId: p.s } : {}), sidechain: p.th === "1", ts: p.at, model: th.m, usage, cost, warm };
60
+ }
61
+ /**
62
+ * Feed one parsed row; a compaction's request when this row completes one
63
+ * (its summary row, or a reply that came with no summary row between). A
64
+ * boundary still waiting for its summary at the end of what was read is kept
65
+ * in `st` and priced when the summary is read.
66
+ */
67
+ export function trackCompaction(st, e) {
68
+ if (!e || typeof e !== "object")
69
+ return undefined;
70
+ if (e.type === "system" && e.subtype === "compact_boundary") {
71
+ // A boundary right after another (no summary between): the first is priced as unseen.
72
+ const before = st.p ? priced(st, SUMMARY_TOKENS_UNSEEN) : undefined;
73
+ const at = Date.parse(String(e.timestamp ?? ""));
74
+ const pre = Number(e.compactMetadata?.preTokens);
75
+ if (Number.isFinite(at) && Number.isFinite(pre) && pre > 0) {
76
+ st.p = { at, pre, th: thread(e), ...(typeof e.uuid === "string" ? { u: e.uuid } : {}), ...(typeof e.sessionId === "string" ? { s: e.sessionId } : {}) };
77
+ }
78
+ return before;
79
+ }
80
+ if (e.type === "user" && e.isCompactSummary === true) {
81
+ if (!st.p)
82
+ return undefined;
83
+ const length = typeof e.n === "number" ? e.n : textOf(e.message?.content).length;
84
+ const model = st.t[st.p.th]?.m;
85
+ return priced(st, Math.max(1, tokensForLength(length, false, model)));
86
+ }
87
+ if (e.type === "assistant" && e.message?.usage) {
88
+ const done = st.p && st.p.th === thread(e) ? priced(st, SUMMARY_TOKENS_UNSEEN) : undefined;
89
+ const model = realModel(e.message.model);
90
+ if (!model)
91
+ return done;
92
+ const u = e.message.usage;
93
+ const th = (st.t[thread(e)] ??= {});
94
+ th.m = model;
95
+ const at = Date.parse(String(e.timestamp ?? ""));
96
+ if (Number.isFinite(at))
97
+ th.at = at;
98
+ const split = u.cache_creation;
99
+ if (split && (split.ephemeral_1h_input_tokens ?? 0) > 0)
100
+ th.ttl = HOUR_MS;
101
+ else if (split && (split.ephemeral_5m_input_tokens ?? 0) > 0)
102
+ th.ttl = FIVE_MIN_MS;
103
+ const b = { ...(u.speed === "fast" ? { speed: "fast" } : {}), ...(u.inference_geo === "us" ? { inference_geo: "us" } : {}) };
104
+ if (Object.keys(b).length)
105
+ th.b = b;
106
+ else
107
+ delete th.b;
108
+ return done;
109
+ }
110
+ return undefined;
111
+ }
112
+ /** A summary row as an extractor keeps it: its length, not its text. */
113
+ export function slimSummary(e) {
114
+ return { type: "user", isCompactSummary: true, n: textOf(e?.message?.content).length, ...(e?.isSidechain === true ? { isSidechain: true } : {}) };
115
+ }
package/dist/cursor.js CHANGED
@@ -12,6 +12,7 @@
12
12
  * say so plainly instead of failing obscurely.
13
13
  */
14
14
  import { execFileSync } from "node:child_process";
15
+ import { toolCwd } from "./toolcwd.js";
15
16
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
16
17
  import { createRequire } from "node:module";
17
18
  import { homedir, platform } from "node:os";
@@ -127,6 +128,7 @@ export function queryRows(dbPath, sql) {
127
128
  }
128
129
  // Fallback: the sqlite3 CLI, if the user has it.
129
130
  const cli = (target) => execFileSync("sqlite3", ["-readonly", "-json", target, sql], {
131
+ cwd: toolCwd(),
130
132
  encoding: "utf8",
131
133
  maxBuffer: 512 * 1024 * 1024,
132
134
  stdio: ["ignore", "pipe", "ignore"], // a missing table is expected on some DBs