limitcast 0.19.3 → 0.20.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/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
  <a href="https://www.npmjs.com/package/limitcast"><code>npm · limitcast</code></a>
7
7
  <a href="https://github.com/SamStull9007/limitcast/actions/workflows/ci.yml"><img src="https://github.com/SamStull9007/limitcast/actions/workflows/ci.yml/badge.svg" alt="CI status"></a>
8
8
  <a href="LICENSE"><code>MIT license</code></a>
9
- <a href="https://nodejs.org"><code>Node.js 20+</code></a>
9
+ <a href="https://nodejs.org"><code>Node.js 22+</code></a>
10
10
  </p>
11
11
 
12
12
  <p align="center">
@@ -42,7 +42,7 @@
42
42
 
43
43
  <a id="free-and-open-source"></a>
44
44
 
45
- **Free and open source.** All features are included. No Limitcast account, license key, or subscription required. Runs locally on **macOS and Linux** with **Node.js 20+**.
45
+ **Free and open source.** All features are included. No Limitcast account, license key, or subscription required. Runs locally on **macOS and Linux** with **Node.js 22+**.
46
46
 
47
47
  <a id="install"></a>
48
48
 
@@ -140,10 +140,11 @@ Your findings depend on your local sessions. `trim` inspects first. Use `trim ke
140
140
 
141
141
  Limitcast reads usage readings and session logs already on your machine. Reports remain local, sharing totals is voluntary, and no billing-service connection is required.
142
142
 
143
- Two optional features make network requests, both **off by default**:
143
+ Three optional features make network requests, all **off by default**:
144
144
 
145
145
  - **Phone or webhook notifications** send notification text to the service you choose.
146
146
  - **Grok weekly usage** reads Grok's existing login and sends it only to grok.com to retrieve your usage. Redirects are refused; the login is never stored or logged by Limitcast.
147
+ - **Optimizer model learning/judging** uses your authenticated Codex CLI and its configured model service. It sends allowlisted check commands, counts and hashed identities; it excludes raw prompts, source text, transcripts and tool output. Calls consume your Codex allowance. [Scope and controls →](docs/optimizer.md#optional-model-learning-and-judging)
147
148
 
148
149
  Context reductions are estimates against a recorded baseline, not measured causal savings or a lower subscription bill. Forecasts depend on observed usage. [How forecasting and measurement work →](docs/usage.md#how-the-forecast-works)
149
150
 
package/bin/limitcast.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // @ts-check
3
3
  import { spawn, spawnSync } from 'node:child_process';
4
- import { existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { existsSync, mkdirSync, openSync, readFileSync, readSync, writeFileSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import {
@@ -24,6 +24,7 @@ import {
24
24
  } from '../src/apply.mjs';
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
+ import { codexHooks, trustLine } from '../src/codex-trust.mjs';
27
28
  import { coldCost, coldMessage, coldNotice, firstNotice, firstWarning } from '../src/cold.mjs';
28
29
  import { unknownFlag } from '../src/flags.mjs';
29
30
  import { forecastAll, oneClaudeAccount, resetTarget } from '../src/forecast.mjs';
@@ -65,14 +66,25 @@ import {
65
66
  spawnIdentity,
66
67
  } from '../src/inflight.mjs';
67
68
  import { insightsReport, insightsShare, periodInsights } from '../src/insights.mjs';
68
- import { doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
69
+ import { codexHooksPath, doctor, install, installedFeatures, readSettings, settingsPath, uninstall } from '../src/install.mjs';
69
70
  import { memoryCheck, memoryDir, memoryReport, scanMemory } from '../src/memory.mjs';
70
- import { buildNotifierApp, loadChannels, notifierApp, notifyChanges, notifyEnabled, send, setChannel, setNotify } from '../src/notify.mjs';
71
+ import {
72
+ buildNotifierApp,
73
+ codexNotifyDue,
74
+ loadChannels,
75
+ notifierApp,
76
+ notifyChanges,
77
+ notifyEnabled,
78
+ send,
79
+ setChannel,
80
+ setNotify,
81
+ } from '../src/notify.mjs';
71
82
  import { onboardingReport } from '../src/onboarding.mjs';
72
83
  import { runOptimizationHook, runOptimize } from '../src/optimize-cli.mjs';
73
- import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
84
+ import { driftMessage, hostSnapshot, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
74
85
  import { advise, getPlan, loadPeaks, PLANS, planPrices, planStats, recordPeaks, setPlan } from '../src/plan.mjs';
75
86
  import { costOf, fmtUsd } from '../src/prices.mjs';
87
+ import { deferReceipt, hostSubagentUsage, settleReceipts, stopHost } from '../src/receipts.mjs';
76
88
  import { burnReport } from '../src/report.mjs';
77
89
  import { loadBlocks, logBlock, resultsReport, resultsShare, resultsStats, weeklyDue, weeklyLine } from '../src/results.mjs';
78
90
  import { claudeSamples, readCodex } from '../src/sources.mjs';
@@ -94,8 +106,8 @@ import {
94
106
  windowStart,
95
107
  } from '../src/subagents.mjs';
96
108
  import { forTerminal } from '../src/term.mjs';
97
- import { firstFlag, toolKey, toolNotice } from '../src/toolcheck.mjs';
98
- import { loadToolStats, saveToolStats, toolLimitDecision, toolStats } from '../src/toollimit.mjs';
109
+ import { firstFlag, resultTokens, toolKey, toolNotice } from '../src/toolcheck.mjs';
110
+ import { loadLiveStats, loadToolStats, recordToolSize, saveToolStats, toolLimitDecision, toolStats } from '../src/toollimit.mjs';
99
111
  import { baseline, contributors, measuredSavings, shareSummary, startupReport, trimReport } from '../src/trim.mjs';
100
112
  import { claudeRoot, grokRoot, readUsage } from '../src/usage.mjs';
101
113
  import { dailyDue, foldEvents, loadValue, saveValue, scanSessions, valuePeriod, valueSection, valueTotals } from '../src/value.mjs';
@@ -179,7 +191,7 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
179
191
  const [cmd, ...args] = process.argv.slice(2);
180
192
  const now = Date.now();
181
193
  // Hooks run unattended and fail open; everything else rejects a mistyped option instead of ignoring it.
182
- const typo = ['guard', 'prompt-check', 'tool-check', 'tool-limit', 'subagent-receipt', 'drift', 'statusline'].includes(cmd)
194
+ const typo = ['guard', 'prompt-check', 'tool-check', 'tool-limit', 'subagent-receipt', 'codex-notify', 'drift', 'statusline'].includes(cmd)
183
195
  ? undefined
184
196
  : unknownFlag(args);
185
197
  if (typo) {
@@ -190,6 +202,19 @@ const flag = (/** @type {string} */ name) => {
190
202
  const i = args.indexOf(name);
191
203
  return i >= 0 ? args[i + 1] : undefined;
192
204
  };
205
+ /** The tool a hook belongs to: `--src codex|grok` on hooks install writes for them, Claude Code otherwise. @returns {'claude'|'codex'|'grok'} */
206
+ const hookHost = () => {
207
+ const s = flag('--src');
208
+ return s === 'codex' || s === 'grok' ? s : 'claude';
209
+ };
210
+ /** Grok writes a finished subagent's usage after its stop hook ran: log the receipts parked at the stop. Never throws. */
211
+ const settleGrokReceipts = () => {
212
+ try {
213
+ settleReceipts(now);
214
+ } catch {
215
+ /* a hook must never break the session */
216
+ }
217
+ };
193
218
  const days = () => {
194
219
  const n = Number(flag('--days') ?? 7);
195
220
  if (!Number.isFinite(n) || n <= 0 || !Number.isFinite(new Date(now - n * 86400_000).getTime())) {
@@ -309,6 +334,7 @@ if (cmd === '_optimize-hook') {
309
334
  if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
310
335
  try {
311
336
  const hook = JSON.parse(readStdin());
337
+ settleGrokReceipts();
312
338
  const id = spawnIdentity(hook);
313
339
  const live = pruneInflight(loadInflight(), now);
314
340
  const dup = id ? findDuplicate(live, id) : null;
@@ -409,19 +435,24 @@ if (cmd === '_optimize-hook') {
409
435
  if (process.env.LIMITCAST_ALLOW === '1') process.exit(0);
410
436
  try {
411
437
  const hook = JSON.parse(readStdin());
438
+ // `--src codex|grok` (set by install) reads that tool's payload and its live-learned sizes; Claude's come from `report --why`.
439
+ const host = hookHost();
440
+ if (host === 'grok') settleGrokReceipts();
412
441
  const name = String(hook?.tool_name ?? hook?.toolName ?? '');
413
- const d = name ? toolLimitDecision(name, hook?.tool_input ?? hook?.toolInput, loadToolStats()) : null;
442
+ const stats = host === 'claude' ? loadToolStats() : loadLiveStats(host);
443
+ const d = name ? toolLimitDecision(name, hook?.tool_input ?? hook?.toolInput, stats, { host, rewrite: host !== 'codex' }) : null;
444
+ const opId = hook?.tool_use_id ?? hook?.toolUseId;
414
445
  if (d && 'deny' in d) {
415
446
  logBlock({
416
447
  t: now,
417
448
  kind: 'tool-limit',
418
- src: 'claude',
419
- win: '5h',
449
+ src: host,
450
+ win: host === 'codex' ? '7d' : '5h',
420
451
  pct: 0,
421
452
  wall: now,
422
453
  reset: now,
423
- sid: hook.session_id,
424
- ...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
454
+ sid: hook.session_id ?? hook.sessionId,
455
+ ...(typeof opId === 'string' ? { operation: opId } : {}),
425
456
  });
426
457
  console.log(
427
458
  JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: d.deny } }),
@@ -430,13 +461,13 @@ if (cmd === '_optimize-hook') {
430
461
  logBlock({
431
462
  t: now,
432
463
  kind: 'tool-cap',
433
- src: 'claude',
434
- win: '5h',
464
+ src: host,
465
+ win: host === 'codex' ? '7d' : '5h',
435
466
  pct: 0,
436
467
  wall: now,
437
468
  reset: now,
438
- sid: hook.session_id,
439
- ...(typeof hook?.tool_use_id === 'string' ? { operation: hook.tool_use_id } : {}),
469
+ sid: hook.session_id ?? hook.sessionId,
470
+ ...(typeof opId === 'string' ? { operation: opId } : {}),
440
471
  });
441
472
  console.log(
442
473
  JSON.stringify({
@@ -458,9 +489,16 @@ if (cmd === '_optimize-hook') {
458
489
  try {
459
490
  {
460
491
  const hook = JSON.parse(readStdin());
461
- const name = String(hook?.tool_name ?? '');
462
- const notice = name ? toolNotice(name, hook?.tool_response, loadValue().calib, Number(process.env.LIMITCAST_TOOL_TOKENS) || undefined) : null;
463
- if (notice && firstFlag(String(hook.session_id), toolKey(name))) console.log(JSON.stringify({ systemMessage: notice }));
492
+ const host = hookHost();
493
+ if (host === 'grok') settleGrokReceipts();
494
+ const name = String(hook?.tool_name ?? hook?.toolName ?? '');
495
+ const response = hook?.tool_response ?? hook?.tool_result ?? hook?.toolResult;
496
+ // Codex and Grok have no 5-hour calibration, and no transcript report to learn tool sizes from: learn them here.
497
+ if (name && host !== 'claude') recordToolSize(host, toolKey(name, host), resultTokens(response));
498
+ const notice = name
499
+ ? toolNotice(name, response, host === 'claude' ? loadValue().calib : null, Number(process.env.LIMITCAST_TOOL_TOKENS) || undefined, host)
500
+ : null;
501
+ if (notice && firstFlag(String(hook.session_id ?? hook.sessionId), toolKey(name, host))) console.log(JSON.stringify({ systemMessage: notice }));
464
502
  }
465
503
  } catch {
466
504
  /* a hook must never break the session */
@@ -470,8 +508,8 @@ if (cmd === '_optimize-hook') {
470
508
  // Pro shows the receipt to the user (systemMessage, never the model). Internal agents (empty type) are skipped.
471
509
  try {
472
510
  const hook = JSON.parse(readStdin());
473
- // Claude Code and Codex send snake_case; Grok sends `sessionId` and `subagentType`. Every host clears the duplicate hold;
474
- // only Claude transcripts are priced below (a Codex or Grok transcript yields no calls, so nothing is logged for them).
511
+ // Claude Code and Codex send snake_case; Grok sends `sessionId` and `subagentType`. Every host clears the duplicate hold
512
+ // and gets a receipt: Claude's from its transcript, Codex's from the child rollout, Grok's from the child session ledger.
475
513
  saveInflight(
476
514
  forgetInflight(
477
515
  loadInflight(),
@@ -481,7 +519,29 @@ if (cmd === '_optimize-hook') {
481
519
  ),
482
520
  );
483
521
  const path = hook?.agent_transcript_path;
484
- if (hook?.agent_type && typeof path === 'string') {
522
+ const host = stopHost(hook);
523
+ if (host !== 'claude') {
524
+ const type = String(hook?.agent_type ?? hook?.subagentType ?? hook?.agentType ?? '');
525
+ if (host === 'grok') settleGrokReceipts();
526
+ const got = type ? hostSubagentUsage(hook) : null;
527
+ // Grok has not written this subagent's usage yet (it does a moment after the stop): park it for the next hook.
528
+ if (!got?.usage.calls && host === 'grok' && type) deferReceipt(now, type, hook);
529
+ if (got?.usage.calls) {
530
+ const { usage } = got;
531
+ logSubagent({
532
+ t: now,
533
+ src: got.src,
534
+ id: hook.agent_id ?? hook.subagentId,
535
+ sid: hook.session_id ?? hook.sessionId,
536
+ type,
537
+ calls: usage.calls,
538
+ fresh: usage.fresh,
539
+ read: usage.read,
540
+ ...(usage.usd === null ? {} : { usd: usage.usd }),
541
+ });
542
+ console.log(JSON.stringify({ systemMessage: receiptMessage(type, usage, null, usage.usd) }));
543
+ }
544
+ } else if (hook?.agent_type && typeof path === 'string') {
485
545
  const u = subagentUsage(path);
486
546
  const calib = loadValue().calib;
487
547
  const pct = calib ? windowPct(calib, { writes: u.fresh, reads: u.read }) : null;
@@ -502,6 +562,23 @@ if (cmd === '_optimize-hook') {
502
562
  } catch {
503
563
  /* a hook must never break the session */
504
564
  }
565
+ } else if (cmd === 'codex-notify') {
566
+ // Codex has no status line to raise a notification from. A Stop hook (installed with --guard) calls this with --hook; at most
567
+ // every few minutes it starts the check below in the background, so no Codex turn waits on reading the rollouts.
568
+ try {
569
+ if (args.includes('--hook')) {
570
+ readStdin();
571
+ if (notifyEnabled() && codexNotifyDue(now))
572
+ spawn(process.execPath, [fileURLToPath(import.meta.url), 'codex-notify'], { detached: true, stdio: 'ignore' }).unref();
573
+ } else if (notifyEnabled()) {
574
+ notifyChanges(
575
+ forecastAll(oneClaudeAccount(await readCodex(now - KEEP_MS)), now).filter((f) => f.src === 'codex'),
576
+ clock,
577
+ );
578
+ }
579
+ } catch {
580
+ /* a hook must never break the session */
581
+ }
505
582
  } else if (cmd === 'plan') {
506
583
  if (args[0] === 'set') {
507
584
  const id = args[1];
@@ -700,6 +777,21 @@ if (cmd === '_optimize-hook') {
700
777
  }
701
778
  const checks = await healthChecks();
702
779
  saveHealth(checks);
780
+ // The key in Codex's config.toml only says a hook was approved once, not that this version of it was. When limitcast has hooks
781
+ // in Codex, ask Codex itself which ones it trusts (it takes a second, so it belongs here and not in the daily background check).
782
+ try {
783
+ if (readFileSync(codexHooksPath(), 'utf8').includes('limitcast')) {
784
+ const rows = await codexHooks();
785
+ const line = rows ? trustLine(rows) : null;
786
+ if (line) {
787
+ const at = checks.findIndex((c) => c.line.startsWith('Codex subagent guard installed'));
788
+ if (at >= 0) checks.splice(at, 1);
789
+ checks.push(line);
790
+ }
791
+ }
792
+ } catch {
793
+ /* no Codex hooks file, or Codex did not answer: the checks above stand */
794
+ }
703
795
  // Memory is per project: shown here, but kept out of the saved health that the daily background check overwrites.
704
796
  const mem = memoryCheck(scanMemory(memoryDir()));
705
797
  if (mem) checks.push(mem);
@@ -796,7 +888,9 @@ if (cmd === '_optimize-hook') {
796
888
  console.log(
797
889
  (changed.length
798
890
  ? `✓ 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`
799
- : 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
891
+ : r.unknown.length
892
+ ? 'Nothing to turn off: usage history is missing or incomplete, so unverified servers stay on.'
893
+ : 'Nothing to turn off: every server that is on was used or is on your keep-list.') + keptNote(r.kept),
800
894
  );
801
895
  } else
802
896
  console.log(
@@ -895,17 +989,24 @@ if (cmd === '_optimize-hook') {
895
989
  } else if (cmd === 'drift') {
896
990
  // SessionStart hook: tells the user (systemMessage, never the model's context) when starting context grew.
897
991
  const hook = args.includes('--hook');
992
+ const host = hookHost();
993
+ if (host === 'grok') settleGrokReceipts();
898
994
  try {
899
- const latest = await latestInteractiveTranscript(claudeRoot());
900
- const d = latest ? recordOverhead(snapshot(latest)) : null;
995
+ // Claude Code: the last interactive transcript. Codex and Grok (`--src`): the sizes their last interactive session logged.
996
+ const claudeLatest = host === 'claude' ? await latestInteractiveTranscript(claudeRoot()) : null;
997
+ const start = host === 'codex' ? await codexStartup() : host === 'grok' ? grokStartup() : null;
998
+ const latest = claudeLatest ?? start;
999
+ const d = claudeLatest
1000
+ ? recordOverhead(snapshot(claudeLatest))
1001
+ : start && host !== 'claude'
1002
+ ? recordOverhead(hostSnapshot(host, start), host)
1003
+ : null;
901
1004
  if (hook) {
902
- const lines = d?.alert ? [driftMessage(d)] : [];
903
- // Claude Code may have rewritten the files `trim --apply` changed: put the cuts back for the next session.
904
- const re = reapplyTrim();
905
- if (re.reapplied.length)
906
- lines.push(
907
- `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)`,
908
- );
1005
+ const lines = d?.alert ? [driftMessage(d, host)] : [];
1006
+ // A host rewrite cannot be distinguished from a user edit: preserve the current settings.
1007
+ const re = host === 'claude' ? reapplyTrim() : { reapplied: [], released: [] };
1008
+ if (re.released.length)
1009
+ lines.push(`limitcast: ${re.released.length} trim settings changed; your current choices were preserved. Run limitcast trim to review.`);
909
1010
  // Once a week, what limitcast did: shown to the user at session start, never to the model.
910
1011
  if (weeklyDue(now)) {
911
1012
  const since = now - 7 * 86400_000;
@@ -918,9 +1019,9 @@ if (cmd === '_optimize-hook') {
918
1019
  );
919
1020
  }
920
1021
  if (lines.length) console.log(JSON.stringify({ systemMessage: lines.join('\n') }));
921
- } else if (!latest) console.log('No interactive Claude Code session found yet.');
1022
+ } else if (!latest) console.log(`No interactive ${host === 'claude' ? 'Claude Code' : host === 'codex' ? 'Codex' : 'Grok'} session found yet.`);
922
1023
  else if (!d) console.log('Starting context recorded. limitcast will tell you when it grows.');
923
- else console.log(d.alert ? forTerminal(driftMessage(d)) : 'No meaningful change in your starting context since the last session.');
1024
+ else console.log(d.alert ? forTerminal(driftMessage(d, host)) : 'No meaningful change in your starting context since the last session.');
924
1025
  } catch (e) {
925
1026
  if (!hook) throw e; // a hook must never break session start
926
1027
  }
@@ -1264,12 +1365,30 @@ function saveFeedShape(feed, file = 'last-feed.json') {
1264
1365
  writeFileSync(join(stateDir(), file), JSON.stringify(shape, null, 2));
1265
1366
  }
1266
1367
 
1368
+ /**
1369
+ * The whole of stdin. A host that pipes a large payload (a tool result can be 100 KB or more) may hand us a non-blocking pipe,
1370
+ * where readFileSync(0) throws EAGAIN once the pipe runs dry and the rest of the payload is lost. Wait for the writer instead,
1371
+ * for at most ten seconds.
1372
+ */
1267
1373
  function readStdin() {
1268
- try {
1269
- return readFileSync(0, 'utf8');
1270
- } catch {
1271
- return '';
1374
+ const chunks = [];
1375
+ const buf = Buffer.alloc(65536);
1376
+ const until = Date.now() + 10_000;
1377
+ for (;;) {
1378
+ let n = 0;
1379
+ try {
1380
+ n = readSync(0, buf, 0, buf.length, null);
1381
+ } catch (e) {
1382
+ if (/** @type {NodeJS.ErrnoException} */ (e).code === 'EAGAIN' && Date.now() < until) {
1383
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
1384
+ continue;
1385
+ }
1386
+ break; // EOF on some platforms, or a closed or unreadable stdin: what arrived so far is what we have
1387
+ }
1388
+ if (n === 0) break;
1389
+ chunks.push(Buffer.from(buf.subarray(0, n)));
1272
1390
  }
1391
+ return Buffer.concat(chunks).toString('utf8');
1273
1392
  }
1274
1393
 
1275
1394
  /** @param {number|null} ms */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.19.3",
3
+ "version": "0.20.0",
4
4
  "description": "Claude Code usage limits: forecast Codex and Grok too.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,7 +11,7 @@
11
11
  "src"
12
12
  ],
13
13
  "engines": {
14
- "node": ">=20"
14
+ "node": ">=22"
15
15
  },
16
16
  "os": [
17
17
  "darwin",
package/src/apply.mjs CHANGED
@@ -1,22 +1,10 @@
1
1
  // @ts-check
2
- import {
3
- chmodSync,
4
- closeSync,
5
- copyFileSync,
6
- existsSync,
7
- mkdirSync,
8
- openSync,
9
- readdirSync,
10
- readFileSync,
11
- readSync,
12
- renameSync,
13
- statSync,
14
- writeFileSync,
15
- } from 'node:fs';
2
+ import { closeSync, copyFileSync, existsSync, openSync, readdirSync, readFileSync, readSync } from 'node:fs';
16
3
  import { homedir } from 'node:os';
17
4
  import { join } from 'node:path';
18
5
  import { readSettings, settingsPath } from './install.mjs';
19
- import { stateDir, updateConfig } from './store.mjs';
6
+ import { stateDir, updateConfig, withStateLock } from './store.mjs';
7
+ import { commitTransaction, editJson, readLedger, recoverTransaction } from './transaction.mjs';
20
8
 
21
9
  // `trim --apply`: hide unused skills and turn off unused MCP servers through Claude Code's own settings.
22
10
  // Skills: `skillOverrides` in ~/.claude/settings.json ("user-invocable-only": the model stops seeing it, /name still works).
@@ -156,26 +144,12 @@ function backup(path) {
156
144
  if (existsSync(path)) copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
157
145
  }
158
146
 
159
- /**
160
- * Write JSON through a temp file and rename, so a crash or a concurrent reader never sees half a file.
161
- * @param {string} path @param {any} value
162
- */
163
- function writeJson(path, value) {
164
- const tmp = `${path}.limitcast-tmp`;
165
- // ~/.claude.json can hold credentials: keep the file's own permissions (owner-only for a new file).
166
- const mode = existsSync(path) ? statSync(path).mode & 0o777 : 0o600;
167
- writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode });
168
- chmodSync(tmp, mode); // a leftover tmp from a crash keeps its old mode otherwise
169
- renameSync(tmp, path);
170
- }
171
-
172
147
  /** @returns {{at:number, cwd:string, skills:{name:string, prev?:string}[], mcp:string[]}[]} */
173
148
  export function loadLedger() {
174
- try {
175
- return JSON.parse(readFileSync(ledgerPath(), 'utf8'));
176
- } catch {
177
- return [];
178
- }
149
+ const entries = readLedger(ledgerPath());
150
+ if (entries.some((e) => typeof e.cwd !== 'string' || !Array.isArray(e.skills) || !Array.isArray(e.mcp)))
151
+ throw new Error('invalid Claude trim ledger');
152
+ return entries;
179
153
  }
180
154
 
181
155
  /**
@@ -184,32 +158,43 @@ export function loadLedger() {
184
158
  * @param {{cwd:string, now:number, settings?:string, claudeJson?:string}} o
185
159
  */
186
160
  export function applyTrim(plan, { cwd, now, settings = settingsPath(), claudeJson = claudeJsonPath() }) {
187
- const entry = { at: now, cwd, skills: /** @type {{name:string, prev?:string}[]} */ ([]), mcp: /** @type {string[]} */ ([]) };
188
- if (plan.hide.length) {
189
- const cfg = readSettings(settings);
190
- backup(settings);
191
- cfg.skillOverrides ??= {};
192
- for (const name of plan.hide) {
193
- entry.skills.push(name in cfg.skillOverrides ? { name, prev: cfg.skillOverrides[name] } : { name });
194
- cfg.skillOverrides[name] = 'user-invocable-only';
161
+ return withStateLock(() => {
162
+ recoverTransaction(ledgerPath());
163
+ const ledger = loadLedger();
164
+ const updates = [];
165
+ const entry = { at: now, cwd, skills: /** @type {{name:string, prev?:string}[]} */ ([]), mcp: /** @type {string[]} */ ([]) };
166
+ if (plan.hide.length) {
167
+ updates.push(
168
+ editJson(settings, (cfg) => {
169
+ cfg.skillOverrides ??= {};
170
+ for (const name of plan.hide) {
171
+ if (cfg.skillOverrides[name] !== undefined && cfg.skillOverrides[name] !== 'on') continue;
172
+ entry.skills.push(name in cfg.skillOverrides ? { name, prev: cfg.skillOverrides[name] } : { name });
173
+ cfg.skillOverrides[name] = 'user-invocable-only';
174
+ }
175
+ }),
176
+ );
195
177
  }
196
- writeJson(settings, cfg);
197
- }
198
- if (plan.disable.length) {
199
- const cj = readSettings(claudeJson);
200
- backup(claudeJson);
201
- cj.projects ??= {};
202
- cj.projects[cwd] ??= {};
203
- const list = (cj.projects[cwd].disabledMcpServers ??= []);
204
- for (const name of plan.disable) if (!list.includes(name)) list.push(name);
205
- entry.mcp = [...plan.disable];
206
- writeJson(claudeJson, cj);
207
- }
208
- if (entry.skills.length || entry.mcp.length) {
209
- mkdirSync(stateDir(), { recursive: true });
210
- writeJson(ledgerPath(), [...loadLedger(), entry]);
211
- }
212
- return entry;
178
+ if (plan.disable.length) {
179
+ updates.push(
180
+ editJson(claudeJson, (cj) => {
181
+ cj.projects ??= {};
182
+ cj.projects[cwd] ??= {};
183
+ const list = (cj.projects[cwd].disabledMcpServers ??= []);
184
+ for (const name of plan.disable)
185
+ if (!list.includes(name)) {
186
+ list.push(name);
187
+ entry.mcp.push(name);
188
+ }
189
+ }),
190
+ );
191
+ }
192
+ if (entry.skills.length || entry.mcp.length) {
193
+ for (const change of updates) backup(change.path);
194
+ commitTransaction(ledgerPath(), [...ledger, entry], updates);
195
+ }
196
+ return entry;
197
+ });
213
198
  }
214
199
 
215
200
  /**
@@ -218,74 +203,69 @@ export function applyTrim(plan, { cwd, now, settings = settingsPath(), claudeJso
218
203
  * @param {{settings?:string, claudeJson?:string}} [o]
219
204
  */
220
205
  export function undoTrim({ settings = settingsPath(), claudeJson = claudeJsonPath() } = {}) {
221
- const ledger = loadLedger();
222
- const last = ledger.pop();
223
- if (!last) return null;
224
- if (last.skills.length) {
225
- const cfg = readSettings(settings);
226
- backup(settings);
227
- for (const s of last.skills) {
228
- if (cfg.skillOverrides?.[s.name] !== 'user-invocable-only') continue;
229
- if (s.prev === undefined) delete cfg.skillOverrides[s.name];
230
- else cfg.skillOverrides[s.name] = s.prev;
206
+ return withStateLock(() => {
207
+ recoverTransaction(ledgerPath());
208
+ const ledger = loadLedger();
209
+ const last = ledger.pop();
210
+ if (!last) return null;
211
+ const updates = [];
212
+ if (last.skills.length && existsSync(settings)) {
213
+ updates.push(
214
+ editJson(settings, (cfg) => {
215
+ for (const s of last.skills) {
216
+ if (cfg.skillOverrides?.[s.name] !== 'user-invocable-only') continue;
217
+ if (s.prev === undefined) delete cfg.skillOverrides[s.name];
218
+ else cfg.skillOverrides[s.name] = s.prev;
219
+ }
220
+ }),
221
+ );
231
222
  }
232
- writeJson(settings, cfg);
233
- }
234
- if (last.mcp.length) {
235
- const cj = readSettings(claudeJson);
236
- backup(claudeJson);
237
- const p = cj.projects?.[last.cwd];
238
- if (p?.disabledMcpServers) p.disabledMcpServers = p.disabledMcpServers.filter((/** @type {string} */ n) => !last.mcp.includes(n));
239
- writeJson(claudeJson, cj);
240
- }
241
- writeJson(ledgerPath(), ledger);
242
- return last;
223
+ if (last.mcp.length && existsSync(claudeJson)) {
224
+ updates.push(
225
+ editJson(claudeJson, (cj) => {
226
+ const p = cj.projects?.[last.cwd];
227
+ if (p?.disabledMcpServers) p.disabledMcpServers = p.disabledMcpServers.filter((/** @type {string} */ n) => !last.mcp.includes(n));
228
+ }),
229
+ );
230
+ }
231
+ for (const change of updates) backup(change.path);
232
+ commitTransaction(ledgerPath(), ledger, updates);
233
+ return last;
234
+ });
243
235
  }
244
236
 
245
237
  /**
246
- * Keep the last --apply in place. A running Claude Code session can rewrite ~/.claude.json (or settings) and drop
247
- * every change at once: then put them back. When only some are gone, you turned those back on yourself (/mcp,
248
- * /skills): leave them and forget them, so limitcast never fights your choice. Checked per file.
238
+ * Release ownership of settings that changed after apply. Never infer that a user's choice was a host rewrite.
249
239
  * @param {{settings?:string, claudeJson?:string}} [o]
250
240
  * @returns {{reapplied:string[], released:string[]}}
251
241
  */
252
242
  export function reapplyTrim({ settings = settingsPath(), claudeJson = claudeJsonPath() } = {}) {
253
- const ledger = loadLedger();
254
- const last = ledger.at(-1);
255
- const out = { reapplied: /** @type {string[]} */ ([]), released: /** @type {string[]} */ ([]) };
256
- if (!last) return out;
257
- if (last.skills.length && existsSync(settings)) {
258
- const cfg = readSettings(settings);
259
- const gone = last.skills.filter((s) => cfg.skillOverrides?.[s.name] !== 'user-invocable-only');
260
- if (gone.length === last.skills.length) {
261
- cfg.skillOverrides ??= {};
262
- for (const s of gone) cfg.skillOverrides[s.name] = 'user-invocable-only';
263
- backup(settings);
264
- writeJson(settings, cfg);
265
- out.reapplied.push(...gone.map((s) => s.name));
266
- } else if (gone.length) {
267
- last.skills = last.skills.filter((s) => !gone.includes(s));
268
- out.released.push(...gone.map((s) => s.name));
243
+ return withStateLock(() => {
244
+ recoverTransaction(ledgerPath());
245
+ const ledger = loadLedger();
246
+ const last = ledger.at(-1);
247
+ const out = { reapplied: /** @type {string[]} */ ([]), released: /** @type {string[]} */ ([]) };
248
+ if (!last) return out;
249
+ if (last.skills.length) {
250
+ const cfg = existsSync(settings) ? readSettings(settings) : {};
251
+ const gone = last.skills.filter((s) => cfg.skillOverrides?.[s.name] !== 'user-invocable-only');
252
+ if (gone.length) {
253
+ last.skills = last.skills.filter((s) => !gone.includes(s));
254
+ out.released.push(...gone.map((s) => s.name));
255
+ }
269
256
  }
270
- }
271
- if (last.mcp.length && existsSync(claudeJson)) {
272
- const cj = readSettings(claudeJson);
273
- const list = cj.projects?.[last.cwd]?.disabledMcpServers ?? [];
274
- const gone = last.mcp.filter((n) => !list.includes(n));
275
- if (gone.length === last.mcp.length) {
276
- cj.projects ??= {};
277
- cj.projects[last.cwd] ??= {};
278
- cj.projects[last.cwd].disabledMcpServers = [...list, ...gone];
279
- backup(claudeJson);
280
- writeJson(claudeJson, cj);
281
- out.reapplied.push(...gone);
282
- } else if (gone.length) {
283
- last.mcp = last.mcp.filter((n) => !gone.includes(n));
284
- out.released.push(...gone);
257
+ if (last.mcp.length) {
258
+ const cj = existsSync(claudeJson) ? readSettings(claudeJson) : {};
259
+ const list = cj.projects?.[last.cwd]?.disabledMcpServers ?? [];
260
+ const gone = last.mcp.filter((n) => !list.includes(n));
261
+ if (gone.length) {
262
+ last.mcp = last.mcp.filter((n) => !gone.includes(n));
263
+ out.released.push(...gone);
264
+ }
285
265
  }
286
- }
287
- if (out.released.length) writeJson(ledgerPath(), ledger);
288
- return out;
266
+ if (out.released.length) commitTransaction(ledgerPath(), ledger, []);
267
+ return out;
268
+ });
289
269
  }
290
270
 
291
271
  /**