context-doctor 0.49.1 → 0.51.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 (57) hide show
  1. package/README.md +19 -17
  2. package/dist/apptools.d.ts +89 -0
  3. package/dist/apptools.js +203 -0
  4. package/dist/appwindow.d.ts +75 -0
  5. package/dist/appwindow.js +161 -0
  6. package/dist/budget.d.ts +20 -2
  7. package/dist/budget.js +43 -3
  8. package/dist/cachemisses.d.ts +70 -0
  9. package/dist/cachemisses.js +126 -0
  10. package/dist/ccost.js +8 -4
  11. package/dist/claudedir.d.ts +15 -0
  12. package/dist/claudedir.js +19 -1
  13. package/dist/cli.js +77 -29
  14. package/dist/clihelp.d.ts +5 -1
  15. package/dist/clihelp.js +9 -1
  16. package/dist/codexstatusline.d.ts +176 -0
  17. package/dist/codexstatusline.js +353 -0
  18. package/dist/compactwindow.d.ts +14 -2
  19. package/dist/compactwindow.js +30 -5
  20. package/dist/credits.d.ts +192 -0
  21. package/dist/credits.js +350 -0
  22. package/dist/doctor.d.ts +18 -0
  23. package/dist/doctor.js +62 -3
  24. package/dist/fanout.d.ts +2 -0
  25. package/dist/fanout.js +12 -2
  26. package/dist/fileparams.js +15 -3
  27. package/dist/fix.d.ts +48 -3
  28. package/dist/fix.js +112 -19
  29. package/dist/limits.d.ts +87 -2
  30. package/dist/limits.js +329 -29
  31. package/dist/mcp.d.ts +1 -0
  32. package/dist/mcp.js +106 -100
  33. package/dist/mod/api.d.ts +27 -1
  34. package/dist/mod/api.js +2 -1
  35. package/dist/mod/logic.d.ts +85 -1
  36. package/dist/mod/logic.js +118 -5
  37. package/dist/mod/register.d.ts +16 -2
  38. package/dist/mod/register.js +59 -5
  39. package/dist/modelids.d.ts +15 -0
  40. package/dist/modelids.js +35 -2
  41. package/dist/modmeasure.d.ts +7 -0
  42. package/dist/modmeasure.js +9 -0
  43. package/dist/orgrates.d.ts +4 -2
  44. package/dist/orgrates.js +21 -3
  45. package/dist/overhead.js +10 -3
  46. package/dist/pricing.js +7 -0
  47. package/dist/progresssummaries.d.ts +103 -1
  48. package/dist/progresssummaries.js +187 -11
  49. package/dist/proxy.d.ts +1 -1
  50. package/dist/proxy.js +9 -4
  51. package/dist/savings.js +3 -1
  52. package/dist/spend.d.ts +32 -3
  53. package/dist/spend.js +68 -6
  54. package/dist/starts.d.ts +34 -1
  55. package/dist/starts.js +88 -21
  56. package/dist/usagepane.js +1 -1
  57. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -35,6 +35,8 @@ import { replaySubagentModels, shares, SUBAGENT_MODEL_ENV, SUBAGENT_MODEL_FORCE_
35
35
  import { BASH_OUTPUT_ENV, BASH_OUTPUT_KEY, replayToolOutput, TOOL_OUTPUT_ROWS } from "./tooloutput.js";
36
36
  import { CODEX_COMPACT_ROWS, codexRollouts, currentCodexCompact, replayCodexCompact } from "./codexcompact.js";
37
37
  import { currentCompactWindow, estimateCompactWindows, MAX_WINDOW, MIN_WINDOW, parseWindow, renderCompactWindows, setCompactWindow, settingsPath } from "./compactwindow.js";
38
+ import { appWindowLines, readAppWindows } from "./appwindow.js";
39
+ import { modelName } from "./subagentmodel.js";
38
40
  import { tilde } from "./claudedir.js";
39
41
  import { renderPreferences, copyToClipboard, CHAT_PREFERENCES } from "./preferences.js";
40
42
  import { recordLedger } from "./ledger.js";
@@ -44,6 +46,7 @@ import { renderDiff } from "./diff.js";
44
46
  import { renderExperiment, runExperiment } from "./experiment.js";
45
47
  import { runStatusLine } from "./statusline.js";
46
48
  import { runMod } from "./modmeasure.js";
49
+ import { recentToolLines } from "./apptools.js";
47
50
  import { renderSubagents, subagentFiles, subagentReport } from "./subagents.js";
48
51
  import { findPreset, PRESETS, RC_FILENAME } from "./config.js";
49
52
  import { runWatch } from "./watch.js";
@@ -56,7 +59,8 @@ import { analyzeCacheUsage, renderCacheReport } from "./cache.js";
56
59
  import { renderToolTimings } from "./timing.js";
57
60
  import { packContextSemantic, readSources, renderPack } from "./pack.js";
58
61
  import { measureBaselines, measureMcpSizes, overheadReport, renderOverhead } from "./overhead.js";
59
- import { deferrableConfigured, measureStarts, START_ROWS } from "./starts.js";
62
+ import { CALL_ROWS, deferrableApp, deferrableConfigured, measureStarts, START_ROWS } from "./starts.js";
63
+ import { DEFER_APP_TOOLS_ENV } from "./mod/logic.js";
60
64
  import { applySplit, planSplit, renderSplit } from "./split.js";
61
65
  import { ciReport, renderCiMarkdown, renderCiText } from "./ci.js";
62
66
  import { renderReads, repeatedReads } from "./reads.js";
@@ -67,6 +71,7 @@ import { renderPayback, subagentPayback, SUBAGENT_CANDIDATE } from "./subagentpa
67
71
  import { compactionQuality, renderCompactionQuality, QUALITY_ROWS } from "./compactquality.js";
68
72
  import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
69
73
  import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits, renderLimitsReport } from "./limits.js";
74
+ import { creditsAheadLine, creditsAheadNow, creditsLines, creditsReport } from "./credits.js";
70
75
  import { currentTranscript, findSession, recall, renderRecall } from "./recall.js";
71
76
  import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
72
77
  import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPrune } from "./prune.js";
@@ -83,7 +88,7 @@ import { claudeCodeSession, collectSpend, renderSpend, renderSpendShare, session
83
88
  import { buildExport, defaultDeveloper, exportFileName, mergeExports, readExports, renderExportDone, renderMerge } from "./spendteam.js";
84
89
  import { renderSessionComparison } from "./ccost.js";
85
90
  import { withOrgRatesHeld } from "./orgrates.js";
86
- import { clearBudget, parseBudget, periodSpend, promptHookInstalled, readBudget, renderBudgetStatus, writeBudget } from "./budget.js";
91
+ import { clearBudget, parseBudget, periodCredits, periodSpend, promptHookInstalled, readBudget, renderBudgetStatus, writeBudget } from "./budget.js";
87
92
  /**
88
93
  * The commands that print JSON with --json. Any other command refuses the
89
94
  * flag: it used to print its text report anyway and exit 0, so a script
@@ -127,13 +132,17 @@ Start here:
127
132
  as billed. --share: totals only, to paste
128
133
  context-doctor fix [--apply ids|all] [--share] What to change, ranked by dollars on your own
129
134
  sessions (compact earlier, the cache lifetime,
130
- autopilot, MCP tool search, unused servers, the
131
- subagents' model): each applied only on a yes
132
- (the subagents' model only by name, never by
133
- "all"), \`fix undo\` reverts them, later runs show
134
- what each saved since. A bare \`context-doctor\`
135
- in a terminal shows the same plan on one screen
136
- and asks once about the fixes with no quality cost
135
+ autopilot, MCP tool search, MCP servers loaded up
136
+ front, the Desktop app's own tools, unused servers,
137
+ long Bash output to a file, the subagents' model,
138
+ Codex's auto-compact limit, subagent progress
139
+ summaries): each applied only on a yes (the
140
+ subagents' model and the two MCP deferrals only by
141
+ name, never by "all"), \`fix undo\` reverts them,
142
+ later runs show what each saved since. A bare
143
+ \`context-doctor\` in a terminal shows the same plan
144
+ on one screen and asks once about the fixes with
145
+ no quality cost
137
146
  context-doctor doctor Self-check the installation (configs, hook, skill,
138
147
  MCP handshake) with one pasteable diagnosis
139
148
  context-doctor uninstall Undo install
@@ -414,12 +423,12 @@ async function measureFixInputs(days) {
414
423
  // With autopilot already on, its replay (most of the time) answers nothing `fix` asks.
415
424
  const replaying = progressLine(autopilotOnNow ? "Reading your Claude Code sessions" : "Replaying your Claude Code sessions");
416
425
  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).
426
+ // A server of the user's own that could have gone whole into a start (mcp-defer); the Desktop app's own servers (desktop-tools-defer) are measured from every start.
418
427
  const configured = claudeMcpConfigs(cwd).some((c) => c.scope !== ".mcp.json");
419
428
  // Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
420
429
  prescan([
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] : [])] },
430
+ { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS, TOOL_OUTPUT_ROWS, START_ROWS, CALL_ROWS] },
431
+ { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS, PROGRESS_ROWS, START_ROWS, CALL_ROWS] },
423
432
  ...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
424
433
  { paths: codexRollouts(Date.now() - days * 86_400_000), extractors: [CODEX_COMPACT_ROWS] },
425
434
  ], replaying.tick);
@@ -434,11 +443,14 @@ async function measureFixInputs(days) {
434
443
  const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
435
444
  measuring.clear();
436
445
  const windowing = progressLine("Replaying an earlier auto-compact window");
437
- const cw = estimateCompactWindows([400_000], days, undefined, reread, windowing.tick);
446
+ // The Desktop app's own window offer, answered: that model's sessions are left as they ran.
447
+ const app = readAppWindows({ cwd });
448
+ const cw = estimateCompactWindows([400_000], days, undefined, reread, windowing.tick, { leaveModels: app.answers.map((a) => a.model) });
438
449
  windowing.clear();
439
450
  const est = cw.estimates[0];
451
+ const appLines = appWindowLines(app, cw.leftAlone?.sessions ?? 0);
440
452
  if (cw.sessions > 0 && est)
441
- compactWindow = { window: est.window, savedUsd: est.savedUsd, savedShare: est.savedPct, compactionsPerWeek: (est.compactions / cw.days) * 7, nowPerWeek: (cw.actualCompactions / cw.days) * 7 };
453
+ compactWindow = { window: est.window, savedUsd: est.savedUsd, savedShare: est.savedPct, compactionsPerWeek: (est.compactions / cw.days) * 7, nowPerWeek: (cw.actualCompactions / cw.days) * 7, ...(appLines.length ? { app: { lines: appLines, answered: app.answers.map((a) => modelName(a.model)), leftSessions: cw.leftAlone?.sessions ?? 0 } } : {}) };
442
454
  }
443
455
  const ttling = progressLine("Replaying both cache lifetimes");
444
456
  const ttl = estimateCacheTtl(days, { onProgress: ttling.tick });
@@ -472,7 +484,7 @@ async function measureFixInputs(days) {
472
484
  // The subagents' progress summaries: estimated from their transcripts; a value of the variable the user set is theirs.
473
485
  const psState = progressSummariesState({ cwd });
474
486
  const psSince = Date.now() - days * 86_400_000;
475
- const progressSummaries = estimateProgressSummaries(subagentTranscripts(psSince), { since: psSince, forkGateOff: psState.forkGateOff, offSince: psState.offSince });
487
+ const progressSummaries = estimateProgressSummaries(subagentTranscripts(psSince), { since: psSince, forkGateOff: psState.forkGateOff, offSince: psState.offSince, route: psState.route });
476
488
  // Codex's auto-compact limit: its rollouts replayed at earlier limits; a limit the user set is theirs.
477
489
  const codexCompact = replayCodexCompact({ days });
478
490
  const cxSet = currentCodexCompact();
@@ -495,7 +507,17 @@ async function measureFixInputs(days) {
495
507
  userSettings = JSON.parse(readFileSync(join(claudeDir(), "settings.json"), "utf8")) ?? {};
496
508
  }
497
509
  catch { /* none */ }
498
- const deferrable = configured ? deferrableConfigured(measureStarts({ days, cwd })) : [];
510
+ const starts = measureStarts({ days, cwd });
511
+ const deferrable = configured ? deferrableConfigured(starts) : [];
512
+ const appTools = deferrableApp(starts);
513
+ // CONTEXT_DOCTOR_DEFER_MCP: the user's settings.json env (fix writes it there), else a shell's own value (not the session's copy of a settings value).
514
+ const userDt = sources.find((s) => s.name === "user")?.settings.env?.[DEFER_APP_TOOLS_ENV];
515
+ const desktopToolsSet = userDt !== undefined && userDt !== null && String(userDt).trim() !== ""
516
+ ? { value: String(userDt), where: `${tilde(join(claudeDir(), "settings.json"))} env` }
517
+ : !underClaudeCode() && shellSet(DEFER_APP_TOOLS_ENV, sources, process.env)
518
+ ? { value: process.env[DEFER_APP_TOOLS_ENV], where: "the environment" }
519
+ : undefined;
520
+ const appToolsSeen = recentToolLines(days);
499
521
  let recordProblem;
500
522
  try {
501
523
  loadFixRecords();
@@ -504,7 +526,11 @@ async function measureFixInputs(days) {
504
526
  recordProblem = e.message;
505
527
  }
506
528
  const sessions = report.sessions.length;
507
- const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact", "progress-summaries"];
529
+ const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact", "progress-summaries", "desktop-tools-defer"];
530
+ const overrides = Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })]));
531
+ // The mod is what reads the variable: without the plugin, nothing moves.
532
+ if (appTools.length && !claudePluginEnabled())
533
+ overrides["desktop-tools-defer"].push("context-doctor's Claude Code plugin is not enabled, and its mod is what reads this (/plugin install context-doctor@context-doctor inside Claude Code)");
508
534
  return {
509
535
  prunePlan,
510
536
  inputs: {
@@ -518,6 +544,10 @@ async function measureFixInputs(days) {
518
544
  mcpServers: toolSearchOff ? servers.length : 0,
519
545
  prune: prunePlan,
520
546
  ...(deferrable.length ? { mcpDefer: { servers: deferrable, days } } : {}),
547
+ ...(appTools.length ? { desktopTools: { servers: appTools.map((s) => ({ name: s.name, tools: s.tools, tokens: s.tokens, starts: s.starts, calledStarts: s.calledStarts, usd: s.usd, unusedUsd: s.unusedUsd, calledUsd: s.calledUsd })), days } } : {}),
548
+ ...(desktopToolsSet ? { desktopToolsSet } : {}),
549
+ // What context-doctor's mod saw Claude Code hand over (apptools.ts): proof the lever reaches the app, or why not.
550
+ ...(appToolsSeen.length ? { appToolsSeen } : {}),
521
551
  subagentModel,
522
552
  subagentModelSet,
523
553
  // The newest ab --via claude-code comparison of Sonnet 5.5 with another model: the subagent-model line quotes it.
@@ -528,7 +558,7 @@ async function measureFixInputs(days) {
528
558
  ...(psState.set ? { progressSummariesSet: psState.set } : {}),
529
559
  ...(codexCompact.requests > 0 ? { codexCompact } : {}),
530
560
  ...(cxSet ? { codexCompactSet: { raw: cxSet.raw, where: cxSet.where } } : {}),
531
- overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
561
+ overrides,
532
562
  recordProblem,
533
563
  // The installs a setting is too new for are named on its fix.
534
564
  claudeCodeInstalls: claudeCodeInstallsFromEnv(),
@@ -1169,7 +1199,7 @@ async function main() {
1169
1199
  const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
1170
1200
  measuring.clear();
1171
1201
  const windowing = progressLine("Replaying an earlier auto-compact window");
1172
- const cwReport = estimateCompactWindows([setWindow ?? 400_000], args.days ?? 30, undefined, reread, windowing.tick);
1202
+ const cwReport = estimateCompactWindows([setWindow ?? 400_000], args.days ?? 30, undefined, reread, windowing.tick, { leaveModels: readAppWindows().answers.map((a) => a.model) });
1173
1203
  windowing.clear();
1174
1204
  const est = cwReport.estimates[0];
1175
1205
  const cwLine = cwReport.sessions > 0 && est
@@ -1261,6 +1291,11 @@ async function main() {
1261
1291
  console.log(`✓ autoCompactWindow = ${w} in ${tilde(settingsPath())}${note ? ` (${note})` : ""}.`);
1262
1292
  console.log(" Claude Code sessions started from now on compact as if the window were that size,");
1263
1293
  console.log(" in the terminal, IDEs and the desktop app. Check in a session with /context.");
1294
+ const answered = readAppWindows().answers;
1295
+ if (answered.length) {
1296
+ console.log(` You answered the Desktop app's own window offer for ${answered.map((a) => modelName(a.model)).join(", ")}: whether this setting`);
1297
+ console.log(" or the app's choice wins there is not recorded on this computer.");
1298
+ }
1264
1299
  const over = fixOverrides("compact-window");
1265
1300
  if (over.length) {
1266
1301
  console.log(` ⚠ It will not take effect while ${over.join("; ")} ${over.length === 1 ? "overrides" : "override"} it.`);
@@ -1281,14 +1316,17 @@ async function main() {
1281
1316
  const reread = compactionQuality(60, undefined, measuring.tick).extraRereadTokensPerCompaction;
1282
1317
  measuring.clear();
1283
1318
  const replaying = progressLine("Replaying your sessions at each window");
1284
- const cw = estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread, replaying.tick);
1319
+ const app = readAppWindows();
1320
+ const cw = estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread, replaying.tick, { leaveModels: app.answers.map((a) => a.model) });
1285
1321
  replaying.clear();
1322
+ const appLines = appWindowLines(app, cw.leftAlone?.sessions ?? 0);
1286
1323
  if (args.json) {
1287
- console.log(JSON.stringify({ ...cw, current: current ?? null }, null, 2));
1324
+ // The Desktop app's answers and the server's windows, only when there are some (the output is otherwise as before).
1325
+ console.log(JSON.stringify({ ...cw, current: current ?? null, ...(appLines.length ? { desktopApp: app } : {}) }, null, 2));
1288
1326
  return;
1289
1327
  }
1290
1328
  const limitFit = claudeLimitFit(limitsReport(cw.days, { claudeOnly: true }));
1291
- console.log(renderCompactWindows(cw, current, (estimates) => limitSavingsLines(limitFit, estimates.map((e) => [`${Math.round(e.window / 1000)}k window`, Math.max(0, e.savedUsd)]), cw.days)));
1329
+ console.log(renderCompactWindows(cw, current, (estimates) => limitSavingsLines(limitFit, estimates.map((e) => [`${Math.round(e.window / 1000)}k window`, Math.max(0, e.savedUsd)]), cw.days), appLines, app.served.length > 0));
1292
1330
  return;
1293
1331
  }
1294
1332
  if (args.command === "autopilot") {
@@ -1422,7 +1460,7 @@ async function main() {
1422
1460
  usageError("--apply and --share do not go together: --share only prints totals.");
1423
1461
  const { inputs, prunePlan } = await measureFixInputs(args.days ?? 30);
1424
1462
  const fixes = planFixes(inputs);
1425
- const since = savedSince(readFixRecords());
1463
+ const since = savedSince(readFixRecords(), { progressRoute: progressSummariesState({ cwd: process.cwd() }).route });
1426
1464
  if (args.share) {
1427
1465
  const text = renderFixShare(inputs.days, inputs.billedUsd, fixes, inputs.codexCompact?.billedUsd);
1428
1466
  console.log(text);
@@ -1550,7 +1588,13 @@ async function main() {
1550
1588
  console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
1551
1589
  return;
1552
1590
  }
1553
- console.log(args.json ? JSON.stringify(report, null, 2) : renderLimits(report));
1591
+ // Requests paid from usage credits past a limit: read only when the ledger says a limit ran out.
1592
+ const credits = creditsReport(report.days, { now: report.now });
1593
+ // Running out before the weekly reset with extra usage on: what the hours past it would cost (the transcripts read only then).
1594
+ const ahead = creditsAheadNow({ now: report.now, status: report.windows.find((w) => w.app === "claude" && w.window === "seven_day") });
1595
+ console.log(args.json
1596
+ ? JSON.stringify({ ...report, ...(credits ? { credits } : {}), ...(ahead ? { creditsAhead: ahead } : {}) }, null, 2)
1597
+ : renderLimits(report, credits ? creditsLines(credits, report.now) : [], ahead ? creditsAheadLine(ahead, report.now) : undefined));
1554
1598
  return;
1555
1599
  }
1556
1600
  if (args.command === "spend") {
@@ -1613,7 +1657,7 @@ async function main() {
1613
1657
  const reading = progressLine("Reading your usage across tools");
1614
1658
  // The progress summaries' estimate: none after the variable turned them off (fix's record), none at all when set with no record.
1615
1659
  const ps = progressSummariesState({ cwd: process.cwd() });
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 } : {}) } });
1660
+ const report = spendReport(args.days ?? 30, { onProgress: reading.tick, ...(by ? { by } : {}), progress: { forkGateOff: ps.forkGateOff, offSince: ps.offSince, route: ps.route, ...(ps.set && disablesSummaries(ps.set.value) ? { set: ps.set.where } : {}) } });
1617
1661
  reading.clear();
1618
1662
  if (args.json)
1619
1663
  console.log(JSON.stringify(report, null, 2));
@@ -1654,10 +1698,14 @@ async function main() {
1654
1698
  }
1655
1699
  const b = readBudget();
1656
1700
  const s = b ? periodSpend(b.period) : undefined;
1701
+ // Claude Code's part past the plan's limit, on usage credits: in `spent` already, said apart.
1702
+ const c = s ? periodCredits(s.start) : undefined;
1703
+ // With a budget set: running out before the weekly reset with extra usage on, and what that would cost.
1704
+ const ahead = s ? creditsAheadNow() : undefined;
1657
1705
  if (args.json)
1658
- console.log(JSON.stringify(b && s ? { ...b, spent: s.usd, byTool: s.byTool, periodStart: s.start, periodEnd: s.end, unpriced: s.unpriced ?? null } : null, null, 2));
1706
+ console.log(JSON.stringify(b && s ? { ...b, spent: s.usd, byTool: s.byTool, periodStart: s.start, periodEnd: s.end, unpriced: s.unpriced ?? null, credits: c ? { usd: c.usd, requests: c.requests, fromHeaders: c.fromHeaders, inferred: c.inferred } : null, creditsAhead: ahead ?? null } : null, null, 2));
1659
1707
  else
1660
- console.log(withInvocation(renderBudgetStatus(b, s, promptHookInstalled())));
1708
+ console.log(withInvocation(renderBudgetStatus(b, s, promptHookInstalled(), c, ahead)));
1661
1709
  return;
1662
1710
  }
1663
1711
  if (args.command === "compactions") {
@@ -1795,8 +1843,8 @@ async function main() {
1795
1843
  // One read of each Claude Code transcript for both counts (scan.ts); subagents hold MCP calls too.
1796
1844
  const mains = claudeTranscripts(args.days ?? 30);
1797
1845
  prescan([
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] },
1846
+ { paths: mains, extractors: [REQUEST_ROWS, MCP_ROWS, START_ROWS, CALL_ROWS] },
1847
+ { paths: mains.flatMap((p) => subagentFiles(p).map((f) => f.file)), extractors: [MCP_ROWS, REQUEST_ROWS, START_ROWS, CALL_ROWS] },
1800
1848
  ], sessions.tick);
1801
1849
  const report = overheadReport({
1802
1850
  days: args.days,
package/dist/clihelp.d.ts CHANGED
@@ -4,7 +4,11 @@
4
4
  * cut out of the full help text. Kept apart from cli.ts, which runs on
5
5
  * import, so they can be tested directly.
6
6
  */
7
- /** Edit distance (insert, delete, substitute; each 1). */
7
+ /**
8
+ * Edit distance (insert, delete, substitute, swap two neighbours; each 1).
9
+ * The swap is the commonest typo: without it `--reprot` was as far from
10
+ * `--repeat` as from `--report`, and the first listed won.
11
+ */
8
12
  export declare function levenshtein(a: string, b: string): number;
9
13
  /**
10
14
  * The closest candidate, when it is close enough to be a typo: within a
package/dist/clihelp.js CHANGED
@@ -4,16 +4,24 @@
4
4
  * cut out of the full help text. Kept apart from cli.ts, which runs on
5
5
  * import, so they can be tested directly.
6
6
  */
7
- /** Edit distance (insert, delete, substitute; each 1). */
7
+ /**
8
+ * Edit distance (insert, delete, substitute, swap two neighbours; each 1).
9
+ * The swap is the commonest typo: without it `--reprot` was as far from
10
+ * `--repeat` as from `--report`, and the first listed won.
11
+ */
8
12
  export function levenshtein(a, b) {
9
13
  if (a === b)
10
14
  return 0;
15
+ let before = [];
11
16
  let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
12
17
  for (let i = 1; i <= a.length; i++) {
13
18
  const cur = [i];
14
19
  for (let j = 1; j <= b.length; j++) {
15
20
  cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
21
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
22
+ cur[j] = Math.min(cur[j], before[j - 2] + 1);
16
23
  }
24
+ before = prev;
17
25
  prev = cur;
18
26
  }
19
27
  return prev[b.length];
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Codex's footer, drawn by our MCP server (ROADMAP G5).
3
+ *
4
+ * Codex 0.171.0 lets an MCP tool be a status line, behind its
5
+ * `tui_extensions_statusline` experiment (`/experimental`, Custom status
6
+ * line). The shapes here are Codex's own (openai/codex, codex-rs, read
7
+ * 2026-11-20): `tui/src/statusline_provider/descriptor.rs` takes a tool
8
+ * whose `_meta["openai/ui"].entrypoints` holds exactly one
9
+ * `{ type: "statusline", resourceUri: "ui://..." }`, the tool's title being
10
+ * its name in the `/statusline` picker; `tui/src/chatwidget/statusline_reader.rs`
11
+ * then reads that resource with the displayed thread's snapshot in
12
+ * `params._meta["com.openai/codex-statusline-state"]`, gives each read one
13
+ * second, waits a second and reads again; `statusline_reader/resource.rs`
14
+ * wants exactly one text content at the advertised URI, `application/json`,
15
+ * holding a UI tree (`tui/src/ui_tree.rs`: unknown fields refused, 64 KiB,
16
+ * 256 non-null nodes, depth 16, 16 KiB of text; `null` clears the footer).
17
+ * An error or a timeout stops the polling until the person picks the
18
+ * provider again, so a read here never fails: at worst it answers the last
19
+ * line it drew, or `null`.
20
+ *
21
+ * What it shows, short and plain, only what is known:
22
+ * context 412k of 1.0M (41%) $3.21 this session limits: 5h 23%, weekly 41%
23
+ * The context and the plan's windows are the snapshot's own figures. The
24
+ * dollars are the session's price as `spend` and the every-prompt hook count
25
+ * it, at list prices, the agents the thread spawned included (sessionTotal,
26
+ * sharing the hook's per-session entries). That reads the thread's rollout,
27
+ * whole on a change, which on a 70 MB rollout takes longer than a footer
28
+ * may wait, so it runs in a worker thread, at most one at a time, cached
29
+ * per thread and refreshed when the thread's token totals move; a read
30
+ * waits for it at most READ_BUDGET_MS and otherwise draws the last price
31
+ * it had, or, before the first, the snapshot's own totals priced at the
32
+ * model's rates (the thread alone).
33
+ *
34
+ * Nothing is drawn unasked: Codex shows it only to someone who turned the
35
+ * experiment on and picked it in `/statusline`, and the tool is listed only
36
+ * to Codex (mcp.ts).
37
+ */
38
+ import type { Worker } from "node:worker_threads";
39
+ /** The resource Codex reads; the tool advertises it. */
40
+ export declare const CODEX_STATUSLINE_URI = "ui://context-doctor/statusline";
41
+ /** Where Codex puts the displayed thread's snapshot in a read's `params._meta`. */
42
+ export declare const CODEX_STATUSLINE_STATE = "com.openai/codex-statusline-state";
43
+ /** The tool's `_meta`: exactly one statusline entrypoint (Codex ignores a tool with two). */
44
+ export declare const CODEX_STATUSLINE_META: {
45
+ "openai/ui": {
46
+ entrypoints: {
47
+ type: string;
48
+ resourceUri: string;
49
+ }[];
50
+ };
51
+ };
52
+ /** The worker thread's role, passed as its `workerData`. */
53
+ export declare const PRICE_WORKER_ROLE = "context-doctor/codex-statusline-price";
54
+ /** Codex gives a read one second; this answers well inside it. */
55
+ export declare const READ_BUDGET_MS = 200;
56
+ type Color = string;
57
+ export type UiNode = string | {
58
+ type: "text";
59
+ props?: {
60
+ color?: Color | null;
61
+ weight?: "normal" | "bold" | null;
62
+ };
63
+ children: Array<UiNode | null>;
64
+ } | {
65
+ type: "row";
66
+ props: {
67
+ gap: number;
68
+ wrap?: "nowrap" | "wrap";
69
+ justify?: "start" | "center" | "end" | "between";
70
+ };
71
+ children: Array<UiNode | null>;
72
+ };
73
+ /** Codex's limits on a tree's JSON (ui_tree/decode.rs). */
74
+ export declare const TREE_LIMITS: {
75
+ bytes: number;
76
+ nodes: number;
77
+ depth: number;
78
+ textBytes: number;
79
+ };
80
+ /** A tree's JSON measured as Codex measures it; `ok` when it is within every limit. */
81
+ export declare function measureTree(json: string): {
82
+ ok: boolean;
83
+ bytes: number;
84
+ nodes: number;
85
+ depth: number;
86
+ textBytes: number;
87
+ };
88
+ interface RateLimitWindow {
89
+ used_percent?: number;
90
+ window_minutes?: number | null;
91
+ resets_at?: number | null;
92
+ }
93
+ /** The parts of Codex's `StatuslineState` this reads. Everything optional: a field Codex leaves out is simply not shown. */
94
+ export interface CodexStatuslineState {
95
+ account?: {
96
+ rate_limits?: Array<{
97
+ limit_id?: string;
98
+ primary_limit?: RateLimitWindow | null;
99
+ secondary_limit?: RateLimitWindow | null;
100
+ }>;
101
+ };
102
+ thread?: {
103
+ id?: string;
104
+ model?: {
105
+ id?: string;
106
+ display_name?: string;
107
+ };
108
+ usage?: {
109
+ context?: {
110
+ context_window_size?: number;
111
+ used_tokens?: number;
112
+ used_percentage?: number;
113
+ };
114
+ total?: {
115
+ total_input_tokens?: number;
116
+ cache_read_input_tokens?: number;
117
+ cache_write_input_tokens?: number;
118
+ other_input_tokens?: number;
119
+ output_tokens?: number;
120
+ };
121
+ cost?: {
122
+ total_cost_usd?: number;
123
+ total_credits?: number;
124
+ };
125
+ };
126
+ };
127
+ }
128
+ /**
129
+ * The thread's own token totals priced at its model's list rates, the tier
130
+ * of its current context: the price before the rollout's is known. The
131
+ * thread alone (no spawned agents); undefined for a model with no price.
132
+ */
133
+ export declare function snapshotUsd(state: CodexStatuslineState, at?: number): number | undefined;
134
+ /**
135
+ * The footer for one snapshot, or null when nothing is known (Codex then
136
+ * clears it). `sessionUsd`: the session's price, when known; otherwise the
137
+ * snapshot's totals priced, then Codex's own figure.
138
+ */
139
+ export declare function renderCodexStatusline(state: CodexStatuslineState | undefined, sessionUsd?: number, nowMs?: number): UiNode | null;
140
+ /**
141
+ * The rollout of a Codex thread: `sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl`
142
+ * in the day folders around the time its id was made (local and UTC), then
143
+ * the archive, then every session folder.
144
+ */
145
+ export declare function rolloutFor(threadId: string, home?: string): string | undefined;
146
+ /** The worker side: prices a thread's session on request (sessionprice.ts), one at a time. */
147
+ export declare function servePriceWorker(): Promise<void>;
148
+ /**
149
+ * One per server process: what each thread's session has cost, kept, and
150
+ * the worker that reads it. `spawn` starts the worker (mcp.ts knows the
151
+ * file it runs from); undefined, or a worker that fails, leaves the
152
+ * snapshot's own figures.
153
+ */
154
+ export declare class CodexStatusline {
155
+ private spawn?;
156
+ private worker;
157
+ private broken;
158
+ private next;
159
+ private waiting;
160
+ private inFlight;
161
+ private prices;
162
+ private lastGood;
163
+ constructor(spawn?: (() => Worker) | undefined);
164
+ private ask;
165
+ /** The thread's session price: cached, refreshed in the background, waited for at most `budgetMs`. */
166
+ private price;
167
+ /**
168
+ * The resource's text for one read: a UI tree's JSON, or "null". Never
169
+ * throws and answers within about `budgetMs`: a failure answers the last
170
+ * line drawn for the thread.
171
+ */
172
+ read(rawState: unknown, budgetMs?: number): Promise<string>;
173
+ /** Stops the worker (tests). */
174
+ close(): Promise<void>;
175
+ }
176
+ export {};