limitcast 0.9.2 → 0.10.1

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/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Stretch your Claude Code plan. Every session starts with ~100k tokens of context before you type, re-sent on every turn and to every subagent. limitcast measures what's in it, names what you never use, and stops runaway subagents before they burn the rest of your window.
4
4
 
5
+ ![limitcast status, trim and results running in a terminal](https://limitcast.dev/demo.gif)
6
+
5
7
  ```
6
8
  $ limitcast trim
7
9
  Every Claude Code session starts at 102.7k tokens before your first message.
@@ -32,13 +34,15 @@ Requires Node 20+ on macOS or Linux.
32
34
  ## Install
33
35
 
34
36
  ```sh
35
- npm install -g limitcast
37
+ npm install -g limitcast # or: brew install samstull9007/limitcast/limitcast
36
38
  limitcast install # free: status-line recorder
37
- limitcast activate <key> # Pro
39
+ limitcast trial # Pro free for 7 days, no card (or: limitcast activate <key>)
38
40
  limitcast install --guard # also the subagent guard (free: preview only)
39
41
  limitcast doctor
40
42
  ```
41
43
 
44
+ In Claude Code you can also add the plugin, for `/limitcast:status`, `/limitcast:results` and `/limitcast:trim`: `/plugin marketplace add SamStull9007/limitcast`, then `/plugin install limitcast@limitcast`. The status-line recorder still comes from `limitcast install`.
45
+
42
46
  `install` backs up `~/.claude/settings.json` and wraps your existing status line (it looks exactly the same). `--guard` adds the subagent guard (without Pro it only records what it would block). Restart Claude Code to load it. `limitcast uninstall` puts everything back.
43
47
 
44
48
  **Codex:** forecasts and reports need no setup (`~/.codex/sessions`, or `$CODEX_HOME/sessions`). With `--guard`, `install` also appends the guard to `~/.codex/hooks.json`, after your existing hooks so the ones you've already trusted keep their trust. Codex runs a new hook only once you approve it: start Codex and accept it. `limitcast doctor` shows whether it's trusted.
@@ -55,7 +59,8 @@ limitcast doctor
55
59
  | `limitcast after-reset [--src claude/codex] [--window 5h/7d] [--detach] -- <cmd>` | **Pro.** Wait for the window to reset, then run the command |
56
60
  | `limitcast results --html [--out FILE]` | **Pro.** Results, current windows and the burn report on one page, opened in your browser |
57
61
  | `limitcast install [--guard] [--alerts]` / `uninstall` | Wire into Claude Code / restore your settings |
58
- | `limitcast doctor` | Check the setup, data freshness, license, and that Claude Code, Codex and Grok logs are still in a format limitcast reads |
62
+ | `limitcast doctor [--fix]` | Check the setup, data freshness, license, and that Claude Code, Codex and Grok logs are still in a format limitcast reads. Also runs daily in the background and flags problems in the status line. `--fix` re-installs with the current Node (after a Node upgrade) |
63
+ | `limitcast trial` | Pro free for 7 days on this computer, no card, once |
59
64
  | `limitcast report [--days N] [--out FILE]` | **Pro.** Tokens by tool, day, project, model and session; subagent share |
60
65
  | `limitcast trim [--days N] [--share]` | Measured starting context of your latest session and how much you haven't used in N days (default 7). **Pro** names each item. `--share`: totals only, no names, safe to post |
61
66
  | `limitcast saved` | **Pro.** How much the part of your starting context you control has dropped since limitcast first measured it, times your sessions since |
@@ -76,7 +81,7 @@ Each limit reading is saved to `~/.local/state/limitcast/samples.jsonl` when it
76
81
 
77
82
  ## Pricing
78
83
 
79
- Free: runout forecast with NEAR warnings and the daily allowance, status-line readout, your starting-context total with how much you never use (Claude Code and Codex), `results`, and a preview of the guard. Pro ($79/year or $9/month, 14 days free): names what to cut and cuts it (`trim --apply`, also for Codex), a subagent guard that blocks and switches to Sonnet, burn report, alerts, a weekly summary, notifications, after-reset jobs, account headroom, the `/compact` nudge and the HTML dashboard. Cancel anytime; 14-day refund on any charge: email support@limitcast.dev. See https://limitcast.dev.
84
+ Free: runout forecast with NEAR warnings and the daily allowance, status-line readout, your starting-context total with how much you never use (Claude Code and Codex), `results`, and a preview of the guard. Pro ($79/year or $9/month, 14 days free; or `limitcast trial` for 7 days, no card; Team $69/seat/year, 3 seats minimum): names what to cut and cuts it (`trim --apply`, also for Codex), a subagent guard that blocks and switches to Sonnet, burn report, alerts, a weekly summary, notifications, after-reset jobs, account headroom, the `/compact` nudge and the HTML dashboard. Cancel anytime; 14-day refund on any charge: email support@limitcast.dev. See https://limitcast.dev.
80
85
 
81
86
  ## License
82
87
 
package/bin/limitcast.mjs CHANGED
@@ -11,18 +11,20 @@ import {
11
11
  localSkillFolders,
12
12
  planTrim,
13
13
  projectMcpServers,
14
+ reapplyTrim,
14
15
  stillLoading,
15
16
  transcriptCwd,
16
17
  undoTrim,
17
18
  } from '../src/apply.mjs';
19
+ import { calibrate } from '../src/calibrate.mjs';
18
20
  import { applyCodexTrim, codexConfigPath, codexServers, codexStartup, codexTrimReport, codexUsedServers, undoCodexTrim } from '../src/codex.mjs';
19
21
  import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
20
22
  import { formatChecks } from '../src/formats.mjs';
21
23
  import { runGuard } from '../src/guard.mjs';
22
24
  import { accountForecasts, compactHint, headroom, lastCallTokens } from '../src/hints.mjs';
23
25
  import { htmlPage } from '../src/html.mjs';
24
- import { doctor, install, readSettings, settingsPath, uninstall } from '../src/install.mjs';
25
- import { activate, currentLicense, isPro, UPGRADE_URL } from '../src/license.mjs';
26
+ import { doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
27
+ import { activate, currentLicense, isPro, startTrial, trialStatus, UPGRADE_URL } from '../src/license.mjs';
26
28
  import { buildNotifierApp, notifierApp, notifyChanges, notifyEnabled, send, setNotify } from '../src/notify.mjs';
27
29
  import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
28
30
  import { activatePolar, deactivatePolar, refreshDue, refreshPolar } from '../src/polar.mjs';
@@ -31,6 +33,7 @@ import { loadBlocks, resultsReport, resultsShare, resultsStats, weeklyDue, weekl
31
33
  import { claudeSamples, readCodex } from '../src/sources.mjs';
32
34
  import { countInteractiveSince, latestInteractiveTranscript } from '../src/startup.mjs';
33
35
  import { KEEP_MS, load, record, stateDir } from '../src/store.mjs';
36
+ import { forTerminal } from '../src/term.mjs';
34
37
  import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
35
38
  import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
36
39
  import { dailyDue, foldEvents, loadValue, saveValue, scanSessions, valueSection, valueTotals } from '../src/value.mjs';
@@ -41,8 +44,9 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code and Codex plans
41
44
  limitcast install [--guard] wire limitcast into Claude Code (and, with --guard, Codex); backs up settings
42
45
  (without Pro the guard is a preview: it records what it would block, never blocks)
43
46
  limitcast uninstall remove it and restore your original status line
44
- limitcast doctor check the setup
45
- limitcast status [--json] used, burn rate, runout time, reset, and today's share of each weekly window
47
+ limitcast doctor [--fix] check the setup (--fix: re-install with this Node, e.g. after a Node upgrade)
48
+ limitcast trial Pro free for 7 days on this computer, no card
49
+ limitcast status [--json] used, burn rate, runout time, reset, and today's share of each weekly window
46
50
  limitcast trim [--share] tokens every session loads before you type, and how much you never use
47
51
  limitcast trim --codex the same for Codex: AGENTS.md size and MCP servers you haven't used
48
52
  limitcast results [--days N] limits you reached, how far ahead limitcast warned, what the guard blocked
@@ -113,6 +117,8 @@ if (cmd === 'status') {
113
117
  if (refreshDue(now)) spawn(process.execPath, [fileURLToPath(import.meta.url), 'license'], { detached: true, stdio: 'ignore' }).unref();
114
118
  // Readings are kept 8 days; the daily rollup folds what they showed into the long-term value record.
115
119
  if (dailyDue(now)) spawn(process.execPath, [fileURLToPath(import.meta.url), 'rollup'], { detached: true, stdio: 'ignore' }).unref();
120
+ const health = healthHint();
121
+ if (health) hints.push(health);
116
122
  if (isPro()) {
117
123
  const samples = load(now - KEEP_MS);
118
124
  if (notifyEnabled()) notifyChanges(forecastAll(oneClaudeAccount(samples, sid), now), clock);
@@ -120,6 +126,9 @@ if (cmd === 'status') {
120
126
  if (room) hints.push(room);
121
127
  const ctx = typeof feed?.transcript_path === 'string' ? compactHint(lastCallTokens(feed.transcript_path)) : null;
122
128
  if (ctx) hints.push(ctx);
129
+ } else {
130
+ const week = freeWeeklyHint(now);
131
+ if (week) hints.push(week);
123
132
  }
124
133
  } catch {
125
134
  /* never break the status line */
@@ -128,7 +137,7 @@ if (cmd === 'status') {
128
137
  const wrapped = sep >= 0 ? args.slice(sep + 1) : [];
129
138
  if (wrapped.length) {
130
139
  const r = spawnSync(wrapped[0], wrapped.slice(1), { input, stdio: ['pipe', 'inherit', 'inherit'] });
131
- // Your status line stays as it was; Pro adds a second line only when there is something to act on.
140
+ // Your status line stays as it was; limitcast adds a second line only when there is something to act on.
132
141
  if (hints.length) console.log(`limitcast: ${hints.join(' · ')}`);
133
142
  process.exit(r.status ?? 1);
134
143
  }
@@ -168,24 +177,55 @@ if (cmd === 'status') {
168
177
  if (wantAlerts && !isPro()) console.log(`Alerts and the weekly summary are part of limitcast Pro (${UPGRADE_URL}). Skipping them.`);
169
178
  for (const c of install({ guard: wantGuard, alerts: wantAlerts && isPro() })) console.log(`✓ ${c}`);
170
179
  console.log('Restart Claude Code and Codex to load it. Then: limitcast doctor');
180
+ // First run: show the number that matters right away, and what comes next.
181
+ try {
182
+ const latest = await latestInteractiveTranscript(claudeRoot());
183
+ if (latest) {
184
+ recordOverhead(snapshot(latest));
185
+ /** @type {Map<string, number>} */
186
+ const groups = new Map();
187
+ for (const p of latest.pieces) groups.set(p.group, (groups.get(p.group) ?? 0) + p.chars);
188
+ const k = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
189
+ const total = [...groups.values()].reduce((a, c) => a + c, 0);
190
+ const top = [...groups].sort((a, b) => b[1] - a[1]).slice(0, 3);
191
+ console.log(
192
+ [
193
+ '',
194
+ `Your last Claude Code session loaded ~${k(total)} tokens of hooks, MCP servers, skills and instruction files before you typed`,
195
+ `(biggest: ${top.map(([g, c]) => `${g} ${k(c)}`).join(', ')}). It's re-sent on every turn and to every subagent.`,
196
+ 'See what you never use: limitcast trim',
197
+ ].join('\n'),
198
+ );
199
+ }
200
+ } catch {
201
+ /* no transcripts yet */
202
+ }
203
+ console.log(
204
+ `In a week, \`limitcast results\` shows every limit you hit and how far ahead limitcast warned you.${isPro() ? '' : ' Try Pro free for 7 days, no card: limitcast trial'}`,
205
+ );
171
206
  } else if (cmd === 'uninstall') {
172
207
  const changes = uninstall();
173
208
  console.log(changes.length ? changes.map((c) => `✓ ${c}`).join('\n') : 'Nothing to remove.');
174
209
  } else if (cmd === 'doctor') {
175
- // Readings are only stored when they change, so freshness comes from the last feed the status line saw.
176
- let latest = 0;
177
- try {
178
- latest = JSON.parse(readFileSync(join(stateDir(), 'last-feed.json'), 'utf8')).at ?? 0;
179
- } catch {
180
- /* never fed */
210
+ if (args.includes('--fix')) {
211
+ // Re-install what is installed, with this Node and this copy of limitcast (after a Node upgrade, say).
212
+ const f = installedFeatures();
213
+ if (!f.statusLine) console.log('limitcast is not installed. Run `limitcast install` first.');
214
+ else {
215
+ for (const c of install({ guard: f.guard && isPro(), alerts: f.alerts && isPro() })) console.log(`✓ ${c}`);
216
+ console.log('Restart Claude Code to load it. Codex asks you to approve the guard again: start Codex and accept it.');
217
+ }
181
218
  }
182
- const checks = [...doctor({ samplesAgeMs: latest ? now - latest : null, license: currentLicense() }), ...(await formatChecks())];
219
+ const checks = await healthChecks();
220
+ saveHealth(checks);
183
221
  for (const c of checks) console.log(`${c.ok ? '✓' : '✗'} ${c.line}`);
184
222
  process.exit(checks.every((c) => c.ok) ? 0 : 1);
185
223
  } else if (cmd === 'report' || cmd === 'trim') {
186
224
  const pro = isPro();
187
225
  if (!pro && cmd === 'report') {
188
- console.log(`\`limitcast ${cmd}\` is part of limitcast Pro: ${UPGRADE_URL}\nAlready bought it? limitcast activate <license-key>`);
226
+ console.log(
227
+ `\`limitcast ${cmd}\` is part of limitcast Pro: ${UPGRADE_URL}\nTry it free for 7 days: limitcast trial. Already bought it? limitcast activate <license-key>`,
228
+ );
189
229
  process.exit(2);
190
230
  }
191
231
  const since = now - days() * 86400_000;
@@ -215,7 +255,7 @@ if (cmd === 'status') {
215
255
  ? `✓ Turned off ${changed.length} Codex MCP servers (enabled = false in ${codexConfigPath()}): ${changed.map((s) => s.name).join(', ')}\nTakes effect in your next Codex session. Undo: limitcast trim --codex --undo`
216
256
  : 'Nothing to turn off: every server that is on was used.',
217
257
  );
218
- } else console.log(r.text);
258
+ } else console.log(forTerminal(r.text));
219
259
  process.exit(0);
220
260
  }
221
261
  /** @type {import('../src/trim.mjs').Activity} */
@@ -234,7 +274,9 @@ if (cmd === 'status') {
234
274
  }
235
275
  if (args.includes('--apply') || args.includes('--undo')) {
236
276
  if (!pro) {
237
- console.log(`\`limitcast trim --apply\` is part of limitcast Pro: ${UPGRADE_URL}\nAlready bought it? limitcast activate <license-key>`);
277
+ console.log(
278
+ `\`limitcast trim --apply\` is part of limitcast Pro: ${UPGRADE_URL}\nTry it free for 7 days: limitcast trial. Already bought it? limitcast activate <license-key>`,
279
+ );
238
280
  process.exit(2);
239
281
  }
240
282
  console.log(args.includes('--undo') ? undoMessage(undoTrim()) : applyMessage(latest, used));
@@ -243,7 +285,7 @@ if (cmd === 'status') {
243
285
  if (latest && (args.includes('--share') || !pro)) text = shareSummary(baseline(usage), latest, used, days());
244
286
  else text = latest ? startupReport(baseline(usage), latest, used, days()) : trimReport(baseline(usage), contributors(), used, days());
245
287
  if (!pro)
246
- text += `\n\nPro names each item and what it costs, so you can cut it: ${UPGRADE_URL}\nAlready bought it? limitcast activate <license-key>`;
288
+ text += `\n\nPro names each item and what it costs, so you can cut it: ${UPGRADE_URL}\nTry it free for 7 days: limitcast trial. Already bought it? limitcast activate <license-key>`;
247
289
  else if (latest && !args.includes('--share')) {
248
290
  const still = stillLoading(latest);
249
291
  text += still.length
@@ -257,7 +299,7 @@ if (cmd === 'status') {
257
299
  if (out) {
258
300
  writeFileSync(out, `${text}\n`);
259
301
  console.log(`Wrote ${out}`);
260
- } else console.log(text);
302
+ } else console.log(forTerminal(text));
261
303
  } else if (cmd === 'drift') {
262
304
  // SessionStart hook: tells the user (systemMessage, never the model's context) when starting context grew.
263
305
  const hook = args.includes('--hook');
@@ -270,6 +312,12 @@ if (cmd === 'status') {
270
312
  const d = latest ? recordOverhead(snapshot(latest)) : null;
271
313
  if (hook) {
272
314
  const lines = d?.alert ? [driftMessage(d)] : [];
315
+ // Claude Code may have rewritten the files `trim --apply` changed: put the cuts back for the next session.
316
+ const re = reapplyTrim();
317
+ if (re.reapplied.length)
318
+ lines.push(
319
+ `limitcast: Claude Code had undone ${re.reapplied.length} of your trim cuts; they're back from your next session. (limitcast trim --undo to drop them)`,
320
+ );
273
321
  // Once a week, what limitcast did: shown to the user at session start, never to the model.
274
322
  if (weeklyDue(now)) {
275
323
  const since = now - 7 * 86400_000;
@@ -288,7 +336,7 @@ if (cmd === 'status') {
288
336
  if (lines.length) console.log(JSON.stringify({ systemMessage: lines.join('\n') }));
289
337
  } else if (!latest) console.log('No interactive Claude Code session found yet.');
290
338
  else if (!d) console.log('Starting context recorded. limitcast will tell you when it grows.');
291
- else console.log(d.alert ? driftMessage(d) : 'No meaningful change in your starting context since the last session.');
339
+ else console.log(d.alert ? forTerminal(driftMessage(d)) : 'No meaningful change in your starting context since the last session.');
292
340
  } catch (e) {
293
341
  if (!hook) throw e; // a hook must never break session start
294
342
  }
@@ -300,7 +348,9 @@ if (cmd === 'status') {
300
348
  const latest = await latestInteractiveTranscript(claudeRoot());
301
349
  if (latest) recordOverhead(snapshot(latest));
302
350
  const s = loadOverhead();
303
- console.log(s ? savedSummary(s, await countInteractiveSince(claudeRoot(), s.first.at)) : 'Nothing measured yet. Run `limitcast trim` first.');
351
+ console.log(
352
+ forTerminal(s ? savedSummary(s, await countInteractiveSince(claudeRoot(), s.first.at)) : 'Nothing measured yet. Run `limitcast trim` first.'),
353
+ );
304
354
  } else if (cmd === 'results') {
305
355
  // Free shows limits reached, how far ahead limitcast warned, and the guard preview; Pro adds real blocks and savings.
306
356
  const pro = isPro();
@@ -353,7 +403,7 @@ if (cmd === 'status') {
353
403
  opener.on('error', () => {});
354
404
  opener.unref();
355
405
  }
356
- } else console.log(resultsReport({ now, days: days(), samples, blocks, pro, saved, value: valueSection(totals, { now, pro }) }));
406
+ } else console.log(forTerminal(resultsReport({ now, days: days(), samples, blocks, pro, saved, value: valueSection(totals, { now, pro }) })));
357
407
  } else if (cmd === 'notify') {
358
408
  // Desktop notifications from the status line (Pro, opt-in).
359
409
  if (!isPro()) {
@@ -414,7 +464,13 @@ if (cmd === 'status') {
414
464
  const r = spawnSync(command[0], command.slice(1), { stdio: 'inherit' });
415
465
  process.exit(r.status ?? 1);
416
466
  } else if (cmd === 'rollup') {
417
- // Started daily in the background by the status line: keeps the value record current. Never prints.
467
+ // Started daily in the background by the status line: keeps the value record current and checks the setup.
468
+ // Never prints.
469
+ try {
470
+ saveHealth(await healthChecks());
471
+ } catch {
472
+ /* next time */
473
+ }
418
474
  try {
419
475
  await refreshValue();
420
476
  } catch {
@@ -432,7 +488,29 @@ if (cmd === 'status') {
432
488
  process.exit(res.ok ? 0 : 1);
433
489
  } else if (cmd === 'license') {
434
490
  const l = currentLicense();
435
- console.log(l === null ? `Free tier. Pro: ${UPGRADE_URL}` : l.ok ? `Pro: ${l.claims.e}` : `License problem: ${l.reason}`);
491
+ console.log(l === null ? trialLine() : l.ok ? `Pro: ${l.claims.e}` : `License problem: ${l.reason}`);
492
+ } else if (cmd === 'trial') {
493
+ // Pro for 7 days on this machine, no card, once.
494
+ if (currentLicense()?.ok) {
495
+ console.log('You already have Pro.');
496
+ process.exit(0);
497
+ }
498
+ const t = startTrial(now);
499
+ if (!t.ok) {
500
+ console.log(t.active ? `Your Pro trial is already running, until ${clock(t.ends)}.` : trialLine());
501
+ process.exit(t.active ? 0 : 2);
502
+ }
503
+ console.log(
504
+ [
505
+ `✓ Pro trial on: 7 days, until ${new Date(t.ends).toLocaleDateString()}. No card, nothing to cancel.`,
506
+ 'Try it:',
507
+ ' limitcast install --guard --alerts block runaway subagents, move them to Sonnet when a window is tight',
508
+ ' limitcast trim --apply cut the context you never use (limitcast trim --undo reverses it)',
509
+ ' limitcast notify on a desktop notification before you hit a limit',
510
+ ' limitcast results what it did for you, any time',
511
+ `Keep Pro after the trial: ${UPGRADE_URL}`,
512
+ ].join('\n'),
513
+ );
436
514
  } else if (cmd === '--version' || cmd === '-v') {
437
515
  console.log(VERSION);
438
516
  } else {
@@ -440,6 +518,90 @@ if (cmd === 'status') {
440
518
  process.exit(cmd && !['help', '--help', '-h'].includes(cmd) ? 1 : 0);
441
519
  }
442
520
 
521
+ /** Everything `doctor` checks: setup, data freshness, license, and whether each tool's logs still parse. */
522
+ async function healthChecks() {
523
+ // Readings are only stored when they change, so freshness comes from the last feed the status line saw.
524
+ let latest = 0;
525
+ try {
526
+ latest = JSON.parse(readFileSync(join(stateDir(), 'last-feed.json'), 'utf8')).at ?? 0;
527
+ } catch {
528
+ /* never fed */
529
+ }
530
+ const license = currentLicense();
531
+ const checks = doctor({ samplesAgeMs: latest ? now - latest : null, license });
532
+ if (license === null && trialStatus(now)) checks.push({ ok: true, line: trialLine() });
533
+ return [...checks, ...(await formatChecks())];
534
+ }
535
+
536
+ /**
537
+ * Remember the failing checks that need the user (not just "no reading yet": that fixes itself), for the
538
+ * status-line hint, and notify once when a new one appears.
539
+ * @param {{ok:boolean, line:string}[]} checks
540
+ */
541
+ function saveHealth(checks) {
542
+ const file = join(stateDir(), 'health.json');
543
+ const failed = checks.filter((c) => !c.ok && !/^(No Claude limit readings|Last Claude reading)/.test(c.line)).map((c) => c.line);
544
+ let before = [];
545
+ try {
546
+ before = JSON.parse(readFileSync(file, 'utf8')).failed ?? [];
547
+ } catch {
548
+ /* first check */
549
+ }
550
+ mkdirSync(stateDir(), { recursive: true });
551
+ writeFileSync(file, JSON.stringify({ at: now, failed }));
552
+ const fresh = failed.filter((l) => !before.includes(l));
553
+ if (fresh.length && isPro() && notifyEnabled()) send(`limitcast needs a fix: ${fresh[0]} Run: limitcast doctor`);
554
+ return failed;
555
+ }
556
+
557
+ /**
558
+ * Free installs: for one day a week, what the guard preview saw Pro would have done, e.g.
559
+ * "this week Pro would have stopped 2 subagents and moved 5 to Sonnet · limitcast trial". Silent when it's nothing.
560
+ * @param {number} t epoch ms
561
+ */
562
+ function freeWeeklyHint(t) {
563
+ const file = join(stateDir(), 'free-weekly.json');
564
+ let from = 0;
565
+ try {
566
+ from = JSON.parse(readFileSync(file, 'utf8')).from ?? 0;
567
+ } catch {
568
+ /* first run: start the clock */
569
+ }
570
+ const WEEK = 7 * 86400_000;
571
+ if (!from || t >= from + 86400_000) {
572
+ // First run starts a week out; afterwards the next day-long showing is a week after this one.
573
+ from = from ? from + Math.ceil((t - from - 86400_000 + 1) / WEEK) * WEEK : t + WEEK;
574
+ mkdirSync(stateDir(), { recursive: true });
575
+ writeFileSync(file, JSON.stringify({ from }));
576
+ }
577
+ if (t < from) return null;
578
+ const preview = loadBlocks(t - WEEK).filter((b) => b.shadow);
579
+ const stopped = preview.filter((b) => b.kind !== 'switch').length;
580
+ const moved = preview.length - stopped;
581
+ if (!stopped && !moved) return null;
582
+ const parts = [stopped ? `stopped ${stopped} subagent${stopped === 1 ? '' : 's'}` : '', moved ? `moved ${moved} to Sonnet` : ''].filter(Boolean);
583
+ return `this week Pro would have ${parts.join(' and ')} · limitcast trial`;
584
+ }
585
+
586
+ /** Free tier, a running trial, or an ended one, in one line. */
587
+ function trialLine() {
588
+ const t = trialStatus(now);
589
+ if (!t) return `Free tier. Try Pro free for 7 days, no card: limitcast trial. Buy: ${UPGRADE_URL}`;
590
+ if (t.active)
591
+ return `Pro trial: ${Math.ceil((t.ends - now) / 86400_000)} days left (until ${new Date(t.ends).toLocaleDateString()}). Keep Pro: ${UPGRADE_URL}`;
592
+ return `Pro trial ended ${new Date(t.ends).toLocaleDateString()}. Keep Pro: ${UPGRADE_URL}`;
593
+ }
594
+
595
+ /** The status-line hint while the last health check found something to fix. */
596
+ function healthHint() {
597
+ try {
598
+ const { failed } = JSON.parse(readFileSync(join(stateDir(), 'health.json'), 'utf8'));
599
+ return failed?.length ? '⚠ run limitcast doctor' : null;
600
+ } catch {
601
+ return null;
602
+ }
603
+ }
604
+
443
605
  /** Fold the last 8 days of readings and blocks, and any new sessions, into the long-term value record. */
444
606
  async function refreshValue() {
445
607
  const since = now - KEEP_MS;
@@ -449,6 +611,9 @@ async function refreshValue() {
449
611
  const start = Math.min(now, o?.first.at ?? now, ...claude.map((s) => s.t));
450
612
  const v = foldEvents(loadValue(), { now, samples: [...claude, ...(await readCodex(since))], blocks: loadBlocks(since), start });
451
613
  await scanSessions(v, { root: claudeRoot(), baseline: o ? { at: o.first.at, chars: o.first.chars } : null, now });
614
+ // Recalibrate from the last 8 days when there is enough data; keep the last good calibration otherwise.
615
+ const c = calibrate(claude, await readUsage(since, {}));
616
+ if (c) v.calib = { ...c, at: now };
452
617
  saveValue(v);
453
618
  return v;
454
619
  }
package/package.json CHANGED
@@ -1,16 +1,40 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.9.2",
3
+ "version": "0.10.1",
4
4
  "description": "Stretch your Claude Code plan: measure what every session loads before you type, cut what you never use, and stop runaway subagents before they burn your window.",
5
5
  "type": "module",
6
- "bin": { "limitcast": "bin/limitcast.mjs" },
7
- "files": ["bin", "src"],
8
- "engines": { "node": ">=20" },
9
- "os": ["darwin", "linux"],
10
- "scripts": { "test": "node --test" },
11
- "keywords": ["claude-code", "codex", "rate-limit", "usage-limit", "tokens", "hooks", "status-line", "ai-agents"],
6
+ "bin": {
7
+ "limitcast": "bin/limitcast.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src"
12
+ ],
13
+ "engines": {
14
+ "node": ">=20"
15
+ },
16
+ "os": [
17
+ "darwin",
18
+ "linux"
19
+ ],
20
+ "scripts": {
21
+ "test": "node --test"
22
+ },
23
+ "keywords": [
24
+ "claude-code",
25
+ "codex",
26
+ "rate-limit",
27
+ "usage-limit",
28
+ "tokens",
29
+ "hooks",
30
+ "status-line",
31
+ "ai-agents"
32
+ ],
12
33
  "homepage": "https://limitcast.dev",
13
- "repository": { "type": "git", "url": "git+https://github.com/SamStull9007/limitcast.git" },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/SamStull9007/limitcast.git"
37
+ },
14
38
  "author": "Sam Stull",
15
39
  "license": "Elastic-2.0"
16
40
  }
package/src/apply.mjs CHANGED
@@ -189,6 +189,52 @@ export function undoTrim({ settings = settingsPath(), claudeJson = claudeJsonPat
189
189
  return last;
190
190
  }
191
191
 
192
+ /**
193
+ * Keep the last --apply in place. A running Claude Code session can rewrite ~/.claude.json (or settings) and drop
194
+ * every change at once: then put them back. When only some are gone, you turned those back on yourself (/mcp,
195
+ * /skills): leave them and forget them, so limitcast never fights your choice. Checked per file.
196
+ * @param {{settings?:string, claudeJson?:string}} [o]
197
+ * @returns {{reapplied:string[], released:string[]}}
198
+ */
199
+ export function reapplyTrim({ settings = settingsPath(), claudeJson = claudeJsonPath() } = {}) {
200
+ const ledger = loadLedger();
201
+ const last = ledger.at(-1);
202
+ const out = { reapplied: /** @type {string[]} */ ([]), released: /** @type {string[]} */ ([]) };
203
+ if (!last) return out;
204
+ if (last.skills.length && existsSync(settings)) {
205
+ const cfg = readSettings(settings);
206
+ const gone = last.skills.filter((s) => cfg.skillOverrides?.[s.name] !== 'user-invocable-only');
207
+ if (gone.length === last.skills.length) {
208
+ cfg.skillOverrides ??= {};
209
+ for (const s of gone) cfg.skillOverrides[s.name] = 'user-invocable-only';
210
+ backup(settings);
211
+ writeJson(settings, cfg);
212
+ out.reapplied.push(...gone.map((s) => s.name));
213
+ } else if (gone.length) {
214
+ last.skills = last.skills.filter((s) => !gone.includes(s));
215
+ out.released.push(...gone.map((s) => s.name));
216
+ }
217
+ }
218
+ if (last.mcp.length && existsSync(claudeJson)) {
219
+ const cj = readSettings(claudeJson);
220
+ const list = cj.projects?.[last.cwd]?.disabledMcpServers ?? [];
221
+ const gone = last.mcp.filter((n) => !list.includes(n));
222
+ if (gone.length === last.mcp.length) {
223
+ cj.projects ??= {};
224
+ cj.projects[last.cwd] ??= {};
225
+ cj.projects[last.cwd].disabledMcpServers = [...list, ...gone];
226
+ backup(claudeJson);
227
+ writeJson(claudeJson, cj);
228
+ out.reapplied.push(...gone);
229
+ } else if (gone.length) {
230
+ last.mcp = last.mcp.filter((n) => !gone.includes(n));
231
+ out.released.push(...gone);
232
+ }
233
+ }
234
+ if (out.released.length) writeJson(ledgerPath(), ledger);
235
+ return out;
236
+ }
237
+
192
238
  /**
193
239
  * Items an earlier --apply turned off that still loaded in a session started after it
194
240
  * (for example, a running Claude Code session rewrote ~/.claude.json).
@@ -0,0 +1,69 @@
1
+ // @ts-check
2
+ import { claudeAccounts } from './forecast.mjs';
3
+
4
+ // How many tokens move this user's Claude 5-hour meter by 1%, from their own readings and transcripts.
5
+ // Each pair of consecutive readings of one account's window where usage rose is one observation: the rise
6
+ // against the tokens that account's sessions used in between, split into new tokens (input, cache writes,
7
+ // output) and cache reads, which count far less. Least squares with no intercept gives % per token of each.
8
+
9
+ /** @typedef {import('./forecast.mjs').Sample} Sample */
10
+ /** @typedef {import('./usage.mjs').Usage} Usage */
11
+
12
+ const MIN_OBS = 30;
13
+
14
+ /**
15
+ * @param {Sample[]} samples
16
+ * @param {Usage[]} usage
17
+ * @returns {{fresh:number, read:number, n:number}|null} % of the 5h window per million new / cached tokens
18
+ */
19
+ export function calibrate(samples, usage) {
20
+ const obs = [];
21
+ const claude = usage.filter((u) => u.src === 'claude').sort((a, b) => a.t - b.t);
22
+ for (const acct of claudeAccounts(samples)) {
23
+ const sids = new Set(acct.map((s) => s.sid));
24
+ const mine = claude.filter((u) => sids.has(u.session));
25
+ const w5 = acct.filter((s) => s.win === '5h').sort((a, b) => a.t - b.t);
26
+ for (let i = 1; i < w5.length; i++) {
27
+ const p = w5[i - 1];
28
+ const c = w5[i];
29
+ if (Math.abs(c.reset - p.reset) > 120 || c.pct <= p.pct) continue;
30
+ let f = 0;
31
+ let r = 0;
32
+ for (const u of mine) {
33
+ if (u.t <= p.t) continue;
34
+ if (u.t > c.t) break;
35
+ f += u.input + u.cacheWrite + u.output;
36
+ r += u.cacheRead;
37
+ }
38
+ if (f + r > 0) obs.push({ d: c.pct - p.pct, f: f / 1e6, r: r / 1e6 });
39
+ }
40
+ }
41
+ if (obs.length < MIN_OBS) return null;
42
+ let ff = 0;
43
+ let rr = 0;
44
+ let fr = 0;
45
+ let fd = 0;
46
+ let rd = 0;
47
+ for (const o of obs) {
48
+ ff += o.f * o.f;
49
+ rr += o.r * o.r;
50
+ fr += o.f * o.r;
51
+ fd += o.f * o.d;
52
+ rd += o.r * o.d;
53
+ }
54
+ const det = ff * rr - fr * fr;
55
+ if (!det) return null;
56
+ const fresh = (fd * rr - rd * fr) / det;
57
+ const read = (rd * ff - fd * fr) / det;
58
+ // Both must count, and new tokens must count more than cached ones; anything else is noise, not a calibration.
59
+ if (!(fresh > 0 && read > 0 && fresh > read)) return null;
60
+ return { fresh, read, n: obs.length };
61
+ }
62
+
63
+ /**
64
+ * What a smaller starting context was worth against the 5-hour limit, in % of one window: each session writes its
65
+ * starting context once (new tokens) and re-reads it on every call (cached tokens).
66
+ * @param {{fresh:number, read:number}} c
67
+ * @param {{writes:number, reads:number}} saved tokens not written / not re-read
68
+ */
69
+ export const windowPct = (c, saved) => (saved.writes / 1e6) * c.fresh + (saved.reads / 1e6) * c.read;
package/src/install.mjs CHANGED
@@ -3,6 +3,7 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, writeF
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import { stateDir } from './store.mjs';
6
7
 
7
8
  export const settingsPath = () => join(process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude'), 'settings.json');
8
9
  export const codexHooksPath = () => join(process.env.CODEX_HOME ?? join(homedir(), '.codex'), 'hooks.json');
@@ -13,10 +14,62 @@ const CODEX_MATCHER = '.*spawn_agent.*';
13
14
  /** Shell-quote one argument. @param {string} s */
14
15
  const q = (s) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
15
16
 
16
- /** The command that runs this copy of limitcast: absolute node + script, so hooks work without PATH. */
17
+ /**
18
+ * The command hooks run: a launcher script in the state dir that runs this copy of limitcast (absolute node +
19
+ * script, so hooks work without PATH) and outlives a Node upgrade, which moves both under nvm and Homebrew.
20
+ */
17
21
  export function selfCommand() {
18
- const bin = realpathSync(fileURLToPath(new URL('../bin/limitcast.mjs', import.meta.url)));
19
- return `${q(process.execPath)} ${q(bin)}`;
22
+ return `/bin/sh ${q(writeLauncher())}`;
23
+ }
24
+
25
+ export const launcherPath = () => join(stateDir(), 'limitcast-hook.sh');
26
+
27
+ /**
28
+ * Write the hook launcher. If this node or script is gone, it runs `limitcast` from PATH; if that is gone too,
29
+ * the status line still runs your own wrapped command and every other hook allows (exit 0).
30
+ * @returns {string} its path
31
+ */
32
+ export function writeLauncher(node = process.execPath, bin = realpathSync(fileURLToPath(new URL('../bin/limitcast.mjs', import.meta.url)))) {
33
+ const path = launcherPath();
34
+ mkdirSync(stateDir(), { recursive: true });
35
+ writeFileSync(
36
+ path,
37
+ [
38
+ '#!/bin/sh',
39
+ '# limitcast hook launcher, written by `limitcast install`. Survives Node upgrades.',
40
+ `NODE=${q(node)}`,
41
+ `BIN=${q(bin)}`,
42
+ 'if [ -x "$NODE" ] && [ -f "$BIN" ]; then exec "$NODE" "$BIN" "$@"; fi',
43
+ 'PATH="$PATH:/opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin"',
44
+ 'if command -v limitcast >/dev/null 2>&1; then exec limitcast "$@"; fi',
45
+ '# limitcast is gone: keep your status line working, allow every hook.',
46
+ 'if [ "$1" = statusline ]; then',
47
+ ' while [ $# -gt 0 ] && [ "$1" != -- ]; do shift; done',
48
+ ' if [ $# -gt 0 ]; then shift; exec "$@"; fi',
49
+ 'fi',
50
+ 'exit 0',
51
+ '',
52
+ ].join('\n'),
53
+ { mode: 0o755 },
54
+ );
55
+ return path;
56
+ }
57
+
58
+ /**
59
+ * The node and script a launcher points at (null when it isn't a launcher).
60
+ * @param {string} path
61
+ */
62
+ export function launcherTargets(path) {
63
+ try {
64
+ const text = readFileSync(path, 'utf8');
65
+ const val = (/** @type {string} */ k) => {
66
+ const m = new RegExp(`^${k}=(?:'((?:[^']|'\\\\'')*)'|(\\S+))$`, 'm').exec(text);
67
+ return m ? (m[1] ?? m[2]).replace(/'\\''/g, "'") : null;
68
+ };
69
+ return { node: val('NODE'), bin: val('BIN') };
70
+ } catch {
71
+ return null;
72
+ }
20
73
  }
21
74
 
22
75
  /**
@@ -131,6 +184,19 @@ export function wrappedCommand(command) {
131
184
  return plain ? plain[1] : rest;
132
185
  }
133
186
 
187
+ /**
188
+ * Which optional parts are installed, so `doctor --fix` can re-install exactly those.
189
+ * @param {string} [path]
190
+ */
191
+ export function installedFeatures(path = settingsPath()) {
192
+ const cfg = readSettings(path);
193
+ return {
194
+ statusLine: Boolean(cfg.statusLine?.command?.includes(MARK)),
195
+ guard: (cfg.hooks?.PreToolUse ?? []).some(isGuard),
196
+ alerts: (cfg.hooks?.SessionStart ?? []).some(isAlert),
197
+ };
198
+ }
199
+
134
200
  /** @param {any} h */
135
201
  const isGuard = (h) =>
136
202
  (h.hooks ?? []).some((/** @type {any} */ x) => typeof x.command === 'string' && x.command.includes(MARK) && /\bguard\b/.test(x.command));
@@ -206,13 +272,27 @@ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), sa
206
272
  ok: sl.includes(MARK),
207
273
  line: sl.includes(MARK) ? 'Status-line recorder installed' : 'Status-line recorder missing: run `limitcast install`',
208
274
  });
209
- const exe = sl.match(/^'([^']+)'|^(\S+)/);
210
- const exePath = exe?.[1] ?? exe?.[2];
211
- if (sl.includes(MARK) && exePath?.startsWith('/')) {
275
+ const launcher = /^\/bin\/sh '?([^' ]+limitcast-hook\.sh)'?/.exec(sl)?.[1];
276
+ const targets = launcher ? launcherTargets(launcher) : null;
277
+ if (sl.includes(MARK) && targets) {
278
+ const ok = Boolean(targets.node && existsSync(targets.node) && targets.bin && existsSync(targets.bin));
212
279
  out.push({
213
- ok: existsSync(exePath),
214
- line: existsSync(exePath) ? 'Node path in settings exists' : `Node path in settings is gone (${exePath}): run \`limitcast install\` again`,
280
+ ok,
281
+ line: ok
282
+ ? 'Hook launcher points at this Node and limitcast'
283
+ : 'Node or limitcast moved (a Node upgrade?): hooks fall back to `limitcast` on PATH. Fix: `limitcast doctor --fix`',
215
284
  });
285
+ } else if (sl.includes(MARK)) {
286
+ // Installed before 0.10: settings call node directly.
287
+ const exe = sl.match(/^'([^']+)'|^(\S+)/);
288
+ const exePath = exe?.[1] ?? exe?.[2];
289
+ if (exePath?.startsWith('/'))
290
+ out.push({
291
+ ok: existsSync(exePath),
292
+ line: existsSync(exePath)
293
+ ? 'Node path in settings exists (`limitcast doctor --fix` switches to the upgrade-proof launcher)'
294
+ : `Node path in settings is gone (${exePath}): run \`limitcast doctor --fix\``,
295
+ });
216
296
  }
217
297
  const guard = /** @type {any} */ (cfg.hooks?.PreToolUse ?? []).some(isGuard);
218
298
  out.push({
package/src/license.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  // @ts-check
2
2
  import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
3
3
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
- import { join } from 'node:path';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join } from 'node:path';
5
6
  import { loadPolar, polarStatus } from './polar.mjs';
6
7
  import { stateDir } from './store.mjs';
7
8
 
@@ -68,4 +69,42 @@ export function activate(key) {
68
69
  return res;
69
70
  }
70
71
 
71
- export const isPro = () => currentLicense()?.ok === true;
72
+ export const isPro = () => currentLicense()?.ok === true || trialStatus()?.active === true;
73
+
74
+ const TRIAL_MS = 7 * 86400_000;
75
+ const trialFile = () => join(stateDir(), 'trial.json');
76
+ // A second marker outside the state dir, so clearing limitcast's state doesn't restart the trial.
77
+ // shortcut: a determined user can still delete both; fine at this price, move to a server check if it matters.
78
+ const trialMarker = () => join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'limitcast', 'trial-used');
79
+
80
+ /**
81
+ * The no-card Pro trial on this machine: active, or when it ended. null if never started.
82
+ * @param {number} [now]
83
+ */
84
+ export function trialStatus(now = Date.now()) {
85
+ let start = 0;
86
+ for (const f of [trialFile(), trialMarker()]) {
87
+ try {
88
+ start ||= Number(JSON.parse(readFileSync(f, 'utf8')).start) || 0;
89
+ } catch {
90
+ /* not this one */
91
+ }
92
+ }
93
+ if (!start) return null;
94
+ const ends = start + TRIAL_MS;
95
+ return { active: now < ends, ends };
96
+ }
97
+
98
+ /**
99
+ * Start the 7-day trial, once per machine.
100
+ * @param {number} [now]
101
+ */
102
+ export function startTrial(now = Date.now()) {
103
+ const existing = trialStatus(now);
104
+ if (existing) return { ok: false, ...existing };
105
+ for (const f of [trialFile(), trialMarker()]) {
106
+ mkdirSync(dirname(f), { recursive: true });
107
+ writeFileSync(f, JSON.stringify({ start: now }));
108
+ }
109
+ return { ok: true, active: true, ends: now + TRIAL_MS };
110
+ }
package/src/term.mjs ADDED
@@ -0,0 +1,13 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * The Markdown reports for a person at a terminal: headings and **bold** in bold, markers gone.
5
+ * Piped or written to a file, the Markdown is left as is. NO_COLOR drops the styling, not the cleanup.
6
+ * @param {string} md
7
+ * @param {{tty?: boolean, color?: boolean}} [o]
8
+ */
9
+ export function forTerminal(md, { tty = process.stdout.isTTY === true, color = !process.env.NO_COLOR } = {}) {
10
+ if (!tty) return md;
11
+ const b = color ? (/** @type {string} */ s) => `\x1b[1m${s}\x1b[22m` : (/** @type {string} */ s) => s;
12
+ return md.replace(/^#{1,6} (.+)$/gm, (_, h) => b(h)).replace(/\*\*(.+?)\*\*/g, (_, s) => b(s));
13
+ }
package/src/usage.mjs CHANGED
@@ -1,8 +1,9 @@
1
1
  // @ts-check
2
- import { createReadStream, existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { basename, join } from 'node:path';
5
5
  import { createInterface } from 'node:readline';
6
+ import { stateDir } from './store.mjs';
6
7
 
7
8
  /**
8
9
  * One model response's token usage.
@@ -166,24 +167,58 @@ function grokLedgers(root, since) {
166
167
  export async function readUsage(since, roots = {}, activity) {
167
168
  /** @type {Usage[]} */
168
169
  const out = [];
170
+ // Parsed transcripts are cached by size and mtime: only new or changed ones are read again.
171
+ const cache = loadUsageCache();
172
+ /** @type {typeof cache} */
173
+ const next = {};
174
+ /**
175
+ * @param {string} file
176
+ * @param {(file:string)=>Promise<{u:Usage[], a?:{skills:string[], mcp:string[]}}>} parse
177
+ */
178
+ const cached = async (file, parse) => {
179
+ const st = statSync(file);
180
+ const hit = cache[file];
181
+ const entry = hit && hit.s === st.size && hit.m === st.mtimeMs ? hit : { s: st.size, m: st.mtimeMs, ...(await parse(file)) };
182
+ next[file] = entry;
183
+ return entry;
184
+ };
169
185
  for (const file of jsonlFiles(roots.claude ?? claudeRoot(), since, () => true)) {
170
- const seen = new Set();
171
- const session = basename(file, '.jsonl');
172
- for await (const line of lines(file)) {
173
- if (activity) claudeActivity(line, activity);
174
- const u = claudeUsage(line, seen, session);
175
- if (u && u.t >= since) out.push(u);
186
+ const e = await cached(file, async (f) => {
187
+ const seen = new Set();
188
+ const session = basename(f, '.jsonl');
189
+ /** @type {import('./trim.mjs').Activity} */
190
+ const act = { skills: new Set(), mcp: new Set() };
191
+ const u = [];
192
+ for await (const line of lines(f)) {
193
+ claudeActivity(line, act);
194
+ const x = claudeUsage(line, seen, session);
195
+ if (x) u.push(x);
196
+ }
197
+ return { u, a: { skills: [...act.skills], mcp: [...act.mcp] } };
198
+ });
199
+ for (const u of e.u) if (u.t >= since) out.push(u);
200
+ if (activity && e.a) {
201
+ for (const s of e.a.skills) activity.skills.add(s);
202
+ for (const m of e.a.mcp) activity.mcp.add(m);
176
203
  }
177
204
  }
178
205
  for (const file of jsonlFiles(roots.codex ?? codexRoot(), since, (n) => n.startsWith('rollout-'))) {
179
- const st = { prev: null, cwd: '', model: '' };
180
- // rollout-2026-10-23T18-39-41-<session uuid>.jsonl → the uuid
181
- const session = basename(file, '.jsonl').replace(/^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-/, '');
182
- for await (const line of lines(file)) {
183
- const u = codexUsage(line, st, session);
184
- if (u && u.t >= since) out.push(u);
185
- }
206
+ const e = await cached(file, async (f) => {
207
+ const st = { prev: null, cwd: '', model: '' };
208
+ // rollout-2026-10-23T18-39-41-<session uuid>.jsonl → the uuid
209
+ const session = basename(f, '.jsonl').replace(/^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-/, '');
210
+ const u = [];
211
+ for await (const line of lines(f)) {
212
+ const x = codexUsage(line, st, session);
213
+ if (x) u.push(x);
214
+ }
215
+ return { u };
216
+ });
217
+ for (const u of e.u) if (u.t >= since) out.push(u);
186
218
  }
219
+ // Keep entries for files this run didn't need (another period) while they are recent; drop the rest.
220
+ for (const [f, e] of Object.entries(cache)) if (!next[f] && e.m >= Date.now() - CACHE_KEEP_MS && existsSync(f)) next[f] = e;
221
+ saveUsageCache(next);
187
222
  for (const { file, session, project } of grokLedgers(roots.grok ?? grokRoot(), since)) {
188
223
  let ledger;
189
224
  try {
@@ -196,6 +231,28 @@ export async function readUsage(since, roots = {}, activity) {
196
231
  return out;
197
232
  }
198
233
 
234
+ const CACHE_KEEP_MS = 35 * 86400_000;
235
+ const usageCacheFile = () => join(stateDir(), 'usage-cache.json');
236
+
237
+ /** @returns {Record<string, {s:number, m:number, u:Usage[], a?:{skills:string[], mcp:string[]}}>} */
238
+ function loadUsageCache() {
239
+ try {
240
+ return JSON.parse(readFileSync(usageCacheFile(), 'utf8'));
241
+ } catch {
242
+ return {};
243
+ }
244
+ }
245
+
246
+ /** @param {ReturnType<typeof loadUsageCache>} c */
247
+ function saveUsageCache(c) {
248
+ try {
249
+ mkdirSync(stateDir(), { recursive: true });
250
+ writeFileSync(usageCacheFile(), JSON.stringify(c));
251
+ } catch {
252
+ /* a cache: the next run just reads the transcripts */
253
+ }
254
+ }
255
+
199
256
  /** @param {string} s */
200
257
  function safeDecode(s) {
201
258
  try {
package/src/value.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  import { createReadStream, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { createInterface } from 'node:readline';
5
+ import { windowPct } from './calibrate.mjs';
5
6
  import { blockOutcomes, limitHits } from './results.mjs';
6
7
  import { startupBreakdown } from './startup.mjs';
7
8
  import { stateDir } from './store.mjs';
@@ -15,7 +16,7 @@ import { claudeUsage } from './usage.mjs';
15
16
  /** @typedef {{at:number, turns:number, savedPerTurn:number}} SessionValue savedPerTurn: tokens below the first measured start */
16
17
  /** @typedef {{src:string, win:string, at:number, lead:number|null, unseen:boolean}} HitValue lead: minutes of warning */
17
18
  /** @typedef {{t:number, src:string, win:string, shadow:boolean, outcome:string}} BlockValue */
18
- /** @typedef {{since:number, scanned:number, sessions:Record<string, SessionValue>, hits:Record<string, HitValue>, blocks:Record<string, BlockValue>, switches?:Record<string, {shadow:boolean}>}} Value */
19
+ /** @typedef {{since:number, scanned:number, sessions:Record<string, SessionValue>, hits:Record<string, HitValue>, blocks:Record<string, BlockValue>, switches?:Record<string, {shadow:boolean}>, calib?:{fresh:number, read:number, n:number, at:number}}} Value */
19
20
 
20
21
  const file = () => join(stateDir(), 'value.json');
21
22
  const tok = (/** @type {number} */ chars) => Math.round(chars / 4);
@@ -154,6 +155,14 @@ export function valueTotals(v) {
154
155
  confirmed: blocks.filter((b) => b.outcome === 'hit').length,
155
156
  switched: Object.values(v.switches ?? {}).filter((s) => !s.shadow).length,
156
157
  switchPreviewed: Object.values(v.switches ?? {}).filter((s) => s.shadow).length,
158
+ calib: v.calib ?? null,
159
+ // Against the 5-hour limit: each session wrote its smaller start once and re-read it on every call.
160
+ windowPct: v.calib
161
+ ? windowPct(v.calib, {
162
+ writes: sessions.reduce((a, s) => a + s.savedPerTurn, 0),
163
+ reads: sessions.reduce((a, s) => a + s.turns * s.savedPerTurn, 0),
164
+ })
165
+ : null,
157
166
  };
158
167
  }
159
168
 
@@ -170,6 +179,10 @@ export function valueSection(t, { now, pro }) {
170
179
  out.push(
171
180
  `- **${fmtBig(t.tokens)} tokens not re-sent.** Your sessions now start smaller than the first one limitcast measured, and Claude Code re-sends the starting context on every model call: ${t.turns.toLocaleString()} calls across ${t.sessions} sessions. (Most of it would have been cached input.)`,
172
181
  );
182
+ if (t.windowPct !== null && t.calib)
183
+ out.push(
184
+ ` Against your limit: **≈ ${t.windowPct < 1 ? t.windowPct.toFixed(2) : t.windowPct.toFixed(1)}% of a 5-hour window.** From your own readings, 1% of it is about ${fmtBig(Math.round(1e6 / t.calib.fresh))} new tokens or ${fmtBig(Math.round(1e6 / t.calib.read))} cached ones, so cached context is cheap and new tokens (long sessions, subagents) are what run you out.`,
185
+ );
173
186
  } else if (t.sessions) {
174
187
  out.push(`- Starting context: no smaller than when limitcast first measured it. \`limitcast trim\` shows what to cut.`);
175
188
  }