context-doctor 0.51.0 → 0.53.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
@@ -1654,6 +1654,159 @@ function perReset(readings, usage, now) {
1654
1654
  }
1655
1655
  return { resets, changes };
1656
1656
  }
1657
+ /** A weekly line this close before a 5-hour one still stands for that moment: the recorder would have written the weekly window again had it moved (a minute's throttle) or after 15 minutes unchanged. */
1658
+ const EXCHANGE_PAIR_MS = KEEPALIVE_MS + MIN;
1659
+ /** A figure is quoted from this many 5-hour windows... */
1660
+ const MIN_EXCHANGE_WINDOWS = 3;
1661
+ /** ...known to this relative error or better. */
1662
+ const MAX_EXCHANGE_REL_SE = 0.25;
1663
+ /**
1664
+ * A move is reported beyond this many standard errors (1.5 times a
1665
+ * two-standard-error band: the bar slopeChanges sets between windows) and
1666
+ * of at least this factor either way.
1667
+ */
1668
+ const EXCHANGE_SIGMA = 3;
1669
+ const MIN_EXCHANGE_FACTOR = 1.1;
1670
+ /** Each 5-hour period's rise and the weekly rise over the same moments, split where a weekly reset falls inside it; with the weekly period each belongs to. */
1671
+ function exchangeSamples(short, long) {
1672
+ const weeks = periodsOf(long);
1673
+ const flat = weeks.flatMap((p) => p.map((r) => ({ r, week: p }))).sort((a, b) => a.r.ts - b.r.ts);
1674
+ /** The weekly reading standing at `ts`: the last one at or before it, within EXCHANGE_PAIR_MS, its period not reset by then. */
1675
+ const at = (ts) => {
1676
+ let lo = 0, hi = flat.length - 1, found = -1;
1677
+ while (lo <= hi) {
1678
+ const mid = (lo + hi) >> 1;
1679
+ if (flat[mid].r.ts <= ts) {
1680
+ found = mid;
1681
+ lo = mid + 1;
1682
+ }
1683
+ else
1684
+ hi = mid - 1;
1685
+ }
1686
+ const e = found >= 0 ? flat[found] : undefined;
1687
+ if (!e || ts - e.r.ts > EXCHANGE_PAIR_MS || (e.r.resetsAt !== undefined && e.r.resetsAt < ts))
1688
+ return undefined;
1689
+ return e;
1690
+ };
1691
+ const out = [];
1692
+ for (const period of periodsOf(short)) {
1693
+ let run = [];
1694
+ let week;
1695
+ const flush = () => {
1696
+ if (week && run.length >= 2) {
1697
+ const a = run[0], b = run[run.length - 1];
1698
+ const fivePct = Math.max(0, b.f - a.f), weekPct = Math.max(0, b.w - a.w);
1699
+ if (fivePct > 0 || weekPct > 0)
1700
+ out.push({ from: a.ts, to: b.ts, fivePct, weekPct, week });
1701
+ }
1702
+ run = [];
1703
+ };
1704
+ for (const r of period) {
1705
+ const e = at(r.ts);
1706
+ if (!e)
1707
+ continue;
1708
+ if (e.week !== week) {
1709
+ flush();
1710
+ week = e.week;
1711
+ }
1712
+ run.push({ ts: r.ts, f: r.pct, w: e.r.pct });
1713
+ }
1714
+ flush();
1715
+ }
1716
+ return out.sort((a, b) => a.from - b.from);
1717
+ }
1718
+ /** The ratio over some samples, with its error, or why it is not quoted. `res`: each window's reading step (1 for whole percents). */
1719
+ function exchangeFigure(samples, res) {
1720
+ const n = samples.length;
1721
+ const fivePct = samples.reduce((a, s) => a + s.fivePct, 0), weekPct = samples.reduce((a, s) => a + s.weekPct, 0);
1722
+ const fig = { windows: n, fivePct, weekPct };
1723
+ if (n < MIN_EXCHANGE_WINDOWS) {
1724
+ fig.why = `${n} five-hour window${n === 1 ? "" : "s"} with weekly readings beside ${n === 1 ? "it" : "them"}; ${MIN_EXCHANGE_WINDOWS} make a figure`;
1725
+ return fig;
1726
+ }
1727
+ if (!(fivePct > 0)) {
1728
+ fig.why = "the 5-hour window has not risen beside weekly readings yet";
1729
+ return fig;
1730
+ }
1731
+ if (!(weekPct > 0)) {
1732
+ fig.why = `the weekly reading has not moved across ${pts(fivePct)} points of 5-hour windows yet`;
1733
+ return fig;
1734
+ }
1735
+ const r = weekPct / fivePct;
1736
+ // The spread between windows (the ratio estimator's error), and the whole-percent steps: each rise is a difference of two readings, each off by up to half a step.
1737
+ const spread = ratio(samples.map((s) => s.weekPct), samples.map((s) => s.fivePct))?.relSe ?? Infinity;
1738
+ const steps = Math.sqrt((n * ((res.long / weekPct) ** 2 + (res.short / fivePct) ** 2)) / 6);
1739
+ const relSe = Math.max(spread, steps);
1740
+ fig.pct = 100 * r;
1741
+ fig.err = 100 * r * relSe;
1742
+ if (!(relSe <= MAX_EXCHANGE_REL_SE))
1743
+ fig.why = `known only to ±${Number.isFinite(relSe) ? Math.round(relSe * 100) : "∞"}% so far`;
1744
+ return fig;
1745
+ }
1746
+ /** One app's exchange from its short (5-hour) and long (weekly) readings; undefined when either is missing (Ultra has no 5-hour window). */
1747
+ export function exchangeOf(short, long, opts) {
1748
+ if (!short.length || !long.length)
1749
+ return undefined;
1750
+ const now = opts.now ?? Date.now();
1751
+ const res = { short: resolutionOf(short), long: resolutionOf(long) };
1752
+ const samples = exchangeSamples(short, long);
1753
+ const byWeek = new Map();
1754
+ for (const s of samples) {
1755
+ const list = byWeek.get(s.week);
1756
+ if (list)
1757
+ list.push(s);
1758
+ else
1759
+ byWeek.set(s.week, [s]);
1760
+ }
1761
+ const weeks = [...byWeek].map(([period, list]) => {
1762
+ const last = period[period.length - 1];
1763
+ const windowMs = last.windowMs ?? 7 * DAY;
1764
+ const resetsAt = last.resetsAt ?? period[0].ts + windowMs;
1765
+ return { start: resetsAt - windowMs, resetsAt, current: resetsAt > now, ...exchangeFigure(list, res) };
1766
+ }).sort((a, b) => a.start - b.start);
1767
+ const quoted = weeks.filter((w) => w.pct !== undefined && w.err !== undefined && !w.why);
1768
+ const moves = [];
1769
+ for (let i = 1; i < quoted.length; i++) {
1770
+ const a = quoted[i - 1], b = quoted[i];
1771
+ const se = Math.hypot(a.err, b.err);
1772
+ const sigma = se > 0 ? Math.abs(b.pct - a.pct) / se : Infinity;
1773
+ const factor = b.pct / a.pct;
1774
+ if (sigma < EXCHANGE_SIGMA || Math.max(factor, 1 / factor) < MIN_EXCHANGE_FACTOR)
1775
+ continue;
1776
+ moves.push({ at: b.start, prevEnd: a.resetsAt, pctBefore: a.pct, errBefore: a.err, pctAfter: b.pct, errAfter: b.err, sigma });
1777
+ }
1778
+ const lastMove = moves[moves.length - 1];
1779
+ const pooled = lastMove ? samples.filter((s) => s.from >= lastMove.at) : samples;
1780
+ const since = lastMove ? lastMove.at : samples[0]?.from ?? short[0].ts;
1781
+ return {
1782
+ app: opts.app, label: opts.label, short: short[short.length - 1].window, long: long[long.length - 1].window,
1783
+ ...exchangeFigure(pooled, res),
1784
+ since, compared: quoted.length, weeks, moves,
1785
+ };
1786
+ }
1787
+ /** Codex's windows paired: per plan and limit id, the 5-hour one with the weekly one. */
1788
+ function codexExchanges(readings, now) {
1789
+ const groups = new Map();
1790
+ for (const [key, rs] of byWindow(readings)) {
1791
+ const ms = rs[rs.length - 1]?.windowMs;
1792
+ const kind = ms === 5 * HOUR ? "short" : ms === 7 * DAY ? "long" : undefined;
1793
+ if (!kind)
1794
+ continue;
1795
+ const base = key.split(":").slice(0, -1).join(":");
1796
+ const g = groups.get(base) ?? (groups.set(base, {}), groups.get(base));
1797
+ g[kind] = rs;
1798
+ }
1799
+ const out = [];
1800
+ for (const g of groups.values()) {
1801
+ if (!g.short || !g.long)
1802
+ continue;
1803
+ const long = g.long[g.long.length - 1];
1804
+ const e = exchangeOf(g.short, g.long, { app: "codex", label: windowLabel(long.window, long.windowMs).replace(" weekly", ""), now });
1805
+ if (e)
1806
+ out.push(e);
1807
+ }
1808
+ return out;
1809
+ }
1657
1810
  function byWindow(readings) {
1658
1811
  const m = new Map();
1659
1812
  for (const r of readings) {
@@ -1680,6 +1833,9 @@ export function limitsReport(days = 30, opts = {}) {
1680
1833
  const claudeUse = claude.length >= 2 ? claudeUsage(claude[0].ts - HOUR, claude[claude.length - 1].ts, opts.claudePaths) : [];
1681
1834
  const claudeReset = perReset(claude, claudeUse, now);
1682
1835
  const codexReset = perReset(codex.readings, codex.usage, now);
1836
+ const claudeByWindow = byWindow(claude);
1837
+ const claudeExchange = exchangeOf(claudeByWindow.get("five_hour") ?? [], claudeByWindow.get("seven_day") ?? [], { app: "claude", label: "Claude", now });
1838
+ const exchange = [...(claudeExchange ? [claudeExchange] : []), ...codexExchanges(codex.readings, now)];
1683
1839
  const claudeSources = {};
1684
1840
  for (const r of claude)
1685
1841
  claudeSources[r.source ?? "earlier"] = (claudeSources[r.source ?? "earlier"] ?? 0) + 1;
@@ -1705,6 +1861,7 @@ export function limitsReport(days = 30, opts = {}) {
1705
1861
  changes: [...claudeReset.changes, ...codexReset.changes],
1706
1862
  claudeWindows: CLAUDE_WINDOWS.filter((w) => claude.some((r) => r.window === w)),
1707
1863
  claudeSources,
1864
+ exchange,
1708
1865
  };
1709
1866
  }
1710
1867
  /**
@@ -1835,6 +1992,30 @@ function changeLine(c) {
1835
1992
  }
1836
1993
  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
1994
  }
1995
+ /** "Nov 16", in UTC like the report's other dates. */
1996
+ const monthDay = (ms) => new Date(ms).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
1997
+ const tenth = (v) => (Math.round(v * 10) / 10).toFixed(1);
1998
+ /**
1999
+ * The exchange in one line: what a full 5-hour window costs of the weekly
2000
+ * limit, its error, how many fit in a week, and whether it moved (from what
2001
+ * to what, and when). Too thin: says so, with no figure.
2002
+ */
2003
+ export function exchangeLine(e) {
2004
+ const whose = e.app === "claude" ? "" : `${e.label}: `;
2005
+ if (e.pct === undefined || e.err === undefined || e.why)
2006
+ return `${whose}What a full 5-hour window costs of your weekly limit: too thin to quote yet (${e.why ?? "no figure"}).`;
2007
+ const perWeek = Math.max(1, Math.round(100 / e.pct));
2008
+ const head = `${whose}${whose ? "a" : "A"} full 5-hour window is ${tenth(e.pct)}% of your weekly limit (±${tenth(Math.max(0.1, e.err))}), about ${perWeek} a week`;
2009
+ const m = e.moves[e.moves.length - 1];
2010
+ if (m) {
2011
+ const when = Math.abs(m.prevEnd - m.at) > SAME_RESET_MS ? `between ${monthDay(m.prevEnd)} and ${monthDay(m.at)}` : `at the weekly reset of ${monthDay(m.at)}`;
2012
+ const earlier = e.moves.length > 1 ? ` (the latest of ${e.moves.length} moves since ${monthDay(e.weeks[0].start)})` : "";
2013
+ return `${head}; it was ${tenth(m.pctBefore)}% (±${tenth(Math.max(0.1, m.errBefore))}) and moved ${when}${earlier}. Your model mix does not explain this: both limits count the same requests, so one of the two limits changed.`;
2014
+ }
2015
+ if (e.compared >= 2)
2016
+ return `${head}; unchanged since ${monthDay(e.since)}.`;
2017
+ return `${head} (since ${monthDay(e.since)}; one weekly window so far, nothing to compare yet).`;
2018
+ }
1838
2019
  /** "claude-fable-5-2" as "Fable 5.2"; any other id as it is. */
1839
2020
  export function modelLabel(key) {
1840
2021
  const m = /^claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d{1,2}))?(?!\d)/i.exec(key ?? "");
@@ -1893,6 +2074,8 @@ export function renderLimits(r, pastLimit = [], ahead) {
1893
2074
  if (r.claudeWindows.length === 1 && r.claudeWindows[0] === "seven_day") {
1894
2075
  out.push("", "No 5-hour window in Claude's readings: a plan without one (Ultra), so the weekly window is the limit.");
1895
2076
  }
2077
+ if (r.exchange.length)
2078
+ out.push("", ...r.exchange.map(exchangeLine));
1896
2079
  if (pastLimit.length) {
1897
2080
  out.push("", "Past your plan's limit: usage credits", "─".repeat(60), ...pastLimit);
1898
2081
  }
@@ -2005,6 +2188,8 @@ export function renderLimitsReport(r) {
2005
2188
  const nowWeek = r.windows.find((w) => w.window === "seven_day");
2006
2189
  if (nowWeek || now5h)
2007
2190
  out.push("", `Now: ${[nowWeek ? `weekly ${pts(nowWeek.pct)}%` : "", now5h ? `5-hour ${pts(now5h.pct)}%` : ""].filter(Boolean).join(", ")}.`);
2191
+ if (r.exchange.length)
2192
+ out.push("", ...r.exchange.map(exchangeLine));
2008
2193
  out.push("", "No prompts, file paths, session or account ids are included.");
2009
2194
  return out.join("\n");
2010
2195
  }