limitcast 0.18.1 → 0.18.3

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/bin/limitcast.mjs CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  applyBlocked,
10
10
  applyTrim,
11
11
  claudeJsonPath,
12
+ editKeep,
12
13
  ensureDefaultKeep,
13
14
  getKeep,
14
15
  installedPlugins,
@@ -17,7 +18,6 @@ import {
17
18
  planTrim,
18
19
  projectMcpServers,
19
20
  reapplyTrim,
20
- setKeep,
21
21
  stillLoading,
22
22
  transcriptCwd,
23
23
  undoTrim,
@@ -25,6 +25,7 @@ import {
25
25
  import { calibrate, limitChange, limitChangeMessage, windowPct } from '../src/calibrate.mjs';
26
26
  import { applyCodexTrim, codexConfigPath, codexServers, codexStartup, codexTrimReport, codexUsedServers, undoCodexTrim } from '../src/codex.mjs';
27
27
  import { coldCost, coldMessage, coldNotice, firstNotice, firstWarning } from '../src/cold.mjs';
28
+ import { unknownFlag } from '../src/flags.mjs';
28
29
  import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
29
30
  import { formatChecks } from '../src/formats.mjs';
30
31
  import {
@@ -168,6 +169,14 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
168
169
 
169
170
  const [cmd, ...args] = process.argv.slice(2);
170
171
  const now = Date.now();
172
+ // Hooks run unattended and fail open; everything else rejects a mistyped option instead of ignoring it.
173
+ const typo = ['guard', 'prompt-check', 'tool-check', 'tool-limit', 'subagent-receipt', 'drift', 'statusline'].includes(cmd)
174
+ ? undefined
175
+ : unknownFlag(args);
176
+ if (typo) {
177
+ console.error(`Unknown option ${typo}. Run "limitcast help" for the options.`);
178
+ process.exit(1);
179
+ }
171
180
  const flag = (/** @type {string} */ name) => {
172
181
  const i = args.indexOf(name);
173
182
  return i >= 0 ? args[i + 1] : undefined;
@@ -714,7 +723,7 @@ if (cmd === 'status') {
714
723
  .split(',')
715
724
  .map((n) => n.trim())
716
725
  .filter(Boolean);
717
- if (names.length) setKeep(drop ? getKeep().filter((k) => !isKept(names, k)) : [...getKeep(), ...names]);
726
+ if (names.length) editKeep((keep) => (drop ? keep.filter((k) => !isKept(names, k)) : [...keep, ...names]));
718
727
  const keep = getKeep();
719
728
  console.log(keep.length ? `Kept by \`trim --apply\`: ${keep.join(', ')}` : 'Nothing on the keep-list. Example: limitcast trim keep ego-browser');
720
729
  process.exit(0);
@@ -909,9 +918,10 @@ if (cmd === 'status') {
909
918
  }
910
919
  const samples = [...load(since), ...(await readCodex(since))];
911
920
  const blocks = loadBlocks(since);
912
- const value = await refreshValue();
921
+ const usage = await readUsage(Math.min(since - days() * 86400_000, now - KEEP_MS), {}); // one read feeds both below
922
+ const value = await refreshValue(usage);
913
923
  const totals = valueTotals(value);
914
- const insight = periodInsights({ value, usage: await readUsage(since - days() * 86400_000, {}), blocks, since, until: now });
924
+ const insight = periodInsights({ value, usage: usage.filter((u) => u.t >= since - days() * 86400_000), blocks, since, until: now });
915
925
  if (args.includes('--share'))
916
926
  console.log(
917
927
  resultsShare(resultsStats({ now, days: days(), samples, blocks, pro }), {
@@ -926,7 +936,10 @@ if (cmd === 'status') {
926
936
  else if (args.includes('--html')) {
927
937
  // results, the current windows and the burn report on one page, opened in the browser.
928
938
  const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS))]), now);
929
- const burn = burnReport(await readUsage(since, {}), { since, now }).replace(/^(#{1,2}) /gm, '#$1 ');
939
+ const burn = burnReport(
940
+ usage.filter((u) => u.t >= since),
941
+ { since, now },
942
+ ).replace(/^(#{1,2}) /gm, '#$1 ');
930
943
  const md = [
931
944
  insightsReport(insight, pro),
932
945
  resultsReport({
@@ -1107,8 +1120,11 @@ function healthHint() {
1107
1120
  }
1108
1121
  }
1109
1122
 
1110
- /** Fold the last 8 days of readings and blocks, and any new sessions, into the long-term value record. */
1111
- async function refreshValue() {
1123
+ /**
1124
+ * Fold the last 8 days of readings and blocks, and any new sessions, into the long-term value record.
1125
+ * @param {import('../src/usage.mjs').Usage[]} [preread] usage already read since at least KEEP_MS ago, to skip a second walk of the transcripts
1126
+ */
1127
+ async function refreshValue(preread) {
1112
1128
  const since = now - KEEP_MS;
1113
1129
  const claude = load(since);
1114
1130
  recordPeaks(claude, now); // the long-lived record of window peaks behind `limitcast plan`
@@ -1118,7 +1134,7 @@ async function refreshValue() {
1118
1134
  const v = foldEvents(loadValue(), { now, samples: [...claude, ...(await readCodex(since))], blocks: loadBlocks(since), start });
1119
1135
  await scanSessions(v, { root: claudeRoot(), baseline: o ? { at: o.first.at, chars: o.first.chars } : null, now });
1120
1136
  // Recalibrate from the last 8 days when there is enough data; keep the last good calibration otherwise.
1121
- const usage = await readUsage(since, {});
1137
+ const usage = preread ? preread.filter((u) => u.t >= since) : await readUsage(since, {});
1122
1138
  const c = calibrate(claude, usage);
1123
1139
  if (c) v.calib = { ...c, at: now };
1124
1140
  // Once a day, the last 3 days on their own: a lasting shift against earlier days means the limit itself changed.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.18.1",
3
+ "version": "0.18.3",
4
4
  "description": "Claude Code usage limits: forecast Codex and Grok too.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/apply.mjs CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  import { homedir } from 'node:os';
17
17
  import { join } from 'node:path';
18
18
  import { readSettings, settingsPath } from './install.mjs';
19
- import { stateDir } from './store.mjs';
19
+ import { stateDir, updateConfig } from './store.mjs';
20
20
 
21
21
  // `trim --apply`: hide unused skills and turn off unused MCP servers through Claude Code's own settings.
22
22
  // Skills: `skillOverrides` in ~/.claude/settings.json ("user-invocable-only": the model stops seeing it, /name still works).
@@ -39,11 +39,13 @@ export const DEFAULT_KEEP = ['ego-browser'];
39
39
  export const APPLY_BLOCKED =
40
40
  'Nothing on the keep-list, so `trim --apply` would turn off every server that looks unused, including ego-browser. Run `limitcast trim keep ego-browser` first, or repeat with `--yes`.';
41
41
 
42
+ const keepFrom = (/** @type {any} */ cfg) =>
43
+ Array.isArray(cfg.trimKeep) ? cfg.trimKeep.filter((/** @type {unknown} */ n) => typeof n === 'string') : [];
44
+
42
45
  /** Names `trim --apply` never turns off or hides, from `limitcast trim keep`. @returns {string[]} */
43
46
  export function getKeep() {
44
47
  try {
45
- const k = JSON.parse(readFileSync(configFile(), 'utf8')).trimKeep;
46
- return Array.isArray(k) ? k.filter((n) => typeof n === 'string') : [];
48
+ return keepFrom(JSON.parse(readFileSync(configFile(), 'utf8')));
47
49
  } catch {
48
50
  return [];
49
51
  }
@@ -54,32 +56,29 @@ export function getKeep() {
54
56
  * @returns {{keep:string[], seeded:boolean}}
55
57
  */
56
58
  export function ensureDefaultKeep() {
57
- let cfg = {};
58
- try {
59
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
60
- } catch {
61
- cfg = {};
62
- }
63
- if (Object.hasOwn(cfg, 'trimKeep')) return { keep: getKeep(), seeded: false };
64
- setKeep(DEFAULT_KEEP);
65
- return { keep: [...DEFAULT_KEEP], seeded: true };
59
+ let seeded = false;
60
+ updateConfig((cfg) => {
61
+ if (Object.hasOwn(cfg, 'trimKeep')) return cfg;
62
+ seeded = true;
63
+ return { ...cfg, trimKeep: [...DEFAULT_KEEP] };
64
+ });
65
+ return { keep: seeded ? [...DEFAULT_KEEP] : getKeep(), seeded };
66
66
  }
67
67
 
68
68
  /** True when `--apply` must stop because nothing is protected and the user did not pass `--yes`. */
69
69
  export const applyBlocked = (/** @type {string[]} */ keep, /** @type {boolean} */ yes) => !yes && keep.length === 0;
70
70
 
71
- /** @param {string[]} names */
72
- export function setKeep(names) {
73
- let cfg = {};
74
- try {
75
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
76
- } catch {
77
- /* new */
78
- }
79
- mkdirSync(stateDir(), { recursive: true });
80
- writeFileSync(configFile(), JSON.stringify({ ...cfg, trimKeep: [...new Set(names)] }));
71
+ /**
72
+ * Change the keep-list under the settings lock, so two `trim keep` runs cannot undo each other.
73
+ * @param {(keep: string[]) => string[]} change
74
+ */
75
+ export function editKeep(change) {
76
+ updateConfig((cfg) => ({ ...cfg, trimKeep: [...new Set(change(keepFrom(cfg)))] }));
81
77
  }
82
78
 
79
+ /** @param {string[]} names */
80
+ export const setKeep = (names) => editKeep(() => names);
81
+
83
82
  /** Same server or skill under another spelling ("ego-browser" / "ego_browser") counts. @param {string[]} keep @param {string} name */
84
83
  export const isKept = (keep, name) => keep.some((k) => norm(k) === norm(name));
85
84
 
package/src/flags.mjs ADDED
@@ -0,0 +1,38 @@
1
+ // @ts-check
2
+
3
+ /** Every option the CLI reads. test/flags.test.mjs keeps this list in step with bin/limitcast.mjs. */
4
+ export const KNOWN_FLAGS = [
5
+ '--alerts',
6
+ '--apply',
7
+ '--codex',
8
+ '--days',
9
+ '--detach',
10
+ '--fix',
11
+ '--grok',
12
+ '--guard',
13
+ '--help',
14
+ '--hook',
15
+ '--html',
16
+ '--jobs',
17
+ '--json',
18
+ '--no-open',
19
+ '--out',
20
+ '--refresh',
21
+ '--remove',
22
+ '--share',
23
+ '--src',
24
+ '--undo',
25
+ '--why',
26
+ '--window',
27
+ '--yes',
28
+ ];
29
+
30
+ /**
31
+ * The first mistyped --option before any `--` separator, or undefined. Without this a typo such as
32
+ * `install --gaurd` runs the plain command and looks like it worked.
33
+ * @param {string[]} args
34
+ */
35
+ export function unknownFlag(args) {
36
+ const sep = args.indexOf('--');
37
+ return (sep < 0 ? args : args.slice(0, sep)).find((a) => a.startsWith('--') && !KNOWN_FLAGS.includes(a));
38
+ }
package/src/grok.mjs CHANGED
@@ -4,7 +4,7 @@ import { homedir } from 'node:os';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { codexServers, setEnabled } from './codex.mjs';
6
6
  import { windowMs } from './forecast.mjs';
7
- import { KEEP_MS, stateDir } from './store.mjs';
7
+ import { KEEP_MS, stateDir, updateConfig } from './store.mjs';
8
8
  import { grokRoot } from './usage.mjs';
9
9
 
10
10
  /** @typedef {import('./forecast.mjs').Sample} Sample */
@@ -182,18 +182,13 @@ export function getGrokBudget() {
182
182
  * @param {'5h'|'7d'} [win]
183
183
  */
184
184
  export function setGrokBudget(usd, win = '5h') {
185
- let cfg = {};
186
- try {
187
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
188
- } catch {
189
- /* new */
190
- }
191
- /** @type {{'5h'?:number, '7d'?:number}} */
192
- const cur = typeof cfg.grokBudget === 'number' ? { '5h': cfg.grokBudget } : { ...(cfg.grokBudget ?? {}) };
193
- if (usd === null) delete cur[win];
194
- else cur[win] = usd;
195
- mkdirSync(stateDir(), { recursive: true });
196
- writeFileSync(configFile(), JSON.stringify({ ...cfg, grokBudget: Object.keys(cur).length ? cur : null }));
185
+ updateConfig((cfg) => {
186
+ /** @type {{'5h'?:number, '7d'?:number}} */
187
+ const cur = typeof cfg.grokBudget === 'number' ? { '5h': cfg.grokBudget } : { ...(cfg.grokBudget ?? {}) };
188
+ if (usd === null) delete cur[win];
189
+ else cur[win] = usd;
190
+ return { ...cfg, grokBudget: Object.keys(cur).length ? cur : null };
191
+ });
197
192
  }
198
193
 
199
194
  /**
@@ -234,14 +229,7 @@ export function grokQuotaEnabled() {
234
229
 
235
230
  /** @param {boolean} on */
236
231
  export function setGrokQuota(on) {
237
- let cfg = {};
238
- try {
239
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
240
- } catch {
241
- /* new */
242
- }
243
- mkdirSync(stateDir(), { recursive: true });
244
- writeFileSync(configFile(), JSON.stringify({ ...cfg, grokQuota: on }));
232
+ updateConfig((cfg) => ({ ...cfg, grokQuota: on }));
245
233
  }
246
234
 
247
235
  /** @returns {QuotaState} */
package/src/guard.mjs CHANGED
@@ -130,7 +130,7 @@ export async function runGuard(hook, now, minutes, { preview = false } = {}) {
130
130
  }
131
131
  if (!preview) return todayMessage(day);
132
132
  }
133
- // Pro: hold new Claude subagents once those of this account have used their budget of the current 5-hour window.
133
+ // Hold new Claude subagents once those of this account have used their budget of the current 5-hour window.
134
134
  const budget = src === 'claude' ? getBudget() : null;
135
135
  if (budget) {
136
136
  const start = windowStart(forecasts, now);
package/src/hints.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import { closeSync, openSync, readSync, statSync } from 'node:fs';
3
3
  import { claudeAccounts, forecastAll } from './forecast.mjs';
4
4
 
5
- // Pro hints for the status line: another account with room, and when a long session is worth compacting.
5
+ // Hints for the status line: another account with room, and when a long session is worth compacting.
6
6
 
7
7
  /** @typedef {import('./forecast.mjs').Sample} Sample */
8
8
 
package/src/notify.mjs CHANGED
@@ -4,7 +4,7 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileS
4
4
  import { join } from 'node:path';
5
5
  import { stateDir } from './store.mjs';
6
6
 
7
- // Desktop notifications (Pro, opt-in): one per change of state, raised from the status line.
7
+ // Desktop notifications (opt-in): one per change of state, raised from the status line.
8
8
  // Optionally also sent to a phone (ntfy) or a Slack/Discord webhook.
9
9
 
10
10
  const flag = () => join(stateDir(), 'notify.on');
@@ -94,7 +94,7 @@ export function notifyChanges(rows, clock) {
94
94
  * @param {string} message
95
95
  */
96
96
  export function send(message) {
97
- // Pro: the same message to the phone (ntfy) or a chat webhook, by a detached curl so no hook waits on the network.
97
+ // The same message to the phone (ntfy) or a chat webhook, by a detached curl so no hook waits on the network.
98
98
  try {
99
99
  for (const a of remoteArgs(loadChannels(), message)) run('curl', a);
100
100
  } catch {
package/src/plan.mjs CHANGED
@@ -3,9 +3,9 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { claudeAccounts } from './forecast.mjs';
5
5
  import { fmtUsd } from './prices.mjs';
6
- import { stateDir } from './store.mjs';
6
+ import { stateDir, updateConfig } from './store.mjs';
7
7
 
8
- // `limitcast plan` (Pro): does your Claude plan fit how much you use? From a long-lived record of the peak of every
8
+ // `limitcast plan`: does your Claude plan fit how much you use? From a long-lived record of the peak of every
9
9
  // 5-hour and weekly window (the samples themselves are only kept for 8 days), it says whether you hit your limits often
10
10
  // enough to justify the next plan, or use so little that a smaller one would do, with the monthly price difference.
11
11
 
@@ -42,14 +42,7 @@ export function getPlan() {
42
42
 
43
43
  /** @param {PlanId|null} plan */
44
44
  export function setPlan(plan) {
45
- let cfg = {};
46
- try {
47
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
48
- } catch {
49
- /* new */
50
- }
51
- mkdirSync(stateDir(), { recursive: true });
52
- writeFileSync(configFile(), JSON.stringify({ ...cfg, plan }));
45
+ updateConfig((cfg) => ({ ...cfg, plan }));
53
46
  }
54
47
 
55
48
  /**
package/src/results.mjs CHANGED
@@ -234,7 +234,7 @@ const fmtK = (/** @type {number} */ n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M`
234
234
 
235
235
  /**
236
236
  * @param {{now:number, days:number, samples:Sample[], blocks:Block[], pro:boolean, saved:string|null, value?:string, subagents?:import('./subagents.mjs').SubagentEntry[]}} r
237
- * blocks: every logged block (Pro blocks and free previews); saved: the starting-context text, if any;
237
+ * blocks: every logged block (blocks and free previews); saved: the starting-context text, if any;
238
238
  * value: the "since you installed" section, shown first; subagents: the finished-subagent ledger
239
239
  */
240
240
  export function resultsReport({ now, days, samples, blocks, pro, saved, value = '', subagents = [] }) {
package/src/store.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // @ts-check
2
- import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
 
@@ -12,6 +12,58 @@ export function stateDir() {
12
12
  return process.env.LIMITCAST_STATE ?? join(process.env.XDG_STATE_HOME ?? join(homedir(), '.local', 'state'), 'limitcast');
13
13
  }
14
14
 
15
+ /** Write through a temp file and rename, so a hook reading at the same moment never sees a half-written file. */
16
+ export function writeAtomic(/** @type {string} */ path, /** @type {string} */ text) {
17
+ const tmp = `${path}.${process.pid}.tmp`;
18
+ writeFileSync(tmp, text);
19
+ renameSync(tmp, path);
20
+ }
21
+
22
+ const LOCK_STALE_MS = 2_000; // the lock is held for one read and one write; older than this means its owner died
23
+ const LOCK_WAIT_MS = 5_000;
24
+
25
+ /**
26
+ * Change config.json under a lock: read it, let `change` return the new settings (or the same object to leave the file
27
+ * alone), write it. Without the lock, two commands that each read the file and then each write it lose one change.
28
+ * shortcut: two waiters that break the same stale lock in the same instant can both write; fix with a lockfile library if seen.
29
+ * @param {(cfg: any) => any} change
30
+ */
31
+ export function updateConfig(change) {
32
+ const dir = stateDir();
33
+ mkdirSync(dir, { recursive: true });
34
+ const file = join(dir, 'config.json');
35
+ const lock = `${file}.lock`;
36
+ const start = Date.now();
37
+ for (;;) {
38
+ try {
39
+ mkdirSync(lock); // atomic: exactly one process creates it
40
+ break;
41
+ } catch (e) {
42
+ if (/** @type {NodeJS.ErrnoException} */ (e).code !== 'EEXIST') throw e;
43
+ try {
44
+ if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) rmSync(lock, { recursive: true, force: true });
45
+ } catch {
46
+ /* released while we looked */
47
+ }
48
+ if (Date.now() - start > LOCK_WAIT_MS) throw new Error(`could not lock ${file}: another limitcast command is changing settings`);
49
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
50
+ }
51
+ }
52
+ try {
53
+ let cfg = {};
54
+ try {
55
+ cfg = JSON.parse(readFileSync(file, 'utf8'));
56
+ } catch {
57
+ /* new or corrupt: start fresh */
58
+ }
59
+ if (!cfg || typeof cfg !== 'object') cfg = {};
60
+ const next = change(cfg);
61
+ if (next !== cfg) writeAtomic(file, JSON.stringify(next));
62
+ } finally {
63
+ rmSync(lock, { recursive: true, force: true });
64
+ }
65
+ }
66
+
15
67
  /**
16
68
  * Append samples whose pct or reset changed since the last one for the same series.
17
69
  * The status line fires on every message, so unchanged readings are skipped.
@@ -38,9 +90,9 @@ export function record(samples) {
38
90
  const file = join(dir, 'samples.jsonl');
39
91
  appendFileSync(file, `${fresh.map((s) => JSON.stringify(s)).join('\n')}\n`);
40
92
  for (const s of fresh) last[key(s)] = { pct: s.pct, reset: s.reset };
41
- writeFileSync(lastPath, JSON.stringify(last));
93
+ writeAtomic(lastPath, JSON.stringify(last));
42
94
  if (statSync(file).size > PRUNE_BYTES)
43
- writeFileSync(
95
+ writeAtomic(
44
96
  file,
45
97
  load(Date.now() - KEEP_MS)
46
98
  .map((s) => `${JSON.stringify(s)}\n`)
package/src/subagents.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  // @ts-check
2
- import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
- import { stateDir } from './store.mjs';
5
+ import { stateDir, updateConfig } from './store.mjs';
6
6
 
7
- // Subagent receipts and budgets (Pro). A SubagentStop hook prices each finished subagent against the 5-hour window
7
+ // Subagent receipts and budgets. A SubagentStop hook prices each finished subagent against the 5-hour window
8
8
  // (from the user's own calibration) and logs it; the guard holds new subagents once a window's budget is spent.
9
9
 
10
10
  /** @typedef {{t:number, id?:string, sid?:string, type?:string, calls:number, fresh:number, read:number, pct?:number}} SubagentEntry */
@@ -121,14 +121,7 @@ export function getBudget() {
121
121
 
122
122
  /** @param {number|null} pct */
123
123
  export function setBudget(pct) {
124
- let cfg = {};
125
- try {
126
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
127
- } catch {
128
- /* new */
129
- }
130
- mkdirSync(stateDir(), { recursive: true });
131
- writeFileSync(configFile(), JSON.stringify({ ...cfg, subagentBudget: pct }));
124
+ updateConfig((cfg) => ({ ...cfg, subagentBudget: pct }));
132
125
  }
133
126
 
134
127
  /** Whether the guard holds new subagents once today's share of a weekly window is used up (`limitcast budget today on`). */
@@ -142,14 +135,7 @@ export function getTodayHold() {
142
135
 
143
136
  /** @param {boolean} on */
144
137
  export function setTodayHold(on) {
145
- let cfg = {};
146
- try {
147
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
148
- } catch {
149
- /* new */
150
- }
151
- mkdirSync(stateDir(), { recursive: true });
152
- writeFileSync(configFile(), JSON.stringify({ ...cfg, todayHold: on }));
138
+ updateConfig((cfg) => ({ ...cfg, todayHold: on }));
153
139
  }
154
140
 
155
141
  /** A model a subagent type can be pinned to: sonnet, opus, haiku, a claude-... id, or a grok-... id. */
@@ -183,17 +169,12 @@ export function getSubagentModels() {
183
169
  * @param {string|null} model
184
170
  */
185
171
  export function setSubagentModel(type, model) {
186
- let cfg = /** @type {any} */ ({});
187
- try {
188
- cfg = JSON.parse(readFileSync(configFile(), 'utf8'));
189
- } catch {
190
- /* new */
191
- }
192
- const models = { ...cfg.subagentModels };
193
- if (model === null) delete models[type];
194
- else models[type] = model;
195
- mkdirSync(stateDir(), { recursive: true });
196
- writeFileSync(configFile(), JSON.stringify({ ...cfg, subagentModels: models }));
172
+ updateConfig((cfg) => {
173
+ const models = { ...cfg.subagentModels };
174
+ if (model === null) delete models[type];
175
+ else models[type] = model;
176
+ return { ...cfg, subagentModels: models };
177
+ });
197
178
  }
198
179
 
199
180
  /**
package/src/toolcheck.mjs CHANGED
@@ -3,7 +3,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { stateDir } from './store.mjs';
5
5
 
6
- // Large tool-output notice (Pro, PostToolUse hook, installed with --alerts). A tool result enters the context once as
6
+ // Large tool-output notice (PostToolUse hook, installed with --alerts). A tool result enters the context once as
7
7
  // new tokens and is then re-read on every later call, so a very large one is worth knowing about. The notice goes to
8
8
  // the user (systemMessage), never the model, once per tool per session, with what to ask for next time.
9
9
 
package/src/usage.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  // @ts-check
2
- import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
+ import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, statSync } 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
+ import { stateDir, writeAtomic } from './store.mjs';
7
7
 
8
8
  /**
9
9
  * One model response's token usage.
@@ -171,6 +171,7 @@ export async function readUsage(since, roots = {}, activity) {
171
171
  const out = [];
172
172
  // Parsed transcripts are cached by size and mtime: only new or changed ones are read again.
173
173
  const cache = loadUsageCache();
174
+ let dirty = false; // a parsed file or a dropped entry: only then is the cache file rewritten
174
175
  /** @type {typeof cache} */
175
176
  const next = {};
176
177
  /**
@@ -180,7 +181,9 @@ export async function readUsage(since, roots = {}, activity) {
180
181
  const cached = async (file, parse) => {
181
182
  const st = statSync(file);
182
183
  const hit = cache[file];
183
- const entry = hit && hit.s === st.size && hit.m === st.mtimeMs ? hit : { s: st.size, m: st.mtimeMs, ...(await parse(file)) };
184
+ const fresh = !(hit && hit.s === st.size && hit.m === st.mtimeMs);
185
+ if (fresh) dirty = true;
186
+ const entry = fresh ? { s: st.size, m: st.mtimeMs, ...(await parse(file)) } : hit;
184
187
  next[file] = entry;
185
188
  return entry;
186
189
  };
@@ -220,7 +223,7 @@ export async function readUsage(since, roots = {}, activity) {
220
223
  }
221
224
  // Keep entries for files this run didn't need (another period) while they are recent; drop the rest.
222
225
  for (const [f, e] of Object.entries(cache)) if (!next[f] && e.m >= Date.now() - CACHE_KEEP_MS && existsSync(f)) next[f] = e;
223
- saveUsageCache(next);
226
+ if (dirty || Object.keys(next).length !== Object.keys(cache).length) saveUsageCache(next);
224
227
  for (const { file, session, project } of grokLedgers(roots.grok ?? grokRoot(), since)) {
225
228
  let ledger;
226
229
  try {
@@ -251,7 +254,7 @@ function loadUsageCache() {
251
254
  function saveUsageCache(c) {
252
255
  try {
253
256
  mkdirSync(stateDir(), { recursive: true });
254
- writeFileSync(usageCacheFile(), JSON.stringify({ v: USAGE_CACHE_VERSION, files: c }));
257
+ writeAtomic(usageCacheFile(), JSON.stringify({ v: USAGE_CACHE_VERSION, files: c }));
255
258
  } catch {
256
259
  /* a cache: the next run just reads the transcripts */
257
260
  }
package/src/where.mjs CHANGED
@@ -1,15 +1,15 @@
1
1
  // @ts-check
2
- import { createReadStream, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
+ import { createReadStream, existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { join } from 'node:path';
5
5
  import { createInterface } from 'node:readline';
6
6
  import { fmt } from './report.mjs';
7
7
  import { attachmentPieces, pieceDiff } from './startup.mjs';
8
- import { stateDir } from './store.mjs';
8
+ import { stateDir, writeAtomic } from './store.mjs';
9
9
  import { BIG_RESULT, tipFor, toolKey } from './toolcheck.mjs';
10
10
  import { jsonlFiles } from './usage.mjs';
11
11
 
12
- // `limitcast report --why` (Pro): where the new tokens went, which is what moves the limit (cached reads barely count).
12
+ // `limitcast report --why`: where the new tokens went, which is what moves the limit (cached reads barely count).
13
13
  // A model call's new tokens are input + cache writes + output. The input of call i is what entered the context since
14
14
  // call i-1: its own output (written to the cache) plus the tool results it asked for plus your messages. So the input
15
15
  // of call i, less call i-1's output, is attributed to the tools call i-1 used. Claude Code transcripts only.
@@ -480,16 +480,22 @@ export async function whySessions(root, since) {
480
480
  /** @type {typeof cache} */
481
481
  const next = {};
482
482
  const files = jsonlFiles(root, since, () => true);
483
- for (const f of files) {
484
- const st = statSync(f);
485
- const hit = cache[f];
486
- next[f] = hit && hit.s === st.size && hit.m === st.mtimeMs ? hit : { s: st.size, m: st.mtimeMs, c: await readCalls(f) };
483
+ const stats = files.map((f) => statSync(f));
484
+ const fresh = (/** @type {number} */ i) => !(cache[files[i]] && cache[files[i]].s === stats[i].size && cache[files[i]].m === stats[i].mtimeMs);
485
+ const cold = files.filter((_, i) => fresh(i)).length;
486
+ // The first run reads every transcript (up to a minute on a big machine); say so instead of sitting silent.
487
+ if (cold > 100) console.error(`limitcast: reading ${cold} transcripts for the first time. This can take a minute; later runs use a cache.`);
488
+ for (const [i, f] of files.entries()) {
489
+ next[f] = fresh(i) ? { s: stats[i].size, m: stats[i].mtimeMs, c: await readCalls(f) } : cache[f];
487
490
  }
488
491
  // Keep entries this run didn't need (another period) while they are recent; drop the rest.
489
492
  for (const [f, e] of Object.entries(cache)) if (!next[f] && e.m >= Date.now() - CACHE_KEEP_MS && existsSync(f)) next[f] = e;
490
493
  try {
491
- mkdirSync(stateDir(), { recursive: true });
492
- writeFileSync(cacheFile(), JSON.stringify({ v: CACHE_VERSION, files: next }));
494
+ // Rewrite the file only when something was read or dropped; it is several MB on a busy machine.
495
+ if (cold || Object.keys(next).length !== Object.keys(cache).length) {
496
+ mkdirSync(stateDir(), { recursive: true });
497
+ writeAtomic(cacheFile(), JSON.stringify({ v: CACHE_VERSION, files: next }));
498
+ }
493
499
  } catch {
494
500
  /* a cache: the next run just reads the transcripts */
495
501
  }