context-doctor 0.47.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +17 -14
  2. package/dist/ab.d.ts +51 -3
  3. package/dist/ab.js +68 -26
  4. package/dist/abclaude.d.ts +167 -0
  5. package/dist/abclaude.js +511 -0
  6. package/dist/abstore.d.ts +46 -0
  7. package/dist/abstore.js +58 -0
  8. package/dist/budget.d.ts +5 -2
  9. package/dist/budget.js +21 -7
  10. package/dist/cache.js +3 -3
  11. package/dist/cachemisses.d.ts +3 -0
  12. package/dist/cachemisses.js +8 -0
  13. package/dist/cachettl.js +6 -2
  14. package/dist/ccost.d.ts +160 -0
  15. package/dist/ccost.js +304 -0
  16. package/dist/cli.js +154 -32
  17. package/dist/cline.d.ts +41 -0
  18. package/dist/cline.js +174 -0
  19. package/dist/coldresume.d.ts +11 -0
  20. package/dist/coldresume.js +3 -3
  21. package/dist/coldreturns.d.ts +145 -0
  22. package/dist/coldreturns.js +282 -0
  23. package/dist/compactcost.d.ts +10 -4
  24. package/dist/compactcost.js +12 -7
  25. package/dist/compactwindow.js +2 -2
  26. package/dist/copilotusage.d.ts +78 -0
  27. package/dist/copilotusage.js +193 -0
  28. package/dist/doctor.d.ts +6 -0
  29. package/dist/doctor.js +17 -4
  30. package/dist/fix.d.ts +35 -4
  31. package/dist/fix.js +55 -8
  32. package/dist/install.js +2 -0
  33. package/dist/limits.d.ts +222 -14
  34. package/dist/limits.js +684 -33
  35. package/dist/mcp.d.ts +4 -0
  36. package/dist/mcp.js +142 -98
  37. package/dist/mcpclient.js +73 -42
  38. package/dist/mcpdefer.d.ts +47 -0
  39. package/dist/mcpdefer.js +91 -0
  40. package/dist/mod/api.d.ts +72 -2
  41. package/dist/mod/api.js +5 -1
  42. package/dist/mod/logic.d.ts +281 -0
  43. package/dist/mod/logic.js +336 -0
  44. package/dist/mod/register.d.ts +35 -2
  45. package/dist/mod/register.js +283 -6
  46. package/dist/modelids.d.ts +58 -0
  47. package/dist/modelids.js +133 -1
  48. package/dist/modmeasure.d.ts +6 -4
  49. package/dist/modmeasure.js +8 -4
  50. package/dist/opencode.d.ts +57 -0
  51. package/dist/opencode.js +234 -0
  52. package/dist/orgrates.d.ts +7 -0
  53. package/dist/orgrates.js +19 -0
  54. package/dist/overhead.d.ts +3 -0
  55. package/dist/overhead.js +5 -1
  56. package/dist/pricing.d.ts +59 -2
  57. package/dist/pricing.js +139 -12
  58. package/dist/proxy.d.ts +8 -1
  59. package/dist/proxy.js +13 -1
  60. package/dist/savings.d.ts +5 -1
  61. package/dist/savings.js +11 -5
  62. package/dist/scan.d.ts +3 -1
  63. package/dist/scan.js +8 -1
  64. package/dist/sessionprice.d.ts +5 -0
  65. package/dist/sessionprice.js +5 -1
  66. package/dist/spend.d.ts +86 -3
  67. package/dist/spend.js +240 -23
  68. package/dist/spendplace.d.ts +40 -0
  69. package/dist/spendplace.js +93 -0
  70. package/dist/spendteam.d.ts +160 -0
  71. package/dist/spendteam.js +286 -0
  72. package/dist/starts.d.ts +106 -0
  73. package/dist/starts.js +406 -0
  74. package/dist/statusline.d.ts +2 -2
  75. package/dist/statusline.js +2 -2
  76. package/dist/subagentmodel.js +9 -7
  77. package/dist/subagentpay.d.ts +31 -2
  78. package/dist/subagentpay.js +232 -68
  79. package/dist/subagents.js +3 -3
  80. package/dist/tasks.js +3 -2
  81. package/dist/tooloutput.js +5 -5
  82. package/dist/usagepane.d.ts +77 -0
  83. package/dist/usagepane.js +287 -0
  84. package/package.json +6 -3
package/dist/limits.js CHANGED
@@ -1,16 +1,21 @@
1
1
  /**
2
2
  * `context-doctor limits`: your plan's usage limits, in their own unit.
3
3
  *
4
- * Subscriptions are billed in % of a 5-hour and a weekly window (Claude
5
- * Pro/Max), or in credits per token (Codex since April 2026), and neither
6
- * vendor shows where the percentage went. Two local sources say:
4
+ * Subscriptions are billed in % of a weekly window and, on most plans, a
5
+ * 5-hour one (Claude Pro, Max and Ultra; since 2026-10-30 Max 5x is called
6
+ * Max and Max 20x Ultra, and Ultra has no 5-hour window), or in credits per
7
+ * token (Codex since April 2026), and neither vendor shows where the
8
+ * percentage went. Local sources say:
7
9
  *
8
10
  * - Claude Code hands its status line command `rate_limits.five_hour` and
9
11
  * `.seven_day`, each `{used_percentage, resets_at}` (documented at
10
12
  * code.claude.com/docs/en/statusline; built in 2.1.308 as
11
13
  * Math.round(utilization*1000)/10, so 0.1% steps; present only for
12
- * Pro/Max subscribers, after the first reply). `context-doctor statusline`
13
- * appends each new reading to a small local log (recordLimits).
14
+ * subscribers, after the first reply; `five_hour` absent on Ultra), and
15
+ * the same windows to the plugin's mod (`session.measure`). The status
16
+ * line, the mod and the proxy (from the API's
17
+ * `anthropic-ratelimit-unified-5h-*` / `-7d-*` headers) append each new
18
+ * reading to a small local log (recordLimits).
14
19
  * - Codex records `rate_limits.primary` / `.secondary`
15
20
  * `{used_percent, window_minutes, resets_at}` on every token_count event of
16
21
  * its rollouts (~/.codex/sessions), next to that request's usage, in
@@ -32,15 +37,18 @@ import { codexDir } from "./codexdir.js";
32
37
  import { statePath } from "./ledger.js";
33
38
  import { forEachLine, listSessions, outputSettler, replyCounter, isClaudeSession } from "./session.js";
34
39
  import { subagentFiles } from "./subagents.js";
35
- import { pick, rowsOf, slimUsage } from "./scan.js";
36
- import { isUnbilledModel, NO_MODIFIERS, openAIUsage, requestCost } from "./pricing.js";
40
+ import { pick, prescan, rowsOf, slimUsage } from "./scan.js";
41
+ import { costStateRecord, refusalRecord } from "./ccost.js";
42
+ import { addModifiers, extraIterations, isUnbilledModel, NO_MODIFIERS, openAIUsage, requestCost } from "./pricing.js";
37
43
  import { realModel } from "./tokens.js";
38
44
  import { isCompactionRow, newTrack, slimSummary, trackCompaction } from "./compactcost.js";
45
+ import { PROXY_VERSION } from "./proxy.js";
39
46
  const MIN = 60_000;
40
47
  const HOUR = 60 * MIN;
41
48
  const DAY = 24 * HOUR;
42
49
  /** Claude Code's two windows, as its status line input names them. */
43
50
  export const CLAUDE_WINDOWS = ["five_hour", "seven_day"];
51
+ const SOURCES = ["statusline", "mod", "proxy"];
44
52
  // ---------------------------------------------------------------------------
45
53
  // The Claude readings log, written by the status line
46
54
  // ---------------------------------------------------------------------------
@@ -91,16 +99,18 @@ function parseLogLine(line) {
91
99
  return undefined;
92
100
  if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000)
93
101
  return undefined;
94
- return { ts, app: "claude", w, pct, reset: typeof reset === "number" && Number.isFinite(reset) && reset > 0 ? reset : undefined };
102
+ const src = e.src;
103
+ return { ts, app: "claude", w, pct, reset: typeof reset === "number" && Number.isFinite(reset) && reset > 0 ? reset : undefined, ...(typeof src === "string" && SOURCES.includes(src) ? { src: src } : {}) };
95
104
  }
96
105
  /**
97
106
  * Append what changed in Claude Code's `rate_limits` to the log: a window
98
107
  * whose % or reset time moved since its last line, or that has not been
99
108
  * written for 15 minutes. Nothing when there are no limits (an API key,
100
- * Bedrock, Vertex). Never throws: the status line must stay silent. Returns
101
- * the lines written.
109
+ * Bedrock, Vertex). A window that is not there (Ultra's 5-hour one) is
110
+ * simply not written. Never throws: the status line must stay silent.
111
+ * Returns the lines written.
102
112
  */
103
- export function recordLimits(rateLimits, now = Date.now(), path = limitsLogPath()) {
113
+ export function recordLimits(rateLimits, now = Date.now(), path = limitsLogPath(), source) {
104
114
  if (!rateLimits || typeof rateLimits !== "object")
105
115
  return 0;
106
116
  const fresh = [];
@@ -110,7 +120,7 @@ export function recordLimits(rateLimits, now = Date.now(), path = limitsLogPath(
110
120
  if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000)
111
121
  continue;
112
122
  const reset = typeof r.resets_at === "number" && Number.isFinite(r.resets_at) && r.resets_at > 0 ? Math.round(r.resets_at) : undefined;
113
- fresh.push({ ts: now, app: "claude", w, pct: Math.round(pct * 10) / 10, ...(reset ? { reset } : {}) });
123
+ fresh.push({ ts: now, app: "claude", w, pct: Math.round(pct * 10) / 10, ...(reset ? { reset } : {}), ...(source ? { src: source } : {}) });
114
124
  }
115
125
  if (!fresh.length)
116
126
  return 0;
@@ -169,10 +179,32 @@ export function readClaudeReadings(since = 0, path = limitsLogPath()) {
169
179
  const l = parseLogLine(line);
170
180
  if (!l || l.ts < since)
171
181
  continue;
172
- out.push({ ts: l.ts, app: "claude", window: l.w, pct: l.pct, resetsAt: l.reset ? l.reset * 1000 : undefined, windowMs: l.w === "five_hour" ? 5 * HOUR : 7 * DAY });
182
+ out.push({ ts: l.ts, app: "claude", window: l.w, pct: l.pct, resetsAt: l.reset ? l.reset * 1000 : undefined, windowMs: l.w === "five_hour" ? 5 * HOUR : 7 * DAY, ...(l.src ? { source: l.src } : {}) });
173
183
  }
174
184
  return out.sort((a, b) => a.ts - b.ts);
175
185
  }
186
+ /**
187
+ * The windows an Anthropic response's `anthropic-ratelimit-unified-5h-*` and
188
+ * `-7d-*` headers carry (a claude.ai sign-in, or a gateway), in the status
189
+ * line's shape for recordLimits: utilization is a fraction, the reset epoch
190
+ * seconds. Claude Code reads the same headers into its status line and its
191
+ * mods (Math.round(utilization*1000)/10). Undefined when there are none; a
192
+ * response with only the weekly pair (Ultra) gives only the weekly window.
193
+ */
194
+ export function rateLimitsFromHeaders(get) {
195
+ const out = {};
196
+ for (const [h, w] of [["5h", "five_hour"], ["7d", "seven_day"]]) {
197
+ const raw = get(`anthropic-ratelimit-unified-${h}-utilization`);
198
+ if (raw === null || raw === undefined || raw === "")
199
+ continue;
200
+ const u = Number(raw);
201
+ if (!Number.isFinite(u) || u < 0 || u > 10)
202
+ continue;
203
+ const reset = Number(get(`anthropic-ratelimit-unified-${h}-reset`));
204
+ out[w] = { used_percentage: Math.round(u * 1000) / 10, ...(Number.isFinite(reset) && reset > 0 ? { resets_at: Math.round(reset) } : {}) };
205
+ }
206
+ return Object.keys(out).length ? out : undefined;
207
+ }
176
208
  // ---------------------------------------------------------------------------
177
209
  // Codex: readings and usage, both from its rollouts
178
210
  // ---------------------------------------------------------------------------
@@ -333,17 +365,23 @@ export function codexLimitData(since, root = codexSessionsRoot()) {
333
365
  /**
334
366
  * What the usage fit takes from a Claude Code transcript (subagents' too):
335
367
  * every assistant row with usage, in order. A later row of a reply already
336
- * met keeps only its id and output tokens: it is a repeat, read only for the
337
- * output a streamed reply settles on its last row. `isSidechain` is kept for
338
- * `spend`, which tells a subagent inlined in an older transcript from the
339
- * main thread.
368
+ * met keeps only its id, its output tokens and its billed iterations: it is
369
+ * a repeat, read only for what a streamed reply settles on its last row.
370
+ * `isSidechain` is kept for `spend`, which tells a subagent inlined in an
371
+ * older transcript from the main thread. A request's `usage.iterations` is
372
+ * kept only where some bill beyond its top-level usage (extraIterations).
373
+ * Also Claude Code's own running cost: each `cost-state` row as
374
+ * costStateRecord keeps it, with the Claude Code version of the replies
375
+ * before it (ccost.ts compares it with ours).
340
376
  */
341
377
  export const USAGE_ROWS = {
342
- id: "usage.4",
378
+ id: "usage.5",
343
379
  init: () => ({ ids: {} }),
344
380
  line(line, row, out, st) {
345
381
  const compaction = isCompactionRow(line);
346
- if (!compaction && !line.includes('"usage"'))
382
+ const cost = !compaction && line.startsWith('{"type":"cost-state"');
383
+ const refusal = !compaction && !cost && line.includes('"model_refusal_fallback"');
384
+ if (!compaction && !cost && !refusal && !line.includes('"usage"'))
347
385
  return;
348
386
  let e;
349
387
  try {
@@ -352,6 +390,13 @@ export const USAGE_ROWS = {
352
390
  catch {
353
391
  return;
354
392
  }
393
+ if (cost || refusal) {
394
+ const r = cost ? costStateRecord(e, st.v) : refusalRecord(e);
395
+ if (r)
396
+ out.push(r);
397
+ if (cost || r)
398
+ return;
399
+ }
355
400
  // A compaction's boundary (the context it read) and its summary (the output): what its own request is estimated from (compactcost.ts).
356
401
  if (compaction && e?.type === "system" && e.subtype === "compact_boundary") {
357
402
  out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, compactMetadata: pick(e.compactMetadata ?? {}, ["preTokens"]) }, ["type", "subtype", "uuid", "sessionId", "timestamp", "isSidechain", "compactMetadata"]));
@@ -364,14 +409,18 @@ export const USAGE_ROWS = {
364
409
  const m = e?.message;
365
410
  if (e?.type !== "assistant" || !m?.usage)
366
411
  return;
412
+ if (typeof e.version === "string")
413
+ st.v = e.version.slice(0, 40);
367
414
  if (typeof m.id === "string") {
368
415
  if (st.ids[m.id]) {
369
- out.push({ type: "assistant", message: { id: m.id, usage: pick(m.usage, ["output_tokens"]) } });
416
+ // Its billed iterations too: a streamed reply may settle those on a later row as well.
417
+ const its = slimUsage(m.usage, { iterations: true });
418
+ out.push({ type: "assistant", message: { id: m.id, usage: { ...pick(m.usage, ["output_tokens"]), ...(its?.iterations ? { iterations: its.iterations } : {}) } } });
370
419
  return;
371
420
  }
372
421
  st.ids[m.id] = 1;
373
422
  }
374
- out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, message: pick({ ...m, usage: slimUsage(m.usage) }, ["id", "model", "usage"]) }, ["type", "uuid", "timestamp", "isSidechain", "message"]));
423
+ out.push(pick({ ...e, isSidechain: e.isSidechain === true || undefined, message: pick({ ...m, usage: slimUsage(m.usage, { iterations: true }) }, ["id", "model", "usage"]) }, ["type", "uuid", "timestamp", "isSidechain", "message"]));
375
424
  },
376
425
  };
377
426
  /** A compaction's estimated request as a request point (no message id: its key is the boundary's uuid). */
@@ -383,6 +432,37 @@ export function compactionPoint(c) {
383
432
  ...(c.uuid ? { uuid: c.uuid } : {}), ...(c.sidechain ? { sidechain: true } : {}), ...(c.cost.estimated ? { estimated: true } : {}), ...(c.cost.changedOn ? { changedOn: c.cost.changedOn } : {}),
384
433
  };
385
434
  }
435
+ /** A request's iterations billed beyond its top-level usage, each priced at its own model (the request's when it names none) at `ts`. */
436
+ export function iterationPoints(model, u, ts) {
437
+ return extraIterations(u).map((x) => {
438
+ const m = realModel(x.model ?? model);
439
+ const c = requestCost(m, x.usage, ts);
440
+ return {
441
+ type: x.type, ...(m ? { model: m } : {}),
442
+ input: num(x.usage.input_tokens), read: num(x.usage.cache_read_input_tokens), write: num(x.usage.cache_creation_input_tokens), output: num(x.usage.output_tokens),
443
+ usd: c?.totalUsd ?? 0, promptUsd: c?.promptUsd ?? 0, priced: Boolean(c), modifiers: c ? c.modifiers : { ...NO_MODIFIERS },
444
+ ...(c?.estimated ? { estimated: true } : {}), ...(c?.changedOn ? { changedOn: c.changedOn } : {}),
445
+ };
446
+ });
447
+ }
448
+ /** `p`'s extra iterations set to `extra`, its dollars and modifiers moved by what changed. */
449
+ function setExtra(p, extra) {
450
+ for (const x of p.extra ?? []) {
451
+ p.usd -= x.usd;
452
+ p.promptUsd -= x.promptUsd;
453
+ addModifiers(p.modifiers, negated(x.modifiers));
454
+ }
455
+ if (extra.length)
456
+ p.extra = extra;
457
+ else
458
+ delete p.extra;
459
+ for (const x of extra) {
460
+ p.usd += x.usd;
461
+ p.promptUsd += x.promptUsd;
462
+ addModifiers(p.modifiers, x.modifiers);
463
+ }
464
+ }
465
+ const negated = (m) => ({ fastUsd: -m.fastUsd, geoUsd: -m.geoUsd, longUsd: -m.longUsd, webSearchUsd: -m.webSearchUsd, webSearches: -m.webSearches });
386
466
  /**
387
467
  * The requests of one Claude Code transcript between `since` and `until`,
388
468
  * each reply once, its output settled on its last row (billed at the
@@ -413,11 +493,20 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
413
493
  p.output += more;
414
494
  if (p.rates) {
415
495
  p.usd += (more * p.rates.outputPerM) / 1e6;
416
- // What the modifiers added grows with the output: priced again whole.
417
- if (p.modifiers.fastUsd || p.modifiers.geoUsd || p.modifiers.longUsd)
418
- p.modifiers = requestCost(p.model, { ...known.u, output_tokens: p.output }, p.ts).modifiers;
496
+ // What the modifiers added grows with the output: priced again whole (the iterations' added back).
497
+ if (p.modifiers.fastUsd || p.modifiers.geoUsd || p.modifiers.longUsd) {
498
+ p.modifiers = { ...requestCost(p.model, { ...known.u, output_tokens: p.output }, p.ts).modifiers };
499
+ for (const x of p.extra ?? [])
500
+ addModifiers(p.modifiers, x.modifiers);
501
+ }
419
502
  }
420
503
  }
504
+ // Iterations a later row settles on (an advisor's call, once it ran): priced again, replacing the earlier ones.
505
+ if (known && m.usage.iterations) {
506
+ const extra = iterationPoints(known.point.model, { ...known.u, iterations: m.usage.iterations }, known.point.ts);
507
+ if (JSON.stringify(extra) !== JSON.stringify(known.point.extra ?? []))
508
+ setExtra(known.point, extra);
509
+ }
421
510
  return;
422
511
  }
423
512
  if (seen !== "new")
@@ -450,6 +539,10 @@ export function claudeFileUsage(file, since, until = Infinity, runRows) {
450
539
  if (c.changedOn)
451
540
  point.changedOn = c.changedOn;
452
541
  }
542
+ // The iterations its top-level usage leaves out, each at its own model (counted even when the request's own model has no price).
543
+ const extra = iterationPoints(point.model, u, ts);
544
+ if (extra.length)
545
+ setExtra(point, extra);
453
546
  out.push(point);
454
547
  if (typeof m.id === "string")
455
548
  byId.set(m.id, { point, u });
@@ -477,16 +570,88 @@ export function claudeUsageFiles(since, tops) {
477
570
  }
478
571
  /** How long before a period a session may have been last written and still have subagents running into it. */
479
572
  export const SUBAGENT_LOOKBACK_MS = 2 * 86_400_000;
573
+ /** A Claude Code entrypoint or version as a report may show it: a short token, never free text. */
574
+ const ENTRYPOINT = /^[a-z][\w.-]{0,39}$/i;
575
+ const VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,6}(?:[-+][\w.]{1,20})?$/;
576
+ /**
577
+ * Which Claude Code wrote a transcript, and when that changed: every row
578
+ * carries `entrypoint` ("cli", "claude-desktop", "sdk-cli" for `claude -p`,
579
+ * "claude-vscode"...) and `version`; a record is kept only where either
580
+ * changes (a session resumed after an update), so a file has one or two.
581
+ */
582
+ export const HOST_ROWS = {
583
+ id: "host.1",
584
+ init: () => ({}),
585
+ line(line, row, out, st) {
586
+ if (!line.includes('"entrypoint"') && !line.includes('"version"'))
587
+ return;
588
+ let e;
589
+ try {
590
+ e = row();
591
+ }
592
+ catch {
593
+ return;
594
+ }
595
+ const ep = typeof e?.entrypoint === "string" && ENTRYPOINT.test(e.entrypoint) ? e.entrypoint : undefined;
596
+ const v = typeof e?.version === "string" && VERSION.test(e.version) ? e.version : undefined;
597
+ if ((!ep || ep === st.ep) && (!v || v === st.v))
598
+ return;
599
+ if (ep)
600
+ st.ep = ep;
601
+ if (v)
602
+ st.v = v;
603
+ const ts = Date.parse(String(e.timestamp ?? ""));
604
+ out.push({ ts: Number.isFinite(ts) ? ts : 0, ...(st.ep ? { ep: st.ep } : {}), ...(st.v ? { v: st.v } : {}) });
605
+ },
606
+ };
607
+ /** Each request's entrypoint and version: the transcript's own as of the request, else (a subagent's file with none) its session's. */
608
+ function stampHost(points, hosts, fallback) {
609
+ let h = 0;
610
+ for (const p of points) {
611
+ while (h + 1 < hosts.length && hosts[h + 1].ts <= p.ts)
612
+ h++;
613
+ const at = hosts[h] ?? fallback;
614
+ if (!at)
615
+ continue;
616
+ if (at.ep)
617
+ p.entrypoint = at.ep;
618
+ if (at.v)
619
+ p.version = at.v;
620
+ }
621
+ }
480
622
  /**
481
623
  * Every Claude Code request between `since` and `until`, main threads and
482
- * subagents alike (both draw on the same limits), each reply once.
624
+ * subagents alike (both draw on the same limits), each reply once, with
625
+ * the entrypoint and Claude Code version it was made from.
483
626
  */
484
627
  export function claudeUsage(since, until = Infinity, paths) {
485
628
  const out = [];
486
629
  const runRows = new Set();
487
- for (const { file } of claudeUsageFiles(since, paths)) {
630
+ const files = claudeUsageFiles(since, paths);
631
+ // One read of each transcript for both extractors.
632
+ prescan([{ paths: files.map((f) => f.file), extractors: [USAGE_ROWS, HOST_ROWS] }]);
633
+ const topHost = new Map();
634
+ for (const { file, top, subagent } of files) {
488
635
  try {
489
- out.push(...claudeFileUsage(file, since, until, runRows));
636
+ const points = claudeFileUsage(file, since, until, runRows);
637
+ let hosts = [];
638
+ try {
639
+ hosts = rowsOf(file, HOST_ROWS);
640
+ }
641
+ catch { /* no host: the points go unstamped */ }
642
+ if (!subagent && hosts.length)
643
+ topHost.set(top, hosts[0]);
644
+ // A subagent's file with no host of its own takes its session's (read here when the session itself is outside the period).
645
+ if (subagent && !hosts.length && !topHost.has(top)) {
646
+ try {
647
+ topHost.set(top, rowsOf(top, HOST_ROWS)[0]);
648
+ }
649
+ catch {
650
+ topHost.set(top, undefined);
651
+ }
652
+ }
653
+ stampHost(points, hosts, topHost.get(top));
654
+ out.push(...points);
490
655
  }
491
656
  catch {
492
657
  /* skip an unreadable transcript */
@@ -576,7 +741,10 @@ export function windowStatus(readings, now = Date.now()) {
576
741
  if (last.ts - start >= 10 * MIN)
577
742
  status.averagePerHour = Math.max(0, (last.pct / (last.ts - start)) * HOUR);
578
743
  }
579
- if (status.recentPerHour && status.recentPerHour > 0 && last.pct < 100) {
744
+ // A reading older than the pace's own stretch says nothing about now: no run-out time from it (it could already be past).
745
+ if (now - last.ts > lookback)
746
+ status.stale = true;
747
+ if (!status.stale && status.recentPerHour && status.recentPerHour > 0 && last.pct < 100) {
580
748
  status.runsOutAt = last.ts + ((100 - last.pct) / status.recentPerHour) * HOUR;
581
749
  status.beforeReset = last.resetsAt === undefined || status.runsOutAt < last.resetsAt;
582
750
  }
@@ -855,6 +1023,320 @@ export function fitWindow(readings, usage, stretchMs) {
855
1023
  fit.usable = true;
856
1024
  return fit;
857
1025
  }
1026
+ /** A window's figure is quoted from this many stretches and this many points matched by usage here. */
1027
+ const MIN_RESET_STRETCHES = 3;
1028
+ const MIN_RESET_PCT = 1;
1029
+ /** Above this relative error the figure is too loose to compare. */
1030
+ const MAX_RESET_REL_SE = 0.25;
1031
+ /** A move is reported from 1.5x either way, and only beyond this many standard errors (more inside a window, where the split is searched for). */
1032
+ const MIN_FACTOR = 1.5;
1033
+ const RESET_SIGMA = 3;
1034
+ const WITHIN_SIGMA = 4;
1035
+ /** Each side of a split inside a window holds at least this many stretches. */
1036
+ const MIN_SIDE = 4;
1037
+ /** A key with under this share of a window's dollars is pooled into "other". */
1038
+ const MIN_KEY_SHARE = 0.05;
1039
+ /** A key's own figure is quoted under this relative error. */
1040
+ const MAX_KEY_REL_SE = 0.3;
1041
+ /** Windows this long or longer are fitted per reset (Claude's weekly; Codex's weekly and monthly). */
1042
+ const PER_RESET_MIN_MS = 7 * DAY - HOUR;
1043
+ /** Ratio of sums, sum(u) / sum(d), and its relative standard error (the ratio estimator's, across stretches). */
1044
+ function ratio(u, d) {
1045
+ const n = u.length;
1046
+ const su = u.reduce((a, v) => a + v, 0), sd = d.reduce((a, v) => a + v, 0);
1047
+ if (!(sd > 0) || !(su > 0))
1048
+ return undefined;
1049
+ const r = su / sd;
1050
+ if (n < 2)
1051
+ return { r, relSe: Infinity };
1052
+ const dbar = sd / n;
1053
+ const s2 = u.reduce((a, v, i) => a + (v - r * d[i]) ** 2, 0) / (n - 1);
1054
+ return { r, relSe: Math.sqrt(s2 / n) / dbar / r };
1055
+ }
1056
+ /** Least squares through the origin with each coefficient's standard error; undefined when singular or with too few rows. */
1057
+ function olsSe(rows, y) {
1058
+ const n = rows.length, k = rows[0]?.length ?? 0;
1059
+ if (!k || n <= k + 1)
1060
+ return undefined;
1061
+ // [XᵀX | I], inverted in place by Gauss-Jordan.
1062
+ const a = Array.from({ length: k }, (_, p) => [...Array.from({ length: k }, (_, q) => rows.reduce((s, r) => s + r[p] * r[q], 0)), ...Array.from({ length: k }, (_, q) => (p === q ? 1 : 0))]);
1063
+ for (let c = 0; c < k; c++) {
1064
+ let piv = c;
1065
+ for (let r = c + 1; r < k; r++)
1066
+ if (Math.abs(a[r][c]) > Math.abs(a[piv][c]))
1067
+ piv = r;
1068
+ if (Math.abs(a[piv][c]) < 1e-12 * Math.max(1e-300, ...a.map((row) => Math.abs(row[c]))))
1069
+ return undefined;
1070
+ [a[c], a[piv]] = [a[piv], a[c]];
1071
+ const d = a[c][c];
1072
+ for (let q = 0; q < 2 * k; q++)
1073
+ a[c][q] /= d;
1074
+ for (let r = 0; r < k; r++) {
1075
+ if (r === c)
1076
+ continue;
1077
+ const f = a[r][c];
1078
+ for (let q = 0; q < 2 * k; q++)
1079
+ a[r][q] -= f * a[c][q];
1080
+ }
1081
+ }
1082
+ const inv = a.map((row) => row.slice(k));
1083
+ const xty = Array.from({ length: k }, (_, p) => rows.reduce((s, r, i) => s + r[p] * y[i], 0));
1084
+ const coef = inv.map((row) => row.reduce((s, v, q) => s + v * xty[q], 0));
1085
+ const sse = rows.reduce((s, r, i) => s + (y[i] - r.reduce((t, v, j) => t + v * coef[j], 0)) ** 2, 0);
1086
+ const s2 = sse / (n - k);
1087
+ return { coef, se: inv.map((row, j) => Math.sqrt(Math.max(0, s2 * row[j]))) };
1088
+ }
1089
+ const tokensOf = (p) => p.input + p.read + p.write + p.output;
1090
+ /**
1091
+ * Shares by `keyOf` over the stretches, and, with two keys or more and
1092
+ * enough stretches, each key's own dollars per 1%: the rise in each stretch
1093
+ * fitted on each key's dollars in it. A key's figure is kept only when it is
1094
+ * known to ±30%; a single key's figure is the window's own.
1095
+ */
1096
+ function splitBy(segments, inSeg, keyOf, whole) {
1097
+ const totals = new Map();
1098
+ let all = 0;
1099
+ for (const pts of inSeg)
1100
+ for (const p of pts) {
1101
+ const k = keyOf(p);
1102
+ const t = totals.get(k) ?? totals.set(k, { key: k, usd: 0, tokens: 0, requests: 0, share: 0 }).get(k);
1103
+ t.usd += p.usd;
1104
+ t.tokens += tokensOf(p);
1105
+ t.requests++;
1106
+ all += p.usd;
1107
+ }
1108
+ let list = [...totals.values()].sort((a, b) => b.usd - a.usd);
1109
+ // Small keys pooled, so the fit has a column only for what can be told apart.
1110
+ const small = list.filter((t) => all > 0 && t.usd / all < MIN_KEY_SHARE);
1111
+ if (small.length > 1) {
1112
+ const other = { key: "other", usd: 0, tokens: 0, requests: 0, share: 0 };
1113
+ for (const t of small) {
1114
+ other.usd += t.usd;
1115
+ other.tokens += t.tokens;
1116
+ other.requests += t.requests;
1117
+ }
1118
+ list = [...list.filter((t) => !small.includes(t)), other];
1119
+ }
1120
+ for (const t of list)
1121
+ t.share = all > 0 ? t.usd / all : 0;
1122
+ if (list.length === 1 && whole) {
1123
+ list[0].usdPerPct = whole.r;
1124
+ list[0].relSe = whole.relSe;
1125
+ }
1126
+ else if (list.length > 1 && segments.length >= MIN_SEGMENTS) {
1127
+ const col = new Map(list.map((t, i) => [t.key, i]));
1128
+ const otherCol = col.get("other");
1129
+ const rows = inSeg.map((pts) => {
1130
+ const r = new Array(list.length).fill(0);
1131
+ for (const p of pts)
1132
+ r[col.get(keyOf(p)) ?? otherCol ?? 0] += p.usd;
1133
+ return r;
1134
+ });
1135
+ const fit = olsSe(rows, segments.map((s) => s.dpct));
1136
+ if (fit)
1137
+ list.forEach((t, j) => {
1138
+ const k = fit.coef[j], se = fit.se[j];
1139
+ if (k > 0 && se / k <= MAX_KEY_REL_SE) {
1140
+ t.usdPerPct = 1 / k;
1141
+ t.relSe = se / k;
1142
+ }
1143
+ });
1144
+ }
1145
+ return list;
1146
+ }
1147
+ /** One window's readings cut at each reset: the periods, oldest first. */
1148
+ function periodsOf(readings) {
1149
+ const clean = cleanReadings(readings);
1150
+ const res = resolutionOf(clean);
1151
+ const out = [];
1152
+ for (const r of clean) {
1153
+ const cur = out[out.length - 1];
1154
+ if (cur && samePeriod(cur[cur.length - 1], r, res))
1155
+ cur.push(r);
1156
+ else
1157
+ out.push([r]);
1158
+ }
1159
+ return out;
1160
+ }
1161
+ /**
1162
+ * Each reset window of one weekly window's readings: % used, dollars and
1163
+ * tokens per 1% (over the stretches with usage here; rises with none are
1164
+ * counted apart), the split by entrypoint and by model, and the Claude Code
1165
+ * versions. `usage` in time order.
1166
+ */
1167
+ export function resetWindowsOf(readings, usage, opts = {}) {
1168
+ const now = opts.now ?? Date.now();
1169
+ const out = [];
1170
+ for (const period of periodsOf(readings)) {
1171
+ const first = period[0], last = period[period.length - 1];
1172
+ const windowMs = last.windowMs ?? 7 * DAY;
1173
+ const resetsAt = last.resetsAt ?? first.ts + windowMs;
1174
+ const { segments, elsewherePct } = segmentsOf(period, usage, opts.stretchMs);
1175
+ // The requests of each stretch: both lists are in time order.
1176
+ const inSeg = segments.map(() => []);
1177
+ let g = 0;
1178
+ for (const p of usage) {
1179
+ while (g < segments.length && segments[g].to < p.ts)
1180
+ g++;
1181
+ if (g >= segments.length)
1182
+ break;
1183
+ if (p.ts > segments[g].from)
1184
+ inSeg[g].push(p);
1185
+ }
1186
+ const usd = segments.reduce((a, s) => a + s.usd, 0);
1187
+ const tokens = inSeg.reduce((a, pts) => a + pts.reduce((b, p) => b + tokensOf(p), 0), 0);
1188
+ const pctMatched = segments.reduce((a, s) => a + s.dpct, 0);
1189
+ const w = {
1190
+ window: last.window,
1191
+ label: windowLabel(last.window, last.windowMs),
1192
+ app: last.app,
1193
+ start: resetsAt - windowMs,
1194
+ resetsAt,
1195
+ current: resetsAt > now,
1196
+ readings: period.length,
1197
+ firstReading: first.ts,
1198
+ lastReading: last.ts,
1199
+ pctUsed: Math.max(...period.map((r) => r.pct)),
1200
+ pctMatched,
1201
+ pctElsewhere: elsewherePct,
1202
+ stretches: segments.length,
1203
+ requests: segments.reduce((a, s) => a + s.requests, 0),
1204
+ usd,
1205
+ tokens,
1206
+ byEntrypoint: [],
1207
+ byModel: [],
1208
+ versions: [],
1209
+ };
1210
+ const fit = ratio(segments.map((s) => s.usd), segments.map((s) => s.dpct));
1211
+ if (segments.length < MIN_RESET_STRETCHES)
1212
+ w.why = `${segments.length} stretch${segments.length === 1 ? "" : "es"} of readings with usage here; ${MIN_RESET_STRETCHES} make a figure`;
1213
+ else if (pctMatched < MIN_RESET_PCT)
1214
+ w.why = `the limit rose ${pts(pctMatched)} points beside usage here; ${MIN_RESET_PCT} make a figure`;
1215
+ else if (!fit || !(usd > 0))
1216
+ w.why = "no priced usage beside the rises";
1217
+ else {
1218
+ w.usdPerPct = fit.r;
1219
+ w.tokensPerPct = tokens / pctMatched;
1220
+ w.relSe = fit.relSe;
1221
+ if (!(fit.relSe <= MAX_RESET_REL_SE))
1222
+ w.why = `known only to ±${Number.isFinite(fit.relSe) ? Math.round(fit.relSe * 100) : "∞"}%: the rises follow the usage here loosely`;
1223
+ }
1224
+ const quoted = w.usdPerPct !== undefined && !w.why ? fit : undefined;
1225
+ w.byEntrypoint = splitBy(segments, inSeg, (p) => p.entrypoint ?? (p.app === "codex" ? "codex" : "unknown"), quoted);
1226
+ w.byModel = splitBy(segments, inSeg, (p) => reportModel(p.model), quoted);
1227
+ w.versions = [...new Set(inSeg.flat().map((p) => p.version).filter((v) => !!v))].sort(compareVersions);
1228
+ out.push(w);
1229
+ }
1230
+ return out;
1231
+ }
1232
+ /** "2.1.9" before "2.1.10". */
1233
+ function compareVersions(a, b) {
1234
+ const pa = a.split(/[.-]/).map(Number), pb = b.split(/[.-]/).map(Number);
1235
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
1236
+ const d = (pa[i] || 0) - (pb[i] || 0);
1237
+ if (d)
1238
+ return d;
1239
+ }
1240
+ return a.localeCompare(b);
1241
+ }
1242
+ /**
1243
+ * A model id as a report may carry it: a model's name, never a cloud
1244
+ * resource (a Bedrock ARN holds an account number) or anything path-shaped.
1245
+ */
1246
+ export function reportModel(model) {
1247
+ if (!model)
1248
+ return "unknown";
1249
+ if (!/^[a-z][\w.:@[\]-]{0,59}$/i.test(model) || /^arn:/i.test(model) || /\d{8,}/.test(model))
1250
+ return "custom model id";
1251
+ return model;
1252
+ }
1253
+ /** The two sides of a move, each a ratio with its error: how many standard errors apart (log scale). */
1254
+ function sigmaOf(a, b, factor) {
1255
+ const se = Math.sqrt(a.relSe ** 2 + b.relSe ** 2);
1256
+ return se > 0 ? Math.abs(Math.log(factor)) / se : Infinity;
1257
+ }
1258
+ /**
1259
+ * Where what 1% costs moved: between consecutive windows that each have a
1260
+ * figure (dated at the reset), and inside a window at the one split of its
1261
+ * stretches that separates two rates best (dated at that stretch). Reported
1262
+ * from a 1.5x move either way, beyond 3 standard errors between windows and
1263
+ * 4 inside one (the split is searched for).
1264
+ */
1265
+ export function slopeChanges(windows, usage = [], readings = [], stretchMs) {
1266
+ const out = [];
1267
+ const quoted = windows.filter((w) => w.usdPerPct !== undefined && w.relSe !== undefined && Number.isFinite(w.relSe) && !w.why);
1268
+ for (let i = 1; i < quoted.length; i++) {
1269
+ const a = quoted[i - 1], b = quoted[i];
1270
+ if (a.window !== b.window)
1271
+ continue;
1272
+ const factor = b.usdPerPct / a.usdPerPct;
1273
+ const sigma = sigmaOf({ relSe: a.relSe }, { relSe: b.relSe }, factor);
1274
+ if (Math.max(factor, 1 / factor) < MIN_FACTOR || sigma < RESET_SIGMA)
1275
+ continue;
1276
+ out.push({
1277
+ window: b.window, label: b.label, kind: "reset", at: b.start, prevEnd: a.resetsAt,
1278
+ usdPerPctBefore: a.usdPerPct, usdPerPctAfter: b.usdPerPct, tokensPerPctBefore: a.tokensPerPct, tokensPerPctAfter: b.tokensPerPct,
1279
+ factor, sigma, versionsBefore: a.versions, versionsAfter: b.versions,
1280
+ });
1281
+ }
1282
+ // Inside a window: its own stretches again, split once where two rates fit best.
1283
+ const periods = readings.length ? periodsOf(readings) : [];
1284
+ // Every window with a figure, loose ones too: a move inside a window is what makes its figure loose.
1285
+ for (const w of windows.filter((x) => x.usdPerPct !== undefined)) {
1286
+ const period = periods.find((p) => p[0].ts === w.firstReading && p[p.length - 1].ts === w.lastReading);
1287
+ if (!period)
1288
+ continue;
1289
+ const segs = segmentsOf(period, usage, stretchMs).segments;
1290
+ if (segs.length < 2 * MIN_SIDE)
1291
+ continue;
1292
+ const u = segs.map((s) => s.usd), d = segs.map((s) => s.dpct);
1293
+ const sse = (from, to) => {
1294
+ const r = ratio(u.slice(from, to), d.slice(from, to));
1295
+ return r ? u.slice(from, to).reduce((a, v, i) => a + (v - r.r * d[from + i]) ** 2, 0) : Infinity;
1296
+ };
1297
+ let best;
1298
+ for (let s = MIN_SIDE; s <= segs.length - MIN_SIDE; s++) {
1299
+ const cost = sse(0, s) + sse(s, segs.length);
1300
+ if (!best || cost < best.cost)
1301
+ best = { at: s, cost };
1302
+ }
1303
+ if (!best)
1304
+ continue;
1305
+ const before = ratio(u.slice(0, best.at), d.slice(0, best.at)), after = ratio(u.slice(best.at), d.slice(best.at));
1306
+ if (!before || !after)
1307
+ continue;
1308
+ const factor = after.r / before.r;
1309
+ const sigma = sigmaOf(before, after, factor);
1310
+ if (Math.max(factor, 1 / factor) < MIN_FACTOR || sigma < WITHIN_SIGMA)
1311
+ continue;
1312
+ const tok = (from, to) => {
1313
+ const t = usage.filter((p) => p.ts > segs[from].from && p.ts <= segs[to - 1].to).reduce((a, p) => a + tokensOf(p), 0);
1314
+ const pct = d.slice(from, to).reduce((a, v) => a + v, 0);
1315
+ return pct > 0 ? t / pct : undefined;
1316
+ };
1317
+ const vers = (from, to) => [...new Set(usage.filter((p) => p.ts > segs[from].from && p.ts <= segs[to - 1].to).map((p) => p.version).filter((v) => !!v))].sort(compareVersions);
1318
+ out.push({
1319
+ window: w.window, label: w.label, kind: "within", at: segs[best.at].from,
1320
+ usdPerPctBefore: before.r, usdPerPctAfter: after.r, tokensPerPctBefore: tok(0, best.at), tokensPerPctAfter: tok(best.at, segs.length),
1321
+ factor, sigma, versionsBefore: vers(0, best.at), versionsAfter: vers(best.at, segs.length),
1322
+ });
1323
+ }
1324
+ return out.sort((a, b) => a.at - b.at);
1325
+ }
1326
+ /** Every weekly window's resets and the moves between them, for one app's readings and usage. */
1327
+ function perReset(readings, usage, now) {
1328
+ const resets = [];
1329
+ const changes = [];
1330
+ for (const [, rs] of byWindow(readings)) {
1331
+ const ms = rs[rs.length - 1]?.windowMs ?? 0;
1332
+ if (ms < PER_RESET_MIN_MS)
1333
+ continue;
1334
+ const ws = resetWindowsOf(rs, usage, { now });
1335
+ resets.push(...ws);
1336
+ changes.push(...slopeChanges(ws, usage, rs));
1337
+ }
1338
+ return { resets, changes };
1339
+ }
858
1340
  function byWindow(readings) {
859
1341
  const m = new Map();
860
1342
  for (const r of readings) {
@@ -879,6 +1361,11 @@ export function limitsReport(days = 30, opts = {}) {
879
1361
  const fits = [];
880
1362
  // Claude usage is read only when there are readings to fit it against, and only over their span.
881
1363
  const claudeUse = claude.length >= 2 ? claudeUsage(claude[0].ts - HOUR, claude[claude.length - 1].ts, opts.claudePaths) : [];
1364
+ const claudeReset = perReset(claude, claudeUse, now);
1365
+ const codexReset = perReset(codex.readings, codex.usage, now);
1366
+ const claudeSources = {};
1367
+ for (const r of claude)
1368
+ claudeSources[r.source ?? "earlier"] = (claudeSources[r.source ?? "earlier"] ?? 0) + 1;
882
1369
  for (const [, rs] of byWindow(claude)) {
883
1370
  const s = windowStatus(rs, now);
884
1371
  if (s)
@@ -895,7 +1382,24 @@ export function limitsReport(days = 30, opts = {}) {
895
1382
  if (f)
896
1383
  fits.push(f);
897
1384
  }
898
- return { days, now, claudeLog: logPath, claudeReadings: claude.length, codexReadings: codex.readings.length, windows, fits };
1385
+ return {
1386
+ days, now, claudeLog: logPath, claudeReadings: claude.length, codexReadings: codex.readings.length, windows, fits,
1387
+ resets: [...claudeReset.resets, ...codexReset.resets],
1388
+ changes: [...claudeReset.changes, ...codexReset.changes],
1389
+ claudeWindows: CLAUDE_WINDOWS.filter((w) => claude.some((r) => r.window === w)),
1390
+ claudeSources,
1391
+ };
1392
+ }
1393
+ /**
1394
+ * The per-reset view of the limits, for a pane or a script: every window's
1395
+ * current state, every weekly window with its dollars and tokens per 1%
1396
+ * (by entrypoint and model where the readings allow) and every move in that
1397
+ * figure, dated. Reads the limits ledger, Codex's rollouts and the
1398
+ * transcripts over the readings' span; never writes.
1399
+ */
1400
+ export function limitsByReset(days = 30, opts = {}) {
1401
+ const r = limitsReport(days, opts);
1402
+ return { now: r.now, windows: r.windows, resets: r.resets, changes: r.changes, noFiveHour: r.claudeWindows.length === 1 && r.claudeWindows[0] === "seven_day", readings: r.claudeReadings + r.codexReadings };
899
1403
  }
900
1404
  /** The Claude fit to quote savings in: the weekly window first (savings are weekly), then the 5-hour one. */
901
1405
  export function claudeLimitFit(r) {
@@ -953,10 +1457,60 @@ function clock(ms, now) {
953
1457
  return Math.abs(ms - now) < 20 * HOUR ? t : `${d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" })} ${t}`;
954
1458
  }
955
1459
  const pts = (v) => (v >= 10 ? Math.round(v).toString() : v >= 1 ? v.toFixed(1) : v.toFixed(2));
1460
+ /**
1461
+ * The one line that says how to start recording Claude readings: the
1462
+ * plugin's mod (after each turn, in the Desktop app, the terminal and VS
1463
+ * Code), or the autopilot proxy (from the API's rate-limit headers).
1464
+ */
1465
+ export const HOW_TO_RECORD = "To record them: `context-doctor install` (the plugin's mod writes them after each turn, Claude Code 2.1.286+; `install --statusline` on older ones), or `context-doctor autopilot on` (its proxy reads them from the API's replies).";
1466
+ /** "2026-11-03" and "2026-11-03 14:00 UTC": the same date for whoever reads a pasted report. */
1467
+ const utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
1468
+ const utcMinute = (ms) => `${new Date(ms).toISOString().slice(0, 16).replace("T", " ")} UTC`;
1469
+ /** "$25.10", "$4.02", "$130". */
1470
+ const dollars = (v) => (v >= 100 ? `$${Math.round(v)}` : `$${v.toFixed(2)}`);
1471
+ /** "21.0M", "450k". */
1472
+ const tokenCount = (v) => (v >= 1e6 ? `${(v / 1e6).toFixed(1)}M` : v >= 1e3 ? `${Math.round(v / 1e3)}k` : String(Math.round(v)));
1473
+ const plusMinus = (relSe) => (relSe !== undefined && Number.isFinite(relSe) ? ` ±${Math.max(1, Math.round(relSe * 100))}%` : "");
1474
+ /** "2.1.321", "2.1.321 to 2.1.325 (3)". */
1475
+ const versionSpan = (vs) => (!vs.length ? "unknown" : vs.length === 1 ? vs[0] : `${vs[0]} to ${vs[vs.length - 1]}${vs.length > 2 ? ` (${vs.length})` : ""}`);
1476
+ /** "claude-desktop 88%, cli 12%". */
1477
+ const sharesLine = (list) => list.map((t) => `${t.key} ${Math.round(t.share * 100)}%`).join(", ");
1478
+ /** Two windows of the same kind with a figure each: something to compare. */
1479
+ const comparable = (ws) => {
1480
+ const seen = new Map();
1481
+ for (const w of ws)
1482
+ if (w.usdPerPct !== undefined && !w.why)
1483
+ seen.set(w.window, (seen.get(w.window) ?? 0) + 1);
1484
+ return [...seen.values()].some((n) => n > 1);
1485
+ };
1486
+ /** Two keys or more with a real share of the dollars: a split worth a line. */
1487
+ const mixed = (list) => list.filter((t) => t.share >= MIN_KEY_SHARE).length >= 2;
1488
+ /** A move in words: when, from what to what, how many times, and the Claude Code versions either side. */
1489
+ function changeLine(c) {
1490
+ const when = c.kind === "reset"
1491
+ ? c.prevEnd !== undefined && Math.abs(c.prevEnd - c.at) > SAME_RESET_MS
1492
+ ? `between the reset of ${utcMinute(c.prevEnd)} and the window from ${utcMinute(c.at)}`
1493
+ : `at the reset of ${utcMinute(c.at)}`
1494
+ : `within the window, around ${utcMinute(c.at)}`;
1495
+ const times = c.factor < 1 ? `${(1 / c.factor).toFixed(1)}x less use per 1%: the limit drains faster` : `${c.factor.toFixed(1)}x more use per 1%: the limit drains slower`;
1496
+ const tok = c.tokensPerPctBefore !== undefined && c.tokensPerPctAfter !== undefined ? `; tokens per 1% ${tokenCount(c.tokensPerPctBefore)} to ${tokenCount(c.tokensPerPctAfter)}` : "";
1497
+ const ver = versionSpan(c.versionsBefore) !== versionSpan(c.versionsAfter) ? `; Claude Code ${versionSpan(c.versionsBefore)} before, ${versionSpan(c.versionsAfter)} after` : "";
1498
+ return `${c.label}, ${when}: 1% went from ${dollars(c.usdPerPctBefore)} to ${dollars(c.usdPerPctAfter)} of API-equivalent use (${times})${tok}${ver}.`;
1499
+ }
1500
+ /** Each key's own dollars per 1%, where the fit told them apart: "sdk-cli $13.90 ±9%, cli $25.00 ±7% (sdk-cli drains 1.8x per dollar)". */
1501
+ function splitLine(list) {
1502
+ const known = list.filter((t) => t.usdPerPct !== undefined);
1503
+ if (known.length < 2)
1504
+ return undefined;
1505
+ const sorted = [...known].sort((a, b) => a.usdPerPct - b.usdPerPct);
1506
+ const fast = sorted[0], slow = sorted[sorted.length - 1];
1507
+ const ratio = slow.usdPerPct / fast.usdPerPct;
1508
+ return `${sorted.map((t) => `${t.key} ${dollars(t.usdPerPct)}${plusMinus(t.relSe)}`).join(", ")} per 1%${ratio >= 1.1 ? ` (${fast.key} drains ${ratio.toFixed(1)}x per dollar against ${slow.key})` : ""}`;
1509
+ }
956
1510
  export function renderLimits(r) {
957
1511
  const out = ["USAGE LIMITS", "═".repeat(60)];
958
- if (!r.windows.length) {
959
- out.push("No limit readings yet.", "", "Claude (Pro and Max): `context-doctor statusline` records the 5-hour and weekly", "windows as Claude Code reports them. Set it up with", " context-doctor install --statusline", `(or keep your own status line and pipe its input to it too). Readings: ${r.claudeLog.replace(homedir(), "~")}`, "Codex: read from ~/.codex/sessions; none found in the period.");
1512
+ if (!r.windows.length && !r.resets.length) {
1513
+ out.push(`No limit readings yet. ${HOW_TO_RECORD}`, "", `Claude readings are kept in ${r.claudeLog.replace(homedir(), "~")}; Codex's are read from ~/.codex/sessions (none in the period).`);
960
1514
  return out.join("\n");
961
1515
  }
962
1516
  for (const s of r.windows) {
@@ -968,7 +1522,9 @@ export function renderLimits(r) {
968
1522
  }
969
1523
  if (s.resetsAt)
970
1524
  out.push(` Resets ${clock(s.resetsAt, r.now)} (in ${hm(s.resetsAt - r.now)}).`);
971
- if (s.recentPerHour === undefined)
1525
+ if (s.stale)
1526
+ out.push(` The newest reading is ${hm(age)} old: no pace or run-out time from it until a new one comes in.`);
1527
+ else if (s.recentPerHour === undefined)
972
1528
  out.push(" Pace: not enough recent readings.");
973
1529
  else if (s.recentPerHour === 0)
974
1530
  out.push(" Pace: no rise over the recent readings.");
@@ -982,6 +1538,43 @@ export function renderLimits(r) {
982
1538
  }
983
1539
  }
984
1540
  }
1541
+ if (r.claudeWindows.length === 1 && r.claudeWindows[0] === "seven_day") {
1542
+ out.push("", "No 5-hour window in Claude's readings: a plan without one (Ultra), so the weekly window is the limit.");
1543
+ }
1544
+ if (r.resets.length) {
1545
+ out.push("", "Each weekly (or longer) window, reset to reset: API-equivalent use per 1% (UTC dates)");
1546
+ out.push("─".repeat(60));
1547
+ for (const w of r.resets) {
1548
+ const head = `${w.label}, ${utcDay(w.start)} to ${utcDay(w.resetsAt)}${w.current ? " (now)" : ""}: ${pts(w.pctUsed)}% used`;
1549
+ if (w.usdPerPct !== undefined && !w.why)
1550
+ out.push(`${head}; ${dollars(w.usdPerPct)} per 1%${plusMinus(w.relSe)}, ${tokenCount(w.tokensPerPct ?? 0)} tokens per 1%`);
1551
+ else
1552
+ out.push(`${head}; no figure: ${w.why}`);
1553
+ if (w.pctElsewhere > 0)
1554
+ out.push(` ${pts(w.pctElsewhere)} points rose with no usage here (used elsewhere), left out.`);
1555
+ if (w.byEntrypoint.length)
1556
+ out.push(` By entrypoint (share of dollars): ${sharesLine(w.byEntrypoint)}`);
1557
+ const ep = splitLine(w.byEntrypoint);
1558
+ if (ep)
1559
+ out.push(` ${ep}`);
1560
+ if (mixed(w.byModel))
1561
+ out.push(` By model: ${sharesLine(w.byModel)}`);
1562
+ const md = splitLine(w.byModel);
1563
+ if (md)
1564
+ out.push(` ${md}`);
1565
+ if (w.versions.length)
1566
+ out.push(` Claude Code ${versionSpan(w.versions)}`);
1567
+ }
1568
+ if (r.changes.length) {
1569
+ out.push("", "What 1% buys moved:");
1570
+ for (const c of r.changes)
1571
+ out.push(` ${changeLine(c)}`);
1572
+ }
1573
+ else if (comparable(r.resets)) {
1574
+ out.push("", "What 1% buys held steady across these windows (no move of 1.5x or more beyond the error).");
1575
+ }
1576
+ out.push("`context-doctor limits --report` prints this as a block to paste into a bug report.");
1577
+ }
985
1578
  out.push("", "What 1M tokens cost in each limit (fitted on your own readings)");
986
1579
  out.push("─".repeat(60));
987
1580
  for (const f of r.fits) {
@@ -998,7 +1591,65 @@ export function renderLimits(r) {
998
1591
  out.push(` rate known to ±${Math.round((f.byPrice.relSe ?? 0) * 100)}%; explains ${Math.round(Math.max(0, f.byPrice.r2) * 100)}% of the rises; predicts each within ±${pts(f.byPrice.looRmse)} points (${Math.round(f.byPrice.relError * 100)}%)`);
999
1592
  }
1000
1593
  out.push(f.usable ? " Good enough to show savings in this limit (savings, cache-misses, compact-window)." : ` Too thin to quote: ${f.why}.`);
1594
+ if (r.changes.some((c) => c.window === f.window))
1595
+ out.push(" This fit spans the move in what 1% buys (above): read the per-window figures.");
1596
+ }
1597
+ out.push("", "Readings: Claude Code's (Pro, Max and Ultra; 0.1% steps) from the plugin's mod,", "the status line or the proxy, and Codex's rollouts (whole percents). Usage", "elsewhere (the web app, another computer) moves the limit without a transcript", "here, so it widens the error.");
1598
+ return out.join("\n");
1599
+ }
1600
+ /**
1601
+ * `limits --report`: a block to paste into a GitHub issue. Per weekly
1602
+ * window: % used, dollars and tokens per 1%, the split by entrypoint and
1603
+ * model, Claude Code's versions, and every move in what 1% buys, dated. It
1604
+ * carries figures, dates, model and entrypoint names and version numbers
1605
+ * only: no prompt, no path, no session or account id (reportModel masks a
1606
+ * model id that is a cloud resource).
1607
+ */
1608
+ export function renderLimitsReport(r) {
1609
+ if (!r.windows.length && !r.resets.length)
1610
+ return `No limit readings yet. ${HOW_TO_RECORD}`;
1611
+ const out = ["### Usage limits, measured on my machine", ""];
1612
+ const versions = [...new Set(r.resets.filter((w) => w.app === "claude").flatMap((w) => w.versions))].sort(compareVersions);
1613
+ const claude = r.claudeWindows.length
1614
+ ? r.claudeWindows.includes("five_hour") ? "weekly and 5-hour" : "weekly only (no 5-hour window in the readings)"
1615
+ : "none";
1616
+ const srcNames = { mod: "the plugin's mod", statusline: "the status line", proxy: "the proxy", earlier: "an earlier recorder" };
1617
+ const sources = Object.entries(r.claudeSources).sort((a, b) => b[1] - a[1]).map(([k, n]) => `${n} from ${srcNames[k] ?? k}`).join(", ");
1618
+ out.push(`- Measured with context-doctor ${PROXY_VERSION} (\`context-doctor limits --report\`), ${r.days} days to ${utcMinute(r.now)}`, `- Claude windows read: ${claude}${r.claudeReadings ? `; ${r.claudeReadings} readings (${sources})` : ""}${r.codexReadings ? `; Codex: ${r.codexReadings} readings` : ""}`, ...(r.claudeReadings ? [`- Claude Code version${versions.length === 1 ? "" : "s"}: ${versions.length ? versions.join(", ") : "unknown"}`] : []), "- Dollars are API-equivalent: this machine's requests priced at API list rates, not a bill. % matched: the rise in stretches with usage here; the rest came with no transcript here (claude.ai, another computer).", "");
1619
+ if (r.resets.length) {
1620
+ out.push("| Window, reset to reset (UTC) | % used | % matched | $ per 1% | Tokens per 1% | By entrypoint ($ share) | Claude Code |", "|---|---|---|---|---|---|---|");
1621
+ for (const w of r.resets) {
1622
+ const fig = w.usdPerPct !== undefined && !w.why;
1623
+ out.push(`| ${w.label.replace(/ weekly$/, "")} ${utcDay(w.start)} to ${utcDay(w.resetsAt)}${w.current ? " (now)" : ""} | ${pts(w.pctUsed)} | ${pts(w.pctMatched)} | ${fig ? `${dollars(w.usdPerPct)}${plusMinus(w.relSe)}` : "n/a"} | ${fig ? tokenCount(w.tokensPerPct ?? 0) : "n/a"} | ${sharesLine(w.byEntrypoint) || "none"} | ${w.app === "claude" ? versionSpan(w.versions) : "n/a"} |`);
1624
+ }
1625
+ out.push("");
1626
+ out.push(r.changes.length ? "**What 1% buys moved:**" : comparable(r.resets) ? "**What 1% buys:** no move of 1.5x or more beyond the error between these windows." : "**What 1% buys:** fewer than two windows with a figure, nothing to compare yet.");
1627
+ for (const c of r.changes)
1628
+ out.push(`- ${changeLine(c)}`);
1629
+ const splits = r.resets.flatMap((w) => {
1630
+ const lines = [];
1631
+ const ep = splitLine(w.byEntrypoint), md = splitLine(w.byModel);
1632
+ if (ep)
1633
+ lines.push(`- ${utcDay(w.start)} to ${utcDay(w.resetsAt)}, by entrypoint: ${ep}`);
1634
+ if (md)
1635
+ lines.push(`- ${utcDay(w.start)} to ${utcDay(w.resetsAt)}, by model: ${md}`);
1636
+ if (!md && mixed(w.byModel))
1637
+ lines.push(`- ${utcDay(w.start)} to ${utcDay(w.resetsAt)}, models ($ share): ${sharesLine(w.byModel)}`);
1638
+ return lines;
1639
+ });
1640
+ if (splits.length)
1641
+ out.push("", "**Per entrypoint and model** (each one's own $ per 1%, where the stretches tell them apart):", ...splits);
1642
+ const thin = r.resets.filter((w) => w.why);
1643
+ if (thin.length)
1644
+ out.push("", ...thin.map((w) => `- No figure for ${utcDay(w.start)} to ${utcDay(w.resetsAt)}: ${w.why}.`));
1645
+ }
1646
+ else {
1647
+ out.push("No weekly window with readings in the period yet.");
1001
1648
  }
1002
- out.push("", "Readings: Claude Code's status line input (Pro/Max, 0.1% steps) and Codex's", "rollouts (whole percents). Usage elsewhere (the web app, another computer)", "moves the limit without a transcript here, so it widens the error.");
1649
+ const now5h = r.windows.find((w) => w.window === "five_hour");
1650
+ const nowWeek = r.windows.find((w) => w.window === "seven_day");
1651
+ if (nowWeek || now5h)
1652
+ out.push("", `Now: ${[nowWeek ? `weekly ${pts(nowWeek.pct)}%` : "", now5h ? `5-hour ${pts(now5h.pct)}%` : ""].filter(Boolean).join(", ")}.`);
1653
+ out.push("", "No prompts, file paths, session or account ids are included.");
1003
1654
  return out.join("\n");
1004
1655
  }