context-doctor 0.37.0 → 0.38.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.
package/dist/limits.js ADDED
@@ -0,0 +1,869 @@
1
+ /**
2
+ * `context-doctor limits`: your plan's usage limits, in their own unit.
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:
7
+ *
8
+ * - Claude Code hands its status line command `rate_limits.five_hour` and
9
+ * `.seven_day`, each `{used_percentage, resets_at}` (documented at
10
+ * code.claude.com/docs/en/statusline; built in 2.1.308 as
11
+ * 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
+ * - Codex records `rate_limits.primary` / `.secondary`
15
+ * `{used_percent, window_minutes, resets_at}` on every token_count event of
16
+ * its rollouts (~/.codex/sessions), next to that request's usage, in
17
+ * whole percent.
18
+ *
19
+ * From the readings: the current %, the pace, and when each window runs out
20
+ * at that pace. And, by fitting each rise in % against the usage recorded on
21
+ * this machine over the same interval, an estimate of what 1M tokens of each
22
+ * kind cost in % of the limit, with the fit's error. Usage elsewhere (claude.ai
23
+ * in a browser, another computer) moves the % without leaving a transcript
24
+ * here; it shows up as error, and rises with no local usage at all are
25
+ * counted apart. When the fit is too thin to trust, the report says so
26
+ * instead of printing a number.
27
+ */
28
+ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
29
+ import { homedir } from "node:os";
30
+ import { dirname, join } from "node:path";
31
+ import { statePath } from "./ledger.js";
32
+ import { forEachLine, listSessions, outputSettler, replyCounter } from "./session.js";
33
+ import { subagentDir } from "./subagents.js";
34
+ import { openAIUsage, pricingFor, usageCost } from "./pricing.js";
35
+ import { realModel } from "./tokens.js";
36
+ const MIN = 60_000;
37
+ const HOUR = 60 * MIN;
38
+ const DAY = 24 * HOUR;
39
+ /** Claude Code's two windows, as its status line input names them. */
40
+ export const CLAUDE_WINDOWS = ["five_hour", "seven_day"];
41
+ // ---------------------------------------------------------------------------
42
+ // The Claude readings log, written by the status line
43
+ // ---------------------------------------------------------------------------
44
+ /** Beside the hook state and the ledger: ~/.claude/.context-doctor-limits.jsonl. */
45
+ export function limitsLogPath() {
46
+ return join(dirname(statePath()), ".context-doctor-limits.jsonl");
47
+ }
48
+ /** An unchanged reading is written again after this long, so the log says the window was still there. */
49
+ const KEEPALIVE_MS = 15 * MIN;
50
+ /** A window that moved is written at most once a minute: plenty for stretches of half an hour. */
51
+ const THROTTLE_MS = MIN;
52
+ /**
53
+ * Past this size the log keeps its newest LOG_KEEP_BYTES. At the throttle a
54
+ * window writes at most one ~75-byte line a minute: a heavy user (both
55
+ * windows moving 16 hours a day) writes ~140 KB a day, so 1.5 MB holds over
56
+ * a week of the heaviest use.
57
+ */
58
+ const LOG_ROTATE_AT = 2 * 1024 * 1024;
59
+ const LOG_KEEP_BYTES = 1536 * 1024;
60
+ /** Two reset times this close name the same window period (Claude Code rounds; Codex re-reports). */
61
+ const SAME_RESET_MS = 10 * MIN;
62
+ /** The last `bytes` of a file as text (the first line of it may be partial). */
63
+ function tail(path, bytes) {
64
+ const size = statSync(path).size;
65
+ const n = Math.min(size, bytes);
66
+ const fd = openSync(path, "r");
67
+ try {
68
+ const buf = Buffer.alloc(n);
69
+ readSync(fd, buf, 0, n, size - n);
70
+ return buf.toString("utf8");
71
+ }
72
+ finally {
73
+ closeSync(fd);
74
+ }
75
+ }
76
+ function parseLogLine(line) {
77
+ let e;
78
+ try {
79
+ e = JSON.parse(line);
80
+ }
81
+ catch {
82
+ return undefined;
83
+ }
84
+ if (!e || typeof e !== "object")
85
+ return undefined;
86
+ const { ts, w, pct, reset } = e;
87
+ if (typeof ts !== "number" || !Number.isFinite(ts) || typeof w !== "string" || !CLAUDE_WINDOWS.includes(w))
88
+ return undefined;
89
+ if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000)
90
+ return undefined;
91
+ return { ts, app: "claude", w, pct, reset: typeof reset === "number" && Number.isFinite(reset) && reset > 0 ? reset : undefined };
92
+ }
93
+ /**
94
+ * Append what changed in Claude Code's `rate_limits` to the log: a window
95
+ * whose % or reset time moved since its last line, or that has not been
96
+ * written for 15 minutes. Nothing when there are no limits (an API key,
97
+ * Bedrock, Vertex). Never throws: the status line must stay silent. Returns
98
+ * the lines written.
99
+ */
100
+ export function recordLimits(rateLimits, now = Date.now(), path = limitsLogPath()) {
101
+ if (!rateLimits || typeof rateLimits !== "object")
102
+ return 0;
103
+ const fresh = [];
104
+ for (const w of CLAUDE_WINDOWS) {
105
+ const r = rateLimits[w];
106
+ const pct = r?.used_percentage;
107
+ if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000)
108
+ continue;
109
+ const reset = typeof r.resets_at === "number" && Number.isFinite(r.resets_at) && r.resets_at > 0 ? Math.round(r.resets_at) : undefined;
110
+ fresh.push({ ts: now, app: "claude", w, pct: Math.round(pct * 10) / 10, ...(reset ? { reset } : {}) });
111
+ }
112
+ if (!fresh.length)
113
+ return 0;
114
+ try {
115
+ mkdirSync(dirname(path), { recursive: true });
116
+ const last = new Map();
117
+ if (existsSync(path)) {
118
+ for (const line of tail(path, 16 * 1024).split("\n")) {
119
+ const l = parseLogLine(line);
120
+ if (l)
121
+ last.set(l.w, l);
122
+ }
123
+ }
124
+ const due = fresh.filter((l) => {
125
+ const p = last.get(l.w);
126
+ if (!p || now < p.ts)
127
+ return true;
128
+ const sameReset = p.reset !== undefined && l.reset !== undefined ? Math.abs(p.reset - l.reset) * 1000 <= SAME_RESET_MS : p.reset === l.reset;
129
+ if (!sameReset)
130
+ return true;
131
+ // Lower than the last reading of the same window period: another Claude
132
+ // Code session's status line still holding an older figure. Usage within
133
+ // a period never goes down, so it is never logged.
134
+ if (l.pct < p.pct)
135
+ return false;
136
+ if (l.pct === p.pct)
137
+ return now - p.ts >= KEEPALIVE_MS;
138
+ return now - p.ts >= THROTTLE_MS;
139
+ });
140
+ if (!due.length)
141
+ return 0;
142
+ if (existsSync(path) && statSync(path).size > LOG_ROTATE_AT) {
143
+ const text = tail(path, LOG_KEEP_BYTES);
144
+ writeFileSync(path, text.slice(text.indexOf("\n") + 1));
145
+ }
146
+ appendFileSync(path, due.map((l) => JSON.stringify(l)).join("\n") + "\n");
147
+ return due.length;
148
+ }
149
+ catch {
150
+ return 0;
151
+ }
152
+ }
153
+ /** Every Claude reading in the log since `since`. */
154
+ export function readClaudeReadings(since = 0, path = limitsLogPath()) {
155
+ if (!existsSync(path))
156
+ return [];
157
+ let text;
158
+ try {
159
+ text = readFileSync(path, "utf8");
160
+ }
161
+ catch {
162
+ return [];
163
+ }
164
+ const out = [];
165
+ for (const line of text.split("\n")) {
166
+ const l = parseLogLine(line);
167
+ if (!l || l.ts < since)
168
+ continue;
169
+ 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 });
170
+ }
171
+ return out.sort((a, b) => a.ts - b.ts);
172
+ }
173
+ // ---------------------------------------------------------------------------
174
+ // Codex: readings and usage, both from its rollouts
175
+ // ---------------------------------------------------------------------------
176
+ export function codexSessionsRoot(home = homedir()) {
177
+ return join(home, ".codex", "sessions");
178
+ }
179
+ function rolloutFiles(root, since) {
180
+ const out = [];
181
+ const walk = (dir, depth) => {
182
+ let names;
183
+ try {
184
+ names = readdirSync(dir);
185
+ }
186
+ catch {
187
+ return;
188
+ }
189
+ for (const name of names) {
190
+ const p = join(dir, name);
191
+ let st;
192
+ try {
193
+ st = statSync(p);
194
+ }
195
+ catch {
196
+ continue;
197
+ }
198
+ if (st.isDirectory()) {
199
+ if (depth < 3)
200
+ walk(p, depth + 1);
201
+ }
202
+ else if (name.endsWith(".jsonl") && st.mtimeMs >= since) {
203
+ out.push(p);
204
+ }
205
+ }
206
+ };
207
+ walk(root, 0);
208
+ return out;
209
+ }
210
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
211
+ /** "codex:300", "codex:10080"; a limit id other than "codex" is kept in the key. */
212
+ function codexWindow(limitId, minutes, plan) {
213
+ // The plan is part of the key: two sign-ins (a team plan, a free one) are two accounts' limits.
214
+ const p = typeof plan === "string" && /^[\w-]{1,20}$/.test(plan) ? `${plan}:` : "";
215
+ return typeof limitId === "string" && limitId && limitId !== "codex" ? `codex:${p}${limitId.slice(0, 40)}:${minutes}` : `codex:${p}${minutes}`;
216
+ }
217
+ /**
218
+ * Codex readings and usage since `since`. A token_count event repeats the
219
+ * last request's usage when only the limits were refreshed, so a request is
220
+ * counted when the running total moves.
221
+ */
222
+ export function codexLimitData(since, root = codexSessionsRoot()) {
223
+ const readings = [];
224
+ const usage = [];
225
+ if (!existsSync(root))
226
+ return { readings, usage };
227
+ for (const file of rolloutFiles(root, since)) {
228
+ let model;
229
+ let total = -1;
230
+ try {
231
+ forEachLine(file, (line) => {
232
+ if (!line.includes('"token_count"') && !line.includes('"turn_context"'))
233
+ return;
234
+ let e;
235
+ try {
236
+ e = JSON.parse(line);
237
+ }
238
+ catch {
239
+ return;
240
+ }
241
+ const p = e?.payload;
242
+ if (!p || typeof p !== "object")
243
+ return;
244
+ if (e.type === "turn_context") {
245
+ if (typeof p.model === "string")
246
+ model = p.model;
247
+ return;
248
+ }
249
+ if (e.type !== "event_msg" || p.type !== "token_count")
250
+ return;
251
+ const ts = Date.parse(String(e.timestamp ?? ""));
252
+ if (!Number.isFinite(ts) || ts < since)
253
+ return;
254
+ const runTotal = num(p.info?.total_token_usage?.total_tokens);
255
+ const last = p.info?.last_token_usage;
256
+ // No running total recorded: every event is a request.
257
+ if (last && num(last.input_tokens) > 0 && (runTotal === 0 || runTotal !== total)) {
258
+ total = runTotal;
259
+ const u = openAIUsage(last);
260
+ const price = pricingFor(model);
261
+ usage.push({ ts, app: "codex", model, input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: price ? usageCost(u, price).totalUsd : 0 });
262
+ }
263
+ const rl = p.rate_limits;
264
+ if (!rl || typeof rl !== "object")
265
+ return;
266
+ for (const slot of ["primary", "secondary"]) {
267
+ const w = rl[slot];
268
+ const pct = w?.used_percent;
269
+ const minutes = num(w?.window_minutes);
270
+ if (typeof pct !== "number" || !Number.isFinite(pct) || pct < 0 || pct > 1000 || !minutes)
271
+ continue;
272
+ const reset = num(w.resets_at);
273
+ readings.push({ ts, app: "codex", window: codexWindow(rl.limit_id, minutes, rl.plan_type), pct, resetsAt: reset ? reset * 1000 : undefined, windowMs: minutes * MIN, plan: typeof rl.plan_type === "string" ? rl.plan_type.slice(0, 20) : undefined });
274
+ }
275
+ });
276
+ }
277
+ catch {
278
+ /* one unreadable rollout must not sink the report */
279
+ }
280
+ }
281
+ readings.sort((a, b) => a.ts - b.ts);
282
+ usage.sort((a, b) => a.ts - b.ts);
283
+ return { readings, usage };
284
+ }
285
+ // ---------------------------------------------------------------------------
286
+ // Claude usage: every request on this machine, subagents included
287
+ // ---------------------------------------------------------------------------
288
+ /**
289
+ * Every Claude Code request between `since` and `until`, main threads and
290
+ * subagents alike (both draw on the same limits), each reply once.
291
+ */
292
+ export function claudeUsage(since, until = Infinity, paths) {
293
+ const tops = paths ?? listSessions(10_000).filter((s) => s.path.includes(".claude") && s.modifiedAt.getTime() >= since).map((s) => s.path);
294
+ const files = [];
295
+ for (const t of tops) {
296
+ files.push(t);
297
+ const dir = subagentDir(t);
298
+ try {
299
+ for (const f of readdirSync(dir))
300
+ if (f.endsWith(".jsonl") && statSync(join(dir, f)).mtimeMs >= since)
301
+ files.push(join(dir, f));
302
+ }
303
+ catch {
304
+ /* no subagents */
305
+ }
306
+ }
307
+ const out = [];
308
+ const runRows = new Set();
309
+ for (const file of files) {
310
+ const sighting = replyCounter(runRows);
311
+ const settle = outputSettler();
312
+ const byId = new Map();
313
+ try {
314
+ forEachLine(file, (line) => {
315
+ if (!line.includes('"usage"'))
316
+ return;
317
+ let e;
318
+ try {
319
+ e = JSON.parse(line);
320
+ }
321
+ catch {
322
+ return;
323
+ }
324
+ const m = e?.message;
325
+ if (e?.type !== "assistant" || !m?.usage)
326
+ return;
327
+ const seen = sighting(e);
328
+ if (seen === "repeat") {
329
+ const known = typeof m.id === "string" ? byId.get(m.id) : undefined;
330
+ const more = settle(e, false);
331
+ if (known && more) {
332
+ known.point.output += more;
333
+ if (known.price)
334
+ known.point.usd += (more * known.price.outputPerM) / 1e6;
335
+ }
336
+ return;
337
+ }
338
+ if (seen !== "new")
339
+ return;
340
+ settle(e, true);
341
+ const ts = Date.parse(String(e.timestamp ?? ""));
342
+ if (!Number.isFinite(ts) || ts < since || ts > until)
343
+ return;
344
+ const u = m.usage;
345
+ const point = { ts, app: "claude", model: realModel(m.model), input: num(u.input_tokens), read: num(u.cache_read_input_tokens), write: num(u.cache_creation_input_tokens), output: num(u.output_tokens), usd: 0 };
346
+ if (point.input + point.read + point.write === 0)
347
+ return;
348
+ const price = pricingFor(point.model);
349
+ if (price)
350
+ point.usd = usageCost(u, price).totalUsd;
351
+ out.push(point);
352
+ if (typeof m.id === "string")
353
+ byId.set(m.id, { point, price });
354
+ });
355
+ }
356
+ catch {
357
+ /* skip an unreadable transcript */
358
+ }
359
+ }
360
+ return out.sort((a, b) => a.ts - b.ts);
361
+ }
362
+ export function windowLabel(window, windowMs) {
363
+ if (window === "five_hour")
364
+ return "Claude 5-hour";
365
+ if (window === "seven_day")
366
+ return "Claude weekly";
367
+ const parts = window.split(":").slice(1);
368
+ const minutes = windowMs ? Math.round(windowMs / MIN) : Number(parts[parts.length - 1]);
369
+ const span = minutes === 300 ? "5-hour" : minutes === 10_080 ? "weekly" : minutes >= 43_000 && minutes <= 44_700 ? "monthly" : minutes % 1440 === 0 ? `${minutes / 1440}-day` : `${minutes}-minute`;
370
+ const tags = parts.slice(0, -1);
371
+ return `Codex ${span}${tags.length ? ` (${tags.join(", ")})` : ""}`;
372
+ }
373
+ /** Two readings of one window belong to the same period: the reset did not move (or, with no reset known, the % did not fall), and the first's reset had not passed. */
374
+ function samePeriod(a, b, resolution) {
375
+ if (a.resetsAt !== undefined && b.resetsAt !== undefined) {
376
+ if (Math.abs(a.resetsAt - b.resetsAt) > SAME_RESET_MS)
377
+ return false;
378
+ }
379
+ else if (b.pct < a.pct - resolution)
380
+ return false;
381
+ if (a.resetsAt !== undefined && b.ts > a.resetsAt)
382
+ return false;
383
+ if (a.windowMs && b.ts - a.ts > a.windowMs)
384
+ return false;
385
+ return true;
386
+ }
387
+ /**
388
+ * One window's readings, in time order, without the stale ones: a reading
389
+ * lower than an earlier one of the same period comes from another session
390
+ * (two Claude Code windows, two Codex sessions) still holding an older
391
+ * figure. Within a period usage only grows, so it is dropped, never read as
392
+ * a new period or a fall in the pace. Logs written before 0.38 hold them.
393
+ */
394
+ export function cleanReadings(readings) {
395
+ const sorted = [...readings].sort((a, b) => a.ts - b.ts);
396
+ const out = [];
397
+ let top;
398
+ for (const r of sorted) {
399
+ if (top && r.resetsAt !== undefined && top.resetsAt !== undefined && Math.abs(r.resetsAt - top.resetsAt) <= SAME_RESET_MS && !(top.resetsAt !== undefined && r.ts > top.resetsAt) && r.pct < top.pct)
400
+ continue;
401
+ out.push(r);
402
+ top = !top || !samePeriod(top, r, 0.1) || r.pct >= top.pct ? r : top;
403
+ }
404
+ return out;
405
+ }
406
+ /** 0.1 when any reading has a fraction (Claude), else 1 (Codex's whole percents). */
407
+ export function resolutionOf(readings) {
408
+ return readings.some((r) => Math.abs(r.pct - Math.round(r.pct)) > 1e-9) ? 0.1 : 1;
409
+ }
410
+ export function windowStatus(readings, now = Date.now()) {
411
+ if (!readings.length)
412
+ return undefined;
413
+ const last = readings[readings.length - 1];
414
+ const res = resolutionOf(readings);
415
+ const status = {
416
+ window: last.window,
417
+ label: windowLabel(last.window, last.windowMs),
418
+ app: last.app,
419
+ pct: last.pct,
420
+ at: last.ts,
421
+ resetsAt: last.resetsAt,
422
+ resetSince: last.resetsAt !== undefined && last.resetsAt <= now,
423
+ readings: readings.length,
424
+ plan: last.plan,
425
+ };
426
+ if (status.resetSince)
427
+ return status;
428
+ // The current period: back from the newest reading while the period holds.
429
+ let first = readings.length - 1;
430
+ while (first > 0 && samePeriod(readings[first - 1], readings[first], res))
431
+ first--;
432
+ const period = readings.slice(first);
433
+ const lookback = last.windowMs && last.windowMs <= 5 * HOUR ? HOUR : DAY;
434
+ const recent = period.filter((r) => r.ts >= last.ts - lookback);
435
+ const from = recent[0];
436
+ if (from && last.ts - from.ts >= 10 * MIN) {
437
+ status.recentPerHour = Math.max(0, ((last.pct - from.pct) / (last.ts - from.ts)) * HOUR);
438
+ }
439
+ if (last.windowMs && last.resetsAt) {
440
+ const start = last.resetsAt - last.windowMs;
441
+ if (last.ts - start >= 10 * MIN)
442
+ status.averagePerHour = Math.max(0, (last.pct / (last.ts - start)) * HOUR);
443
+ }
444
+ if (status.recentPerHour && status.recentPerHour > 0 && last.pct < 100) {
445
+ status.runsOutAt = last.ts + ((100 - last.pct) / status.recentPerHour) * HOUR;
446
+ status.beforeReset = last.resetsAt === undefined || status.runsOutAt < last.resetsAt;
447
+ }
448
+ return status;
449
+ }
450
+ export const TOKEN_TYPES = ["input", "cache read", "cache write", "output"];
451
+ /**
452
+ * Cut each period into stretches of at least `stretchMs` (half an hour on
453
+ * Claude's 0.1% steps, three hours on Codex's whole percents) and sum the
454
+ * usage that falls inside each. Cut by time, not by rise: stretches then
455
+ * differ in how much was used, which is what the fit learns from, and a
456
+ * quiet stretch says as much as a busy one. A rise with no local usage at
457
+ * all is usage elsewhere: counted, kept out of the fit; a quiet stretch with
458
+ * no rise is left out.
459
+ */
460
+ export function segmentsOf(readings, usage, stretchMs) {
461
+ readings = cleanReadings(readings);
462
+ const res = resolutionOf(readings);
463
+ const cut = stretchMs ?? (res < 1 ? 30 * MIN : 3 * HOUR);
464
+ const segments = [];
465
+ let elsewhere = 0, elsewherePct = 0;
466
+ let u = 0;
467
+ const usageIn = (from, to) => {
468
+ while (u < usage.length && usage[u].ts <= from)
469
+ u++;
470
+ const x = [0, 0, 0, 0];
471
+ let usd = 0, requests = 0;
472
+ let j = u;
473
+ for (; j < usage.length && usage[j].ts <= to; j++) {
474
+ const p = usage[j];
475
+ x[0] += p.input / 1e6;
476
+ x[1] += p.read / 1e6;
477
+ x[2] += p.write / 1e6;
478
+ x[3] += p.output / 1e6;
479
+ usd += p.usd;
480
+ requests++;
481
+ }
482
+ u = j;
483
+ return { x, usd, requests };
484
+ };
485
+ let start;
486
+ const close = (end) => {
487
+ if (!start || end.ts <= start.ts)
488
+ return;
489
+ const dpct = Math.max(0, end.pct - start.pct);
490
+ const got = usageIn(start.ts, end.ts);
491
+ if (got.requests === 0) {
492
+ if (dpct > res / 2) {
493
+ elsewhere++;
494
+ elsewherePct += dpct;
495
+ }
496
+ }
497
+ else {
498
+ segments.push({ from: start.ts, to: end.ts, dpct, ...got });
499
+ }
500
+ start = end;
501
+ };
502
+ for (let i = 0; i < readings.length; i++) {
503
+ const r = readings[i];
504
+ if (!start) {
505
+ start = r;
506
+ continue;
507
+ }
508
+ const prev = readings[i - 1];
509
+ if (!samePeriod(prev, r, res)) {
510
+ close(prev);
511
+ start = r;
512
+ continue;
513
+ }
514
+ if (r.ts - start.ts >= cut)
515
+ close(r);
516
+ }
517
+ if (start && readings.length && readings[readings.length - 1] !== start)
518
+ close(readings[readings.length - 1]);
519
+ return { segments, elsewhere, elsewherePct };
520
+ }
521
+ /** Least squares through the origin on the chosen columns; undefined when singular. */
522
+ function ols(rows, y, cols) {
523
+ const k = cols.length;
524
+ if (k === 0)
525
+ return [];
526
+ const a = Array.from({ length: k }, () => new Array(k + 1).fill(0));
527
+ for (let i = 0; i < rows.length; i++) {
528
+ for (let p = 0; p < k; p++) {
529
+ for (let q = 0; q < k; q++)
530
+ a[p][q] += rows[i][cols[p]] * rows[i][cols[q]];
531
+ a[p][k] += rows[i][cols[p]] * y[i];
532
+ }
533
+ }
534
+ // Gauss-Jordan with partial pivoting.
535
+ for (let c = 0; c < k; c++) {
536
+ let piv = c;
537
+ for (let r = c + 1; r < k; r++)
538
+ if (Math.abs(a[r][c]) > Math.abs(a[piv][c]))
539
+ piv = r;
540
+ const scale = Math.max(1e-300, ...a.map((row) => Math.abs(row[c])));
541
+ if (Math.abs(a[piv][c]) < 1e-12 * scale)
542
+ return undefined;
543
+ [a[c], a[piv]] = [a[piv], a[c]];
544
+ for (let r = 0; r < k; r++) {
545
+ if (r === c)
546
+ continue;
547
+ const f = a[r][c] / a[c][c];
548
+ for (let q = c; q <= k; q++)
549
+ a[r][q] -= f * a[c][q];
550
+ }
551
+ }
552
+ return cols.map((_, p) => a[p][k] / a[p][p]);
553
+ }
554
+ /**
555
+ * Non-negative least squares through the origin, exactly, by trying every
556
+ * subset of columns (four token types: sixteen subsets) and keeping the best
557
+ * fit whose coefficients are all non-negative. Columns with almost no data
558
+ * are left out and reported as such.
559
+ */
560
+ export function nnls(rows, y, usable) {
561
+ const width = rows[0]?.length ?? 0;
562
+ let best = { sse: y.reduce((s, v) => s + v * v, 0), coef: new Array(width).fill(0) };
563
+ const n = usable.length;
564
+ for (let mask = 1; mask < 1 << n; mask++) {
565
+ const cols = usable.filter((_, i) => mask & (1 << i));
566
+ const b = ols(rows, y, cols);
567
+ if (!b || b.some((v) => v < 0))
568
+ continue;
569
+ const coef = new Array(width).fill(0);
570
+ cols.forEach((c, i) => (coef[c] = b[i]));
571
+ let sse = 0;
572
+ for (let i = 0; i < rows.length; i++) {
573
+ const r = y[i] - rows[i].reduce((s, v, j) => s + v * coef[j], 0);
574
+ sse += r * r;
575
+ }
576
+ if (sse < best.sse - 1e-15)
577
+ best = { sse, coef };
578
+ }
579
+ return best.coef;
580
+ }
581
+ function quality(y, predictHeldOut, predictAll) {
582
+ const n = y.length;
583
+ const mean = y.reduce((s, v) => s + v, 0) / n;
584
+ let sst = 0, sse = 0, cv = 0;
585
+ for (let i = 0; i < n; i++) {
586
+ sst += (y[i] - mean) ** 2;
587
+ sse += (y[i] - predictAll(i)) ** 2;
588
+ cv += (y[i] - predictHeldOut(i)) ** 2;
589
+ }
590
+ const looRmse = Math.sqrt(cv / n);
591
+ return { r2: sst > 0 ? 1 - sse / sst : 0, looRmse, relError: mean > 0 ? looRmse / mean : Infinity };
592
+ }
593
+ /**
594
+ * When a figure is worth quoting. The gate is on how sure the coefficient
595
+ * itself is (its standard error, which only shrinks as readings accrue, so
596
+ * the savings lines do not come and go from one run to the next), not on R²:
597
+ * stretches of similar size explain little variation even when the
598
+ * coefficient is exact. Predictions per stretch may miss by up to a typical
599
+ * rise (the readings' rounding alone is a large part of a small rise).
600
+ */
601
+ const MIN_SEGMENTS = 8;
602
+ const MAX_REL_SE = 0.15;
603
+ /** The slope with an intercept at least ~3 standard errors above zero. */
604
+ const MAX_SLOPE_REL_SE = 0.3;
605
+ const MAX_REL_ERROR = 1;
606
+ /** Above this share of the rises with no local usage to match, the limit is visibly shared with other use. */
607
+ const MAX_ELSEWHERE = 0.1;
608
+ /** Folds for cross-validating the per-type fit: leave-one-out is quadratic in the stretches. */
609
+ const FOLDS = 10;
610
+ export function fitWindow(readings, usage, stretchMs) {
611
+ if (!readings.length)
612
+ return undefined;
613
+ const last = readings[readings.length - 1];
614
+ const res = resolutionOf(readings);
615
+ const { segments, elsewhere, elsewherePct } = segmentsOf(readings, usage, stretchMs);
616
+ const fit = {
617
+ window: last.window,
618
+ label: windowLabel(last.window, last.windowMs),
619
+ app: last.app,
620
+ segments: segments.length,
621
+ totalPct: segments.reduce((s, g) => s + g.dpct, 0),
622
+ elsewhere,
623
+ elsewherePct,
624
+ resolution: res,
625
+ requests: segments.reduce((s, g) => s + g.requests, 0),
626
+ usd: segments.reduce((s, g) => s + g.usd, 0),
627
+ usable: false,
628
+ };
629
+ // Dollars per model inside the stretches: both lists are in time order, one pass.
630
+ const byModel = new Map();
631
+ let g = 0;
632
+ for (const p of usage) {
633
+ while (g < segments.length && segments[g].to < p.ts)
634
+ g++;
635
+ if (g >= segments.length)
636
+ break;
637
+ if (p.model && p.ts > segments[g].from)
638
+ byModel.set(p.model, (byModel.get(p.model) ?? 0) + p.usd);
639
+ }
640
+ fit.mainModel = [...byModel.entries()].sort((a, b) => b[1] - a[1])[0]?.[0];
641
+ if (segments.length < 3) {
642
+ fit.why = `${segments.length} stretch${segments.length === 1 ? "" : "es"} of readings with usage beside ${segments.length === 1 ? "it" : "them"}; a fit needs ${MIN_SEGMENTS}`;
643
+ return fit;
644
+ }
645
+ const y = segments.map((s) => s.dpct);
646
+ const rows = segments.map((s) => s.x);
647
+ // A token type with under 50k tokens across the segments is not estimated:
648
+ // its coefficient would be noise. (Output is a small share of the tokens
649
+ // and can still carry much of the limit, so a share rule would drop it.)
650
+ const totals = [0, 1, 2, 3].map((j) => rows.reduce((a, r) => a + r[j], 0));
651
+ const usable = [0, 1, 2, 3].filter((j) => totals[j] >= 0.05);
652
+ if (usable.length) {
653
+ const coef = nnls(rows, y, usable);
654
+ const predict = (c, i) => rows[i].reduce((a, v, j) => a + v * c[j], 0);
655
+ const folds = Math.min(FOLDS, rows.length);
656
+ const foldCoef = Array.from({ length: folds }, (_, f) => nnls(rows.filter((_, i) => i % folds !== f), y.filter((_, i) => i % folds !== f), usable));
657
+ fit.byType = quality(y, (i) => predict(foldCoef[i % folds], i), (i) => predict(coef, i));
658
+ fit.perMillion = {};
659
+ usable.forEach((j) => (fit.perMillion[TOKEN_TYPES[j]] = coef[j]));
660
+ }
661
+ let usd = segments.map((s) => s.usd);
662
+ let sxy = usd.reduce((a, x, i) => a + x * y[i], 0);
663
+ let sxx = usd.reduce((a, x) => a + x * x, 0);
664
+ // A stretch that rose far more than its usage explains carries usage from
665
+ // elsewhere (the web app, another computer, in the same half hour): one
666
+ // robust pass drops those (residual over 3x the median absolute residual,
667
+ // upwards only) and refits, so a burst elsewhere does not inflate the rate.
668
+ if (sxx > 0 && usd.length >= MIN_SEGMENTS) {
669
+ const k0 = Math.max(0, sxy / sxx);
670
+ const resid = y.map((v, i) => v - k0 * usd[i]);
671
+ const scale = 1.4826 * [...resid].map(Math.abs).sort((a, b) => a - b)[Math.floor(resid.length / 2)];
672
+ const keep = resid.map((r) => !(scale > 0 && r > 3 * scale));
673
+ const dropped = keep.filter((x) => !x).length;
674
+ if (dropped > 0 && dropped <= resid.length / 4) {
675
+ fit.outliers = dropped;
676
+ fit.outlierPct = y.reduce((a, v, i) => a + (keep[i] ? 0 : v - k0 * usd[i]), 0);
677
+ const yk = y.filter((_, i) => keep[i]);
678
+ usd = usd.filter((_, i) => keep[i]);
679
+ y.splice(0, y.length, ...yk);
680
+ sxy = usd.reduce((a, x, i) => a + x * y[i], 0);
681
+ sxx = usd.reduce((a, x) => a + x * x, 0);
682
+ }
683
+ }
684
+ if (sxx > 0) {
685
+ const k = Math.max(0, sxy / sxx);
686
+ fit.pctPerUsd = k;
687
+ // Leave-one-out in closed form: the fit without stretch i.
688
+ const held = (i) => {
689
+ const den = sxx - usd[i] * usd[i];
690
+ return den > 0 ? Math.max(0, (sxy - usd[i] * y[i]) / den) * usd[i] : k * usd[i];
691
+ };
692
+ fit.byPrice = quality(y, held, (i) => k * usd[i]);
693
+ const sse = y.reduce((a, v, i) => a + (v - k * usd[i]) ** 2, 0);
694
+ const se = Math.sqrt(sse / Math.max(1, y.length - 1) / sxx);
695
+ fit.byPrice.relSe = k > 0 ? se / k : Infinity;
696
+ // Does usage drive the rises at all? Through the origin, any positive
697
+ // rises against any positive usage give a rate. With an intercept, the
698
+ // slope is clearly above zero only when busier stretches rise more.
699
+ const n = y.length;
700
+ const mx = usd.reduce((a, v) => a + v, 0) / n, my = y.reduce((a, v) => a + v, 0) / n;
701
+ const cxx = usd.reduce((a, v) => a + (v - mx) ** 2, 0);
702
+ const b = cxx > 0 ? usd.reduce((a, v, i) => a + (v - mx) * (y[i] - my), 0) / cxx : 0;
703
+ const sseC = y.reduce((a, v, i) => a + (v - (my + b * (usd[i] - mx))) ** 2, 0);
704
+ const seB = cxx > 0 && n > 2 ? Math.sqrt(sseC / (n - 2) / cxx) : Infinity;
705
+ fit.slopeRelSe = b > 0 ? seB / b : Infinity;
706
+ }
707
+ if (segments.length < MIN_SEGMENTS)
708
+ fit.why = `${segments.length} stretches of readings with usage beside them; ${MIN_SEGMENTS} make a fit worth quoting`;
709
+ else if (!fit.byPrice || !(fit.pctPerUsd > 0))
710
+ fit.why = "no priced usage beside the rises";
711
+ else if (!(fit.slopeRelSe <= MAX_SLOPE_REL_SE))
712
+ fit.why = "busier stretches do not rise clearly more than quiet ones: the rises do not follow the usage recorded here";
713
+ else if (fit.byPrice.relSe > MAX_REL_SE)
714
+ fit.why = `% per dollar is known only to ±${Math.round(fit.byPrice.relSe * 100)}% so far (under ±${Math.round(MAX_REL_SE * 100)}% is quoted): more readings narrow it`;
715
+ else if (fit.totalPct > 0 && (fit.elsewherePct + (fit.outlierPct ?? 0)) / (fit.totalPct + fit.elsewherePct) > MAX_ELSEWHERE)
716
+ fit.why = `${Math.round(((fit.elsewherePct + (fit.outlierPct ?? 0)) / (fit.totalPct + fit.elsewherePct)) * 100)}% of the rises came with no usage here to match: this limit is used elsewhere too, so dollars saved here would be overstated in it`;
717
+ else if (fit.byPrice.relError > MAX_REL_ERROR)
718
+ fit.why = `predictions miss by ${Math.round(fit.byPrice.relError * 100)}% of a typical rise: much of this limit moves with something other than the usage recorded here`;
719
+ else
720
+ fit.usable = true;
721
+ return fit;
722
+ }
723
+ function byWindow(readings) {
724
+ const m = new Map();
725
+ for (const r of readings) {
726
+ const list = m.get(r.window);
727
+ if (list)
728
+ list.push(r);
729
+ else
730
+ m.set(r.window, [r]);
731
+ }
732
+ // Stale readings from a parallel session out, once, for the status and the fit alike.
733
+ for (const [k, list] of m)
734
+ m.set(k, cleanReadings(list));
735
+ return m;
736
+ }
737
+ export function limitsReport(days = 30, opts = {}) {
738
+ const now = opts.now ?? Date.now();
739
+ const since = now - days * DAY;
740
+ const logPath = opts.logPath ?? limitsLogPath();
741
+ const claude = readClaudeReadings(since, logPath);
742
+ const codex = opts.claudeOnly ? { readings: [], usage: [] } : codexLimitData(since, opts.codexRoot);
743
+ const windows = [];
744
+ const fits = [];
745
+ // Claude usage is read only when there are readings to fit it against, and only over their span.
746
+ const claudeUse = claude.length >= 2 ? claudeUsage(claude[0].ts - HOUR, claude[claude.length - 1].ts, opts.claudePaths) : [];
747
+ for (const [, rs] of byWindow(claude)) {
748
+ const s = windowStatus(rs, now);
749
+ if (s)
750
+ windows.push(s);
751
+ const f = fitWindow(rs, claudeUse);
752
+ if (f)
753
+ fits.push(f);
754
+ }
755
+ for (const [, rs] of byWindow(codex.readings)) {
756
+ const s = windowStatus(rs, now);
757
+ if (s)
758
+ windows.push(s);
759
+ const f = fitWindow(rs, codex.usage);
760
+ if (f)
761
+ fits.push(f);
762
+ }
763
+ return { days, now, claudeLog: logPath, claudeReadings: claude.length, codexReadings: codex.readings.length, windows, fits };
764
+ }
765
+ /** The Claude fit to quote savings in: the weekly window first (savings are weekly), then the 5-hour one. */
766
+ export function claudeLimitFit(r) {
767
+ return ["seven_day", "five_hour"].map((w) => r.fits.find((f) => f.window === w && f.usable)).find(Boolean);
768
+ }
769
+ /**
770
+ * A dollar saving over `days`, in the limit's own unit: for the weekly
771
+ * limit, points of it a week ("≈ 4.1% of your weekly limit a week (±0.4)");
772
+ * for the 5-hour window, how many whole windows the saving amounts to. The
773
+ * ± is the rate's own standard error: a saving sums many stretches, so the
774
+ * per-stretch miss averages out and the rate's error is what remains.
775
+ */
776
+ export function inLimit(fit, usd, days) {
777
+ if (!fit.usable || fit.pctPerUsd === undefined || !fit.byPrice || !(usd > 0) || !(days > 0))
778
+ return undefined;
779
+ const round = (v) => (v >= 10 ? Math.round(v).toString() : v.toFixed(1));
780
+ const total = fit.pctPerUsd * usd;
781
+ if (fit.window === "seven_day") {
782
+ const pct = (total * 7) / days;
783
+ return `≈ ${round(pct)}% of your weekly limit a week (±${round(pct * (fit.byPrice.relSe ?? 0))})`;
784
+ }
785
+ const windows = total / 100;
786
+ return `≈ ${round(windows)} full 5-hour window${windows >= 0.95 && windows < 1.05 ? "" : "s"} in ${days} days (±${round(windows * (fit.byPrice.relSe ?? 0))})`;
787
+ }
788
+ /**
789
+ * Lines for the Claude Code reports: each lever's saving in the limit, when
790
+ * a fit is good enough; nothing otherwise (never a number the fit cannot
791
+ * carry). Kept within 60 columns, as `savings` is.
792
+ */
793
+ export function limitSavingsLines(fit, items, days) {
794
+ if (!fit)
795
+ return [];
796
+ const rows = items.map(([label, usd]) => [label, inLimit(fit, usd, days)]).filter((r) => Boolean(r[1]));
797
+ if (!rows.length)
798
+ return [];
799
+ const err = fit.byPrice?.relSe !== undefined ? Math.round(fit.byPrice.relSe * 100) : 0;
800
+ return [
801
+ `In your plan's ${fit.window === "seven_day" ? "weekly limit" : "5-hour window"} (fitted on ${fit.segments} stretches of your`,
802
+ `readings: % per list-price dollar known to ±${err}%):`,
803
+ ...rows.map(([label, text]) => ` ${label}: ${text}`),
804
+ ];
805
+ }
806
+ const hm = (ms) => {
807
+ const mins = Math.max(0, Math.round(ms / MIN));
808
+ if (mins < 60)
809
+ return `${mins} min`;
810
+ if (mins < 48 * 60)
811
+ return `${Math.floor(mins / 60)}h ${String(mins % 60).padStart(2, "0")}m`;
812
+ return `${Math.round(mins / 1440)} days`;
813
+ };
814
+ /** Local clock time, with the weekday when it is not within the next day. */
815
+ function clock(ms, now) {
816
+ const d = new Date(ms);
817
+ const t = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
818
+ return Math.abs(ms - now) < 20 * HOUR ? t : `${d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" })} ${t}`;
819
+ }
820
+ const pts = (v) => (v >= 10 ? Math.round(v).toString() : v >= 1 ? v.toFixed(1) : v.toFixed(2));
821
+ export function renderLimits(r) {
822
+ const out = ["USAGE LIMITS", "═".repeat(60)];
823
+ if (!r.windows.length) {
824
+ 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.");
825
+ return out.join("\n");
826
+ }
827
+ for (const s of r.windows) {
828
+ const age = r.now - s.at;
829
+ out.push("", `${s.label}: ${pts(s.pct)}% used, read ${hm(age)} ago`);
830
+ if (s.resetSince) {
831
+ out.push(` It has reset since (at ${clock(s.resetsAt, r.now)}); the next reading starts the new window.`);
832
+ continue;
833
+ }
834
+ if (s.resetsAt)
835
+ out.push(` Resets ${clock(s.resetsAt, r.now)} (in ${hm(s.resetsAt - r.now)}).`);
836
+ if (s.recentPerHour === undefined)
837
+ out.push(" Pace: not enough recent readings.");
838
+ else if (s.recentPerHour === 0)
839
+ out.push(" Pace: no rise over the recent readings.");
840
+ else {
841
+ const avg = s.averagePerHour !== undefined ? `; ${pts(s.averagePerHour)} a hour on average this window` : "";
842
+ out.push(` Pace: ${pts(s.recentPerHour)} points an hour lately${avg}.`);
843
+ if (s.runsOutAt !== undefined) {
844
+ out.push(s.beforeReset
845
+ ? ` At that pace it runs out ${clock(s.runsOutAt, r.now)} (in ${hm(s.runsOutAt - r.now)}), before the reset.`
846
+ : " At that pace it lasts until the reset.");
847
+ }
848
+ }
849
+ }
850
+ out.push("", "What 1M tokens cost in each limit (fitted on your own readings)");
851
+ out.push("─".repeat(60));
852
+ for (const f of r.fits) {
853
+ out.push(`${f.label}: ${f.segments} stretch${f.segments === 1 ? "" : "es"}, ${pts(f.totalPct)} points, ${f.requests.toLocaleString("en-US")} requests on this machine`);
854
+ if (f.elsewhere)
855
+ out.push(` ${f.elsewhere} rise${f.elsewhere === 1 ? "" : "s"} (${pts(f.elsewherePct)} points) with no usage here: used elsewhere, left out.`);
856
+ if (f.perMillion && f.byType && (f.usable || f.segments >= MIN_SEGMENTS)) {
857
+ const parts = TOKEN_TYPES.map((t) => (f.perMillion[t] !== undefined ? `${t} ${pts(f.perMillion[t])}%` : `${t} n/a`));
858
+ out.push(` By token type: ${parts.join(", ")}`);
859
+ out.push(` explains ${Math.round(Math.max(0, f.byType.r2) * 100)}% of the rises; predicts each within ±${pts(f.byType.looRmse)} points (${Math.round(f.byType.relError * 100)}%)`);
860
+ }
861
+ if (f.pctPerUsd !== undefined && f.byPrice && (f.usable || f.segments >= MIN_SEGMENTS)) {
862
+ out.push(` By list price: ${pts(f.pctPerUsd * 10)}% per $10${f.mainModel ? ` (mostly ${f.mainModel})` : ""}`);
863
+ 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)}%)`);
864
+ }
865
+ out.push(f.usable ? " Good enough to show savings in this limit (savings, cache-misses, compact-window)." : ` Too thin to quote: ${f.why}.`);
866
+ }
867
+ 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.");
868
+ return out.join("\n");
869
+ }