context-doctor 0.50.0 → 0.52.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 CHANGED
@@ -1199,6 +1199,12 @@ const MIN_KEY_SHARE = 0.05;
1199
1199
  const MAX_KEY_REL_SE = 0.3;
1200
1200
  /** Windows this long or longer are fitted per reset (Claude's weekly; Codex's weekly and monthly). */
1201
1201
  const PER_RESET_MIN_MS = 7 * DAY - HOUR;
1202
+ /** A mix that moved less than this (half the summed share changes) held. */
1203
+ const MIX_HELD = 0.1;
1204
+ /** The mix's prediction must cover this share of each side's dollars with per-model rates. */
1205
+ const MIX_COVER = 0.9;
1206
+ /** A mix prediction within this factor of 1 is no mix move worth naming beside a limit move. */
1207
+ const MIX_NAMED = 1.2;
1202
1208
  /** Ratio of sums, sum(u) / sum(d), and its relative standard error (the ratio estimator's, across stretches). */
1203
1209
  function ratio(u, d) {
1204
1210
  const n = u.length;
@@ -1303,6 +1309,20 @@ function splitBy(segments, inSeg, keyOf, whole) {
1303
1309
  }
1304
1310
  return list;
1305
1311
  }
1312
+ /** The requests of each stretch: both lists are in time order. */
1313
+ function usageBySegment(segments, usage) {
1314
+ const inSeg = segments.map(() => []);
1315
+ let g = 0;
1316
+ for (const p of usage) {
1317
+ while (g < segments.length && segments[g].to < p.ts)
1318
+ g++;
1319
+ if (g >= segments.length)
1320
+ break;
1321
+ if (p.ts > segments[g].from)
1322
+ inSeg[g].push(p);
1323
+ }
1324
+ return inSeg;
1325
+ }
1306
1326
  /** One window's readings cut at each reset: the periods, oldest first. */
1307
1327
  function periodsOf(readings) {
1308
1328
  const clean = cleanReadings(readings);
@@ -1331,17 +1351,7 @@ export function resetWindowsOf(readings, usage, opts = {}) {
1331
1351
  const windowMs = last.windowMs ?? 7 * DAY;
1332
1352
  const resetsAt = last.resetsAt ?? first.ts + windowMs;
1333
1353
  const { segments, elsewherePct } = segmentsOf(period, usage, opts.stretchMs);
1334
- // The requests of each stretch: both lists are in time order.
1335
- const inSeg = segments.map(() => []);
1336
- let g = 0;
1337
- for (const p of usage) {
1338
- while (g < segments.length && segments[g].to < p.ts)
1339
- g++;
1340
- if (g >= segments.length)
1341
- break;
1342
- if (p.ts > segments[g].from)
1343
- inSeg[g].push(p);
1344
- }
1354
+ const inSeg = usageBySegment(segments, usage);
1345
1355
  const usd = segments.reduce((a, s) => a + s.usd, 0);
1346
1356
  const tokens = inSeg.reduce((a, pts) => a + pts.reduce((b, p) => b + tokensOf(p), 0), 0);
1347
1357
  const pctMatched = segments.reduce((a, s) => a + s.dpct, 0);
@@ -1414,15 +1424,158 @@ function sigmaOf(a, b, factor) {
1414
1424
  const se = Math.sqrt(a.relSe ** 2 + b.relSe ** 2);
1415
1425
  return se > 0 ? Math.abs(Math.log(factor)) / se : Infinity;
1416
1426
  }
1427
+ function mixRows(segs, usage, after) {
1428
+ const inSeg = usageBySegment(segs, usage);
1429
+ return segs.map((s, i) => {
1430
+ const byModel = new Map();
1431
+ for (const p of inSeg[i]) {
1432
+ const k = reportModel(p.model);
1433
+ byModel.set(k, (byModel.get(k) ?? 0) + p.usd);
1434
+ }
1435
+ return { dpct: s.dpct, byModel, after };
1436
+ });
1437
+ }
1438
+ function sharesOf(rows) {
1439
+ const t = new Map();
1440
+ let all = 0;
1441
+ for (const r of rows)
1442
+ for (const [k, v] of r.byModel) {
1443
+ t.set(k, (t.get(k) ?? 0) + v);
1444
+ all += v;
1445
+ }
1446
+ return all > 0 ? Object.fromEntries([...t].sort((a, b) => b[1] - a[1]).map(([k, v]) => [k, v / all])) : {};
1447
+ }
1448
+ /**
1449
+ * Per-model % of the limit per dollar, fitted on both sides' stretches at
1450
+ * once with one factor f for the after side (dpct = Σ β_m·usd_m, times f
1451
+ * after the move): f searched for, the rates least squares at each. β is
1452
+ * each model's rate before the move, and a move of the limit itself goes to
1453
+ * f instead of bending the rates. Fitting the rates over both sides with no
1454
+ * f would credit a model used mostly after a real move with that move. Undefined when the stretches cannot tell the
1455
+ * models apart (a rate at or below zero, or known worse than ±30%).
1456
+ */
1457
+ function jointRates(rows, keys) {
1458
+ if (keys.length < 2 || rows.length <= keys.length + 2)
1459
+ return undefined;
1460
+ const y = rows.map((r) => r.dpct);
1461
+ // For a given after-side factor the rates are plain least squares: search
1462
+ // the factor (on the log scale, 1/10x to 10x) for the least squared error.
1463
+ const at = (logF) => {
1464
+ const f = Math.exp(logF);
1465
+ const fit = olsSe(rows.map((r) => keys.map((k) => (r.byModel.get(k) ?? 0) * (r.after ? f : 1))), y);
1466
+ const sse = fit ? rows.reduce((a, r, i) => a + (y[i] - keys.reduce((b, k, j) => b + fit.coef[j] * (r.byModel.get(k) ?? 0) * (r.after ? f : 1), 0)) ** 2, 0) : Infinity;
1467
+ return { fit, sse };
1468
+ };
1469
+ let lo = -Math.log(10), hi = Math.log(10);
1470
+ const g = (Math.sqrt(5) - 1) / 2;
1471
+ let x1 = hi - g * (hi - lo), x2 = lo + g * (hi - lo);
1472
+ let f1 = at(x1).sse, f2 = at(x2).sse;
1473
+ for (let it = 0; it < 60 && hi - lo > 1e-5; it++) {
1474
+ if (f1 <= f2) {
1475
+ hi = x2;
1476
+ x2 = x1;
1477
+ f2 = f1;
1478
+ x1 = hi - g * (hi - lo);
1479
+ f1 = at(x1).sse;
1480
+ }
1481
+ else {
1482
+ lo = x1;
1483
+ x1 = x2;
1484
+ f1 = f2;
1485
+ x2 = lo + g * (hi - lo);
1486
+ f2 = at(x2).sse;
1487
+ }
1488
+ }
1489
+ const { fit } = at((lo + hi) / 2);
1490
+ if (!fit || fit.coef.some((b, j) => !(b > 0) || fit.se[j] / b > MAX_KEY_REL_SE))
1491
+ return undefined;
1492
+ return new Map(keys.map((k, j) => [k, fit.coef[j]]));
1493
+ }
1494
+ /** A window's own per-model rates (splitBy's), as % per dollar: none for the pooled "other". */
1495
+ function windowRates(w) {
1496
+ return new Map(w.byModel.filter((t) => t.usdPerPct !== undefined && t.usdPerPct > 0 && t.key !== "other").map((t) => [t.key, 1 / t.usdPerPct]));
1497
+ }
1498
+ /** Dollars per 1% a mix gives at per-model rates, over the dollars those rates cover; undefined under MIX_COVER. */
1499
+ function predicted(shares, rates) {
1500
+ let cover = 0, pctPerUsd = 0;
1501
+ for (const [k, s] of Object.entries(shares)) {
1502
+ const b = rates.get(k);
1503
+ if (b === undefined)
1504
+ continue;
1505
+ cover += s;
1506
+ pctPerUsd += s * b;
1507
+ }
1508
+ return cover >= MIX_COVER && pctPerUsd > 0 ? cover / pctPerUsd : undefined;
1509
+ }
1510
+ /**
1511
+ * The mix on each side of a move and what it alone predicts: rates from the
1512
+ * joint fit on the two sides' stretches, else the first of `fallback` (the
1513
+ * windows' own per-model figures, nearest first) that covers both sides.
1514
+ */
1515
+ function mixOf(before, after, fallback) {
1516
+ const sb = sharesOf(before), sa = sharesOf(after);
1517
+ const keys = [...new Set([...Object.keys(sb), ...Object.keys(sa)])];
1518
+ if (!keys.length || keys.every((k) => k === "unknown"))
1519
+ return undefined;
1520
+ const delta = keys.map((k) => [k, (sa[k] ?? 0) - (sb[k] ?? 0)]).sort((a, b) => b[1] - a[1]);
1521
+ const mix = {
1522
+ before: sb, after: sa, grew: delta[0][0],
1523
+ ...(delta.length > 1 && delta[delta.length - 1][1] < 0 ? { shrank: delta[delta.length - 1][0] } : {}),
1524
+ moved: delta.reduce((a, [, d]) => a + Math.abs(d), 0) / 2,
1525
+ };
1526
+ const named = keys.filter((k) => k !== "unknown" && k !== "other" && Math.max(sb[k] ?? 0, sa[k] ?? 0) >= MIN_KEY_SHARE);
1527
+ // The joint fit tells a model's own rate from a move only for a model used on both sides: one used on one side alone carries the move in its rate.
1528
+ const both = named.every((k) => (sb[k] ?? 0) >= MIN_KEY_SHARE && (sa[k] ?? 0) >= MIN_KEY_SHARE);
1529
+ const tries = [both ? jointRates([...before, ...after], named) : undefined, ...fallback].filter((r) => !!r && r.size > 0);
1530
+ for (const rates of tries) {
1531
+ const pb = predicted(sb, rates), pa = predicted(sa, rates);
1532
+ if (pb === undefined || pa === undefined)
1533
+ continue;
1534
+ mix.pctPerUsd = Object.fromEntries([...rates].filter(([k]) => k in sb || k in sa));
1535
+ mix.predictedBefore = pb;
1536
+ mix.predictedAfter = pa;
1537
+ return { mix, mixFactor: pa / pb };
1538
+ }
1539
+ return { mix };
1540
+ }
1541
+ /** Set a move's mix fields and its cause (SlopeChange.cause). `minSigma`: the bar the move itself had to clear. */
1542
+ function explainMove(c, before, after, fallback, se, minSigma) {
1543
+ const got = mixOf(before, after, fallback);
1544
+ if (!got)
1545
+ return;
1546
+ c.mix = got.mix;
1547
+ // A mix that held explains nothing, whatever the rates say.
1548
+ const mixFactor = got.mix.moved < MIX_HELD ? 1 : got.mixFactor;
1549
+ if (mixFactor === undefined) {
1550
+ c.cause = "unclear";
1551
+ return;
1552
+ }
1553
+ c.mixFactor = mixFactor;
1554
+ c.residual = c.factor / mixFactor;
1555
+ c.residualSigma = sigmaOf({ relSe: se.before }, { relSe: se.after }, c.residual);
1556
+ const limitMoved = Math.max(c.residual, 1 / c.residual) >= MIN_FACTOR && c.residualSigma >= minSigma;
1557
+ c.cause = !limitMoved ? "mix" : Math.max(mixFactor, 1 / mixFactor) >= MIX_NAMED ? "both" : "limit";
1558
+ }
1417
1559
  /**
1418
1560
  * Where what 1% costs moved: between consecutive windows that each have a
1419
1561
  * figure (dated at the reset), and inside a window at the one split of its
1420
1562
  * stretches that separates two rates best (dated at that stretch). Reported
1421
1563
  * from a 1.5x move either way, beyond 3 standard errors between windows and
1422
- * 4 inside one (the split is searched for).
1564
+ * 4 inside one (the split is searched for). Each move is checked against
1565
+ * the model mix on its two sides (explainMove; needs `readings` to find the
1566
+ * stretches): `cause` says whether the limit moved or the mix did.
1423
1567
  */
1424
1568
  export function slopeChanges(windows, usage = [], readings = [], stretchMs) {
1425
1569
  const out = [];
1570
+ const periods = readings.length ? periodsOf(readings) : [];
1571
+ const periodOf = (w) => periods.find((p) => p[0].ts === w.firstReading && p[p.length - 1].ts === w.lastReading);
1572
+ /**
1573
+ * The mix's fallback rates: `first`'s own per-model figures, then the other
1574
+ * windows', nearest to `around` first, never `skip`'s (a window that holds
1575
+ * a move inside it fits its rates across that move: a model used mostly
1576
+ * after it would carry the move as its own rate).
1577
+ */
1578
+ const ratesNear = (around, first, skip) => [...first, ...windows.filter((x) => !first.includes(x) && x !== skip && x.window === around.window).sort((x, y) => Math.abs(x.start - around.start) - Math.abs(y.start - around.start))].map(windowRates);
1426
1579
  const quoted = windows.filter((w) => w.usdPerPct !== undefined && w.relSe !== undefined && Number.isFinite(w.relSe) && !w.why);
1427
1580
  for (let i = 1; i < quoted.length; i++) {
1428
1581
  const a = quoted[i - 1], b = quoted[i];
@@ -1432,17 +1585,20 @@ export function slopeChanges(windows, usage = [], readings = [], stretchMs) {
1432
1585
  const sigma = sigmaOf({ relSe: a.relSe }, { relSe: b.relSe }, factor);
1433
1586
  if (Math.max(factor, 1 / factor) < MIN_FACTOR || sigma < RESET_SIGMA)
1434
1587
  continue;
1435
- out.push({
1588
+ const c = {
1436
1589
  window: b.window, label: b.label, kind: "reset", at: b.start, prevEnd: a.resetsAt,
1437
1590
  usdPerPctBefore: a.usdPerPct, usdPerPctAfter: b.usdPerPct, tokensPerPctBefore: a.tokensPerPct, tokensPerPctAfter: b.tokensPerPct,
1438
1591
  factor, sigma, versionsBefore: a.versions, versionsAfter: b.versions,
1439
- });
1592
+ };
1593
+ const pa = periodOf(a), pb = periodOf(b);
1594
+ if (pa && pb)
1595
+ explainMove(c, mixRows(segmentsOf(pa, usage, stretchMs).segments, usage, false), mixRows(segmentsOf(pb, usage, stretchMs).segments, usage, true), ratesNear(a, [a, b]), { before: a.relSe, after: b.relSe }, RESET_SIGMA);
1596
+ out.push(c);
1440
1597
  }
1441
1598
  // Inside a window: its own stretches again, split once where two rates fit best.
1442
- const periods = readings.length ? periodsOf(readings) : [];
1443
1599
  // Every window with a figure, loose ones too: a move inside a window is what makes its figure loose.
1444
1600
  for (const w of windows.filter((x) => x.usdPerPct !== undefined)) {
1445
- const period = periods.find((p) => p[0].ts === w.firstReading && p[p.length - 1].ts === w.lastReading);
1601
+ const period = periodOf(w);
1446
1602
  if (!period)
1447
1603
  continue;
1448
1604
  const segs = segmentsOf(period, usage, stretchMs).segments;
@@ -1474,11 +1630,13 @@ export function slopeChanges(windows, usage = [], readings = [], stretchMs) {
1474
1630
  return pct > 0 ? t / pct : undefined;
1475
1631
  };
1476
1632
  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);
1477
- out.push({
1633
+ const c = {
1478
1634
  window: w.window, label: w.label, kind: "within", at: segs[best.at].from,
1479
1635
  usdPerPctBefore: before.r, usdPerPctAfter: after.r, tokensPerPctBefore: tok(0, best.at), tokensPerPctAfter: tok(best.at, segs.length),
1480
1636
  factor, sigma, versionsBefore: vers(0, best.at), versionsAfter: vers(best.at, segs.length),
1481
- });
1637
+ };
1638
+ explainMove(c, mixRows(segs.slice(0, best.at), usage, false), mixRows(segs.slice(best.at), usage, true), ratesNear(w, [], w), { before: before.relSe, after: after.relSe }, WITHIN_SIGMA);
1639
+ out.push(c);
1482
1640
  }
1483
1641
  return out.sort((a, b) => a.at - b.at);
1484
1642
  }
@@ -1651,10 +1809,36 @@ function changeLine(c) {
1651
1809
  ? `between the reset of ${utcMinute(c.prevEnd)} and the window from ${utcMinute(c.at)}`
1652
1810
  : `at the reset of ${utcMinute(c.at)}`
1653
1811
  : `within the window, around ${utcMinute(c.at)}`;
1654
- 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`;
1812
+ const move = (f) => (f < 1 ? `${(1 / f).toFixed(1)}x less use per 1%` : `${f.toFixed(1)}x more use per 1%`);
1813
+ const drains = (f) => (f < 1 ? "the limit drains faster" : "the limit drains slower");
1655
1814
  const tok = c.tokensPerPctBefore !== undefined && c.tokensPerPctAfter !== undefined ? `; tokens per 1% ${tokenCount(c.tokensPerPctBefore)} to ${tokenCount(c.tokensPerPctAfter)}` : "";
1656
1815
  const ver = versionSpan(c.versionsBefore) !== versionSpan(c.versionsAfter) ? `; Claude Code ${versionSpan(c.versionsBefore)} before, ${versionSpan(c.versionsAfter)} after` : "";
1657
- return `${c.label}, ${when}: 1% went from ${dollars(c.usdPerPctBefore)} to ${dollars(c.usdPerPctAfter)} of API-equivalent use (${times})${tok}${ver}.`;
1816
+ const head = `${c.label}, ${when}: 1% went from ${dollars(c.usdPerPctBefore)} to ${dollars(c.usdPerPctAfter)} of API-equivalent use`;
1817
+ if (!c.cause || c.cause === "limit" || !c.mix)
1818
+ return `${head} (${move(c.factor)}: ${drains(c.factor)})${tok}${ver}.`;
1819
+ const m = c.mix;
1820
+ const pct = (v) => `${Math.round((v ?? 0) * 100)}%`;
1821
+ const used = `you used ${modelLabel(m.grew)} for ${pct(m.after[m.grew])} of your dollars after it (${pct(m.before[m.grew])} before)`;
1822
+ const rate = m.pctPerUsd?.[m.grew], other = m.shrank ? m.pctPerUsd?.[m.shrank] : undefined;
1823
+ const ratio = rate !== undefined && other !== undefined && other > 0 ? rate / other : undefined;
1824
+ const per = ratio === undefined || (ratio < 1.1 && ratio > 1 / 1.1) ? ""
1825
+ : ratio > 1 ? `, which uses your limit ${ratio.toFixed(1)}x faster per dollar than ${modelLabel(m.shrank)}`
1826
+ : `, which uses your limit ${(1 / ratio).toFixed(1)}x slower per dollar than ${modelLabel(m.shrank)}`;
1827
+ const predicted = m.predictedBefore !== undefined && m.predictedAfter !== undefined ? `; the mix alone predicts ${dollars(m.predictedBefore)} to ${dollars(m.predictedAfter)}` : "";
1828
+ if (c.cause === "unclear") {
1829
+ return `${head} (${move(c.factor)}), and your model mix changed too: ${used}. Per-model figures are too thin yet to say how much of the move that explains${tok}${ver}.`;
1830
+ }
1831
+ const r = c.residual;
1832
+ if (c.cause === "mix") {
1833
+ const left = Math.max(r, 1 / r) < 1.15 ? "per model, 1% buys about the same" : `per model, 1% buys ${move(r).replace(" per 1%", "")}, under the 1.5x this report calls a move`;
1834
+ return `${head} (${move(c.factor)}). This comes from your model mix, not the limit: ${used}${per}${predicted}; ${left}${tok}${ver}.`;
1835
+ }
1836
+ return `${head} (${move(c.factor)}). Part of it is your model mix: ${used}${per}${predicted}. Beyond the mix, per model, 1% buys ${move(r).replace(" per 1%", "")}: ${drains(r)}${tok}${ver}.`;
1837
+ }
1838
+ /** "claude-fable-5-2" as "Fable 5.2"; any other id as it is. */
1839
+ export function modelLabel(key) {
1840
+ const m = /^claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d{1,2}))?(?!\d)/i.exec(key ?? "");
1841
+ return m ? `${m[1][0].toUpperCase()}${m[1].slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ""}` : key ?? "another model";
1658
1842
  }
1659
1843
  /** 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)". */
1660
1844
  function splitLine(list) {
@@ -1669,9 +1853,11 @@ function splitLine(list) {
1669
1853
  /**
1670
1854
  * The full `limits` report. `pastLimit`: lines on requests paid from usage
1671
1855
  * credits past a limit (credits.ts creditsLines), placed under the windows;
1672
- * none when nothing went past one.
1856
+ * none when nothing went past one. `ahead`: the line on what running out
1857
+ * before the weekly reset would cost on usage credits (credits.ts
1858
+ * creditsAheadLine), under the weekly window's run-out.
1673
1859
  */
1674
- export function renderLimits(r, pastLimit = []) {
1860
+ export function renderLimits(r, pastLimit = [], ahead) {
1675
1861
  const out = ["USAGE LIMITS", "═".repeat(60)];
1676
1862
  if (!r.windows.length && !r.resets.length) {
1677
1863
  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).`);
@@ -1699,6 +1885,8 @@ export function renderLimits(r, pastLimit = []) {
1699
1885
  out.push(s.beforeReset
1700
1886
  ? ` At that pace it runs out ${clock(s.runsOutAt, r.now)} (in ${hm(s.runsOutAt - r.now)}), before the reset.`
1701
1887
  : " At that pace it lasts until the reset.");
1888
+ if (ahead && s.beforeReset && s.app === "claude" && s.window === "seven_day")
1889
+ out.push(` ${ahead}`);
1702
1890
  }
1703
1891
  }
1704
1892
  }