limitcast 0.19.4 → 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
@@ -888,7 +888,9 @@ if (cmd === '_optimize-hook') {
888
888
  console.log(
889
889
  (changed.length
890
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`
891
- : '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),
892
894
  );
893
895
  } else
894
896
  console.log(
@@ -1001,12 +1003,10 @@ if (cmd === '_optimize-hook') {
1001
1003
  : null;
1002
1004
  if (hook) {
1003
1005
  const lines = d?.alert ? [driftMessage(d, host)] : [];
1004
- // Claude Code may have rewritten the files `trim --apply` changed: put the cuts back for the next session.
1005
- const re = host === 'claude' ? reapplyTrim() : { reapplied: [] };
1006
- if (re.reapplied.length)
1007
- lines.push(
1008
- `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)`,
1009
- );
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.`);
1010
1010
  // Once a week, what limitcast did: shown to the user at session start, never to the model.
1011
1011
  if (weeklyDue(now)) {
1012
1012
  const since = now - 7 * 86400_000;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.19.4",
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
  /**
package/src/codex.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  // @ts-check
2
- import { chmodSync, copyFileSync, createReadStream, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
2
+ import { copyFileSync, createReadStream, existsSync, 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
- import { stateDir } from './store.mjs';
6
+ import { stateDir, withStateLock } from './store.mjs';
7
+ import { commitTransaction, editText, readLedger, recoverTransaction } from './transaction.mjs';
7
8
  import { jsonlFiles } from './usage.mjs';
8
9
 
9
10
  // `limitcast trim --codex`: what Codex loads before you type (AGENTS.md, MCP servers) and which servers you never use.
@@ -71,19 +72,30 @@ export function setEnabled(toml, changes) {
71
72
  */
72
73
  export async function codexUsedServers(since, root = join(codexHome(), 'sessions')) {
73
74
  const used = new Set();
75
+ used.observed = false;
76
+ used.complete = true;
74
77
  for (const f of jsonlFiles(root, since, (n) => n.startsWith('rollout-'))) {
75
78
  const rl = createInterface({ input: createReadStream(f), crlfDelay: Infinity });
76
79
  for await (const line of rl) {
77
- if (line.includes('"McpToolCall"')) {
78
- try {
79
- const item = JSON.parse(line)?.payload?.item;
80
- if (item?.type === 'McpToolCall' && typeof item.server === 'string') used.add(norm(item.server));
81
- } catch {
82
- /* a torn line */
83
- }
84
- } else if (line.includes('"namespace":"mcp__')) {
85
- const ns = /"namespace":"mcp__([^"]+)"/.exec(line)?.[1];
86
- if (ns) used.add(norm(ns));
80
+ if (!line.trim()) continue;
81
+ try {
82
+ const row = JSON.parse(line);
83
+ const p = row.payload;
84
+ const item = p?.item;
85
+ if (row.type === 'response_item' && ['function_call', 'custom_tool_call'].includes(p?.type)) {
86
+ used.observed = true;
87
+ const server = /^mcp__(.+?)(?:__|$)/.exec(p.namespace ?? '')?.[1] ?? /^mcp__(.+?)__/.exec(p.name ?? '')?.[1];
88
+ if (server) used.add(norm(server));
89
+ if (typeof p.name !== 'string') used.complete = false;
90
+ if ([p.name, p.namespace].some((n) => typeof n === 'string' && n.startsWith('mcp__')) && !server) used.complete = false;
91
+ } else if (item?.type === 'McpToolCall') {
92
+ used.observed = true;
93
+ if (typeof item.server === 'string') used.add(norm(item.server));
94
+ else used.complete = false;
95
+ } else if (item?.type === 'CommandExecution') used.observed = true;
96
+ else if (/ToolCall$/.test(item?.type ?? '')) used.complete = false;
97
+ } catch {
98
+ used.complete = false;
87
99
  }
88
100
  }
89
101
  }
@@ -156,8 +168,10 @@ export function codexTrimReport({ servers, used, usedMonth = null, startup, days
156
168
  const on = servers.filter((s) => s.enabled !== false);
157
169
  const idle = on.filter((s) => !used.has(norm(s.name)));
158
170
  const kept = idle.filter((s) => keep.some((k) => norm(k) === norm(s.name)));
171
+ const history = usedMonth ?? used;
172
+ const unknown = history.complete === false || history.observed === false ? idle.filter((s) => !kept.includes(s)) : [];
159
173
  const standing = usedMonth ? idle.filter((s) => !kept.includes(s) && usedMonth.has(norm(s.name))) : [];
160
- const unused = idle.filter((s) => !kept.includes(s) && !standing.includes(s));
174
+ const unused = idle.filter((s) => !kept.includes(s) && !standing.includes(s) && !unknown.includes(s));
161
175
  const tok = (/** @type {number} */ c) => `${(c / 4000).toFixed(1)}k`;
162
176
  const out = ['# limitcast trim --codex', ''];
163
177
  if (startup)
@@ -168,9 +182,14 @@ export function codexTrimReport({ servers, used, usedMonth = null, startup, days
168
182
  '',
169
183
  );
170
184
  out.push(`## MCP servers: ${on.length} on, ${unused.length + standing.length} not used in ${days} days`);
185
+ if (unknown.length)
186
+ out.push(
187
+ '',
188
+ `Usage history is missing or incomplete; leaving ${unknown.length} unverified servers on. No pruning is authorized by missing telemetry.`,
189
+ );
171
190
  if (standing.length)
172
191
  out.push('', `${standing.length} used in the last 30 days, so \`trim --apply\` leaves them on:`, ...standing.map((s) => `- ${s.name}`));
173
- if (!unused.length) out.push(kept.length || standing.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
192
+ if (!unused.length) out.push(kept.length || standing.length || unknown.length ? 'Nothing else to turn off.' : 'Every server that is on was used.');
174
193
  else if (pro)
175
194
  out.push(
176
195
  ...unused.map((s) => `- ${s.name}`),
@@ -188,25 +207,15 @@ export function codexTrimReport({ servers, used, usedMonth = null, startup, days
188
207
  unused: unused.map((s) => s.name),
189
208
  standing: standing.map((s) => s.name),
190
209
  kept: kept.map((s) => s.name),
210
+ unknown: unknown.map((s) => s.name),
191
211
  };
192
212
  }
193
213
 
194
- /** @param {string} path @param {string} text */
195
- function writeText(path, text) {
196
- const tmp = `${path}.limitcast-tmp`;
197
- const mode = existsSync(path) ? statSync(path).mode & 0o777 : 0o600;
198
- writeFileSync(tmp, text, { mode });
199
- chmodSync(tmp, mode);
200
- renameSync(tmp, path);
201
- }
202
-
203
214
  /** @returns {{at:number, servers:{name:string, prev:boolean|null}[]}[]} */
204
215
  function loadLedger() {
205
- try {
206
- return JSON.parse(readFileSync(ledgerPath(), 'utf8'));
207
- } catch {
208
- return [];
209
- }
216
+ const entries = readLedger(ledgerPath());
217
+ if (entries.some((e) => !Array.isArray(e.servers))) throw new Error('invalid Codex trim ledger');
218
+ return entries;
210
219
  }
211
220
 
212
221
  /**
@@ -214,31 +223,41 @@ function loadLedger() {
214
223
  * @param {string[]} names
215
224
  */
216
225
  export function applyCodexTrim(names, { now = Date.now(), path = codexConfigPath() } = {}) {
217
- if (!names.length || !existsSync(path)) return [];
218
- const toml = readFileSync(path, 'utf8');
219
- const before = new Map(codexServers(toml).map((s) => [s.name, s.enabled]));
220
- copyFileSync(path, `${path}.limitcast-backup-${new Date(now).toISOString().replace(/[:.]/g, '-')}`);
221
- writeText(path, setEnabled(toml, Object.fromEntries(names.map((n) => [n, false]))));
222
- const servers = names.map((name) => ({ name, prev: before.get(name) ?? null }));
223
- mkdirSync(stateDir(), { recursive: true });
224
- writeFileSync(ledgerPath(), JSON.stringify([...loadLedger(), { at: now, servers }], null, 2));
225
- return servers;
226
+ return withStateLock(() => {
227
+ recoverTransaction(ledgerPath());
228
+ const ledger = loadLedger();
229
+ if (!names.length || !existsSync(path)) return [];
230
+ let toml;
231
+ const update = editText(path, (text) => {
232
+ toml = text;
233
+ return setEnabled(text, Object.fromEntries(names.map((n) => [n, false])));
234
+ });
235
+ const before = new Map(codexServers(toml).map((s) => [s.name, s.enabled]));
236
+ copyFileSync(path, `${path}.limitcast-backup-${new Date(now).toISOString().replace(/[:.]/g, '-')}`);
237
+ const servers = names.map((name) => ({ name, prev: before.get(name) ?? null }));
238
+ commitTransaction(ledgerPath(), [...ledger, { at: now, servers }], [update]);
239
+ return servers;
240
+ });
226
241
  }
227
242
 
228
243
  /** Reverse the last --apply: each server goes back to its previous setting (or no `enabled` key). */
229
244
  export function undoCodexTrim({ path = codexConfigPath() } = {}) {
230
- const ledger = loadLedger();
231
- const last = ledger.pop();
232
- if (!last || !existsSync(path)) return null;
233
- const toml = readFileSync(path, 'utf8');
234
- copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
235
- // Only servers still off: anything turned back on since is left as the user set it.
236
- const off = new Set(
237
- codexServers(toml)
238
- .filter((s) => s.enabled === false)
239
- .map((s) => s.name),
240
- );
241
- writeText(path, setEnabled(toml, Object.fromEntries(last.servers.filter((s) => off.has(s.name)).map((s) => [s.name, s.prev]))));
242
- writeFileSync(ledgerPath(), JSON.stringify(ledger, null, 2));
243
- return last;
245
+ return withStateLock(() => {
246
+ recoverTransaction(ledgerPath());
247
+ const ledger = loadLedger();
248
+ const last = ledger.pop();
249
+ if (!last || !existsSync(path)) return null;
250
+ const update = editText(path, (toml) => {
251
+ // Only servers still off: anything turned back on since is left as the user set it.
252
+ const off = new Set(
253
+ codexServers(toml)
254
+ .filter((s) => s.enabled === false)
255
+ .map((s) => s.name),
256
+ );
257
+ return setEnabled(toml, Object.fromEntries(last.servers.filter((s) => off.has(s.name)).map((s) => [s.name, s.prev])));
258
+ });
259
+ copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
260
+ commitTransaction(ledgerPath(), ledger, [update]);
261
+ return last;
262
+ });
244
263
  }
package/src/grok.mjs CHANGED
@@ -4,7 +4,8 @@ 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, updateConfig } from './store.mjs';
7
+ import { KEEP_MS, stateDir, updateConfig, withStateLock } from './store.mjs';
8
+ import { commitTransaction, editText, readLedger, recoverTransaction } from './transaction.mjs';
8
9
  import { grokRoot } from './usage.mjs';
9
10
 
10
11
  /** @typedef {import('./forecast.mjs').Sample} Sample */
@@ -137,41 +138,49 @@ export function grokTrimReport({ servers, used, usedMonth = null, startup, days,
137
138
  * @param {string[]} names
138
139
  */
139
140
  export function applyGrokTrim(names, { now = Date.now(), path = grokConfigPath() } = {}) {
140
- if (!names.length || !existsSync(path)) return [];
141
- const toml = readFileSync(path, 'utf8');
142
- const before = new Map(codexServers(toml).map((s) => [s.name, s.enabled]));
143
- copyFileSync(path, `${path}.limitcast-backup-${new Date(now).toISOString().replace(/[:.]/g, '-')}`);
144
- writeText(path, setEnabled(toml, Object.fromEntries(names.map((n) => [n, false]))));
145
- const servers = names.map((name) => ({ name, prev: before.get(name) ?? null }));
146
- mkdirSync(stateDir(), { recursive: true });
147
- writeFileSync(trimLedger(), JSON.stringify([...loadTrimLedger(), { at: now, servers }], null, 2));
148
- return servers;
141
+ return withStateLock(() => {
142
+ recoverTransaction(trimLedger());
143
+ const ledger = loadTrimLedger();
144
+ if (!names.length || !existsSync(path)) return [];
145
+ let toml;
146
+ const update = editText(path, (text) => {
147
+ toml = text;
148
+ return setEnabled(text, Object.fromEntries(names.map((n) => [n, false])));
149
+ });
150
+ const before = new Map(codexServers(toml).map((s) => [s.name, s.enabled]));
151
+ copyFileSync(path, `${path}.limitcast-backup-${new Date(now).toISOString().replace(/[:.]/g, '-')}`);
152
+ const servers = names.map((name) => ({ name, prev: before.get(name) ?? null }));
153
+ commitTransaction(trimLedger(), [...ledger, { at: now, servers }], [update]);
154
+ return servers;
155
+ });
149
156
  }
150
157
 
151
158
  /** Reverse the last --apply. Servers the user turned back on stay on. */
152
159
  export function undoGrokTrim({ path = grokConfigPath() } = {}) {
153
- const ledger = loadTrimLedger();
154
- const last = ledger.pop();
155
- if (!last || !existsSync(path)) return null;
156
- const toml = readFileSync(path, 'utf8');
157
- copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
158
- const off = new Set(
159
- codexServers(toml)
160
- .filter((s) => s.enabled === false)
161
- .map((s) => s.name),
162
- );
163
- writeText(path, setEnabled(toml, Object.fromEntries(last.servers.filter((s) => off.has(s.name)).map((s) => [s.name, s.prev]))));
164
- writeFileSync(trimLedger(), JSON.stringify(ledger, null, 2));
165
- return last;
160
+ return withStateLock(() => {
161
+ recoverTransaction(trimLedger());
162
+ const ledger = loadTrimLedger();
163
+ const last = ledger.pop();
164
+ if (!last || !existsSync(path)) return null;
165
+ const update = editText(path, (toml) => {
166
+ const off = new Set(
167
+ codexServers(toml)
168
+ .filter((s) => s.enabled === false)
169
+ .map((s) => s.name),
170
+ );
171
+ return setEnabled(toml, Object.fromEntries(last.servers.filter((s) => off.has(s.name)).map((s) => [s.name, s.prev])));
172
+ });
173
+ copyFileSync(path, `${path}.limitcast-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
174
+ commitTransaction(trimLedger(), ledger, [update]);
175
+ return last;
176
+ });
166
177
  }
167
178
 
168
179
  /** @returns {{at:number, servers:{name:string, prev:boolean|null}[]}[]} */
169
180
  function loadTrimLedger() {
170
- try {
171
- return JSON.parse(readFileSync(trimLedger(), 'utf8'));
172
- } catch {
173
- return [];
174
- }
181
+ const entries = readLedger(trimLedger());
182
+ if (entries.some((e) => !Array.isArray(e.servers))) throw new Error('invalid Grok trim ledger');
183
+ return entries;
175
184
  }
176
185
 
177
186
  /**
@@ -553,7 +562,7 @@ export function installGrok({ guard, alerts = false, self, home = grokHome() })
553
562
  if (wantAlerts) {
554
563
  // Grok accepts Claude's tool names in a matcher (Read is read_file) and its MCP calls as mcp__server__tool.
555
564
  (hooks.PreToolUse ??= []).push({
556
- matcher: 'Read|Grep|mcp__.*',
565
+ matcher: 'Read|Grep',
557
566
  hooks: [{ type: 'command', command: `${self} tool-limit --src grok`, timeout: 10 }],
558
567
  });
559
568
  hooks.PostToolUse = [
package/src/install.mjs CHANGED
@@ -120,12 +120,7 @@ export function install({
120
120
  isToolCheck,
121
121
  );
122
122
  changes.push('added the large tool-output notice');
123
- upsertHook(
124
- cfg,
125
- 'PreToolUse',
126
- { matcher: 'Bash|Read|Grep|WebFetch|mcp__.*', hooks: [{ type: 'command', command: `${self} tool-limit`, timeout: 10 }] },
127
- isToolLimit,
128
- );
123
+ upsertHook(cfg, 'PreToolUse', { matcher: 'Read|Grep', hooks: [{ type: 'command', command: `${self} tool-limit`, timeout: 10 }] }, isToolLimit);
129
124
  changes.push('added the fat-tool limit check');
130
125
  }
131
126
  if (optimize) {
@@ -149,20 +144,14 @@ export function install({
149
144
  if (alerts && existsSync(join(codexPath, '..'))) {
150
145
  const codex = readSettings(codexPath);
151
146
  backup(codexPath);
152
- // Codex has no Read or Grep tool; its fat results come from shell commands and MCP tools. The check learns each
153
- // tool's usual result size as it goes, and only MCP calls (which take a limit) are held.
147
+ // Codex has no native Read/Grep controls. Keep result notices and remove the legacy generic MCP pre-call hold.
154
148
  upsertHook(
155
149
  codex,
156
150
  'PostToolUse',
157
151
  { matcher: 'Bash|mcp__.*', hooks: [{ type: 'command', command: `${self} tool-check --src codex`, timeout: 10 }] },
158
152
  isToolCheck,
159
153
  );
160
- upsertHook(
161
- codex,
162
- 'PreToolUse',
163
- { matcher: 'mcp__.*', hooks: [{ type: 'command', command: `${self} tool-limit --src codex`, timeout: 10 }] },
164
- isToolLimit,
165
- );
154
+ if (codex.hooks?.PreToolUse) codex.hooks.PreToolUse = codex.hooks.PreToolUse.filter((h) => !isToolLimit(h));
166
155
  upsertHook(
167
156
  codex,
168
157
  'SessionStart',
@@ -21,6 +21,13 @@ export function runOptimizationHook(hook, host) {
21
21
  });
22
22
  if (job) startModelWorker(repo, job);
23
23
  const context = [result.context, result.map ? repositoryMap(repo) : ''].filter(Boolean).join('\n\n');
24
+ if (context)
25
+ changeOptimization(repo, (state) => {
26
+ const m = (state.measurements ??= { injections: 0, contextChars: 0, estimatedContextTokens: 0 });
27
+ m.injections++;
28
+ m.contextChars += context.length;
29
+ m.estimatedContextTokens += Math.ceil(context.length / 4);
30
+ });
24
31
  if (host === 'copilot') return context ? { additionalContext: context } : result.notice ? { additionalContext: result.notice } : {};
25
32
  return {
26
33
  ...(result.notice ? { systemMessage: result.notice } : {}),
@@ -125,6 +132,12 @@ export function runOptimize(args, cwd = process.cwd()) {
125
132
  HOSTS.map((h) => [h, { completedSessions: state.hosts[h]?.completed ?? 0, proposed: capabilityProposals(state, h, configuredServers(h)) }]),
126
133
  ),
127
134
  receipts: state.receipts,
135
+ measurements: {
136
+ injectedContext: state.measurements ?? { injections: 0, contextChars: 0, estimatedContextTokens: 0 },
137
+ modelCalls: state.model?.receipts ?? [],
138
+ taskSuccess: 'unmeasured; completed sessions are not proof of task success',
139
+ netSavings: 'unproven; injected context and model calls add overhead',
140
+ },
128
141
  applied: Object.fromEntries(Object.entries(state.applied ?? {}).map(([h, a]) => [h, a.names])),
129
142
  };
130
143
  }
package/src/store.mjs CHANGED
@@ -1,6 +1,20 @@
1
1
  // @ts-check
2
2
  import { randomUUID } from 'node:crypto';
3
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import {
4
+ appendFileSync,
5
+ closeSync,
6
+ existsSync,
7
+ mkdirSync,
8
+ openSync,
9
+ readdirSync,
10
+ readFileSync,
11
+ renameSync,
12
+ rmdirSync,
13
+ rmSync,
14
+ statSync,
15
+ unlinkSync,
16
+ writeFileSync,
17
+ } from 'node:fs';
4
18
  import { homedir } from 'node:os';
5
19
  import { join } from 'node:path';
6
20
 
@@ -30,49 +44,80 @@ export function writeAtomic(/** @type {string} */ path, /** @type {string} */ te
30
44
  }
31
45
  }
32
46
 
33
- const LOCK_STALE_MS = 2_000; // the lock is held for one read and one write; older than this means its owner died
34
- const LOCK_WAIT_MS = 5_000;
47
+ const LOCK_WAIT_MS = 10_000;
48
+
49
+ function releaseLock(lock, owner) {
50
+ try {
51
+ unlinkSync(join(lock, owner));
52
+ // A contender can replace the now-empty directory with its populated lock. Never remove that lock recursively.
53
+ rmdirSync(lock);
54
+ } catch (error) {
55
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error;
56
+ }
57
+ }
58
+
59
+ /** Serialize settings and trim transactions. Publish a populated owner directory atomically; reclaim only dead owners. */
60
+ export function withStateLock(change) {
61
+ const dir = stateDir();
62
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
63
+ const lock = join(dir, 'config.json.lock');
64
+ const owner = `${process.pid}-${randomUUID()}`;
65
+ const candidate = `${lock}.${owner}`;
66
+ mkdirSync(candidate, { mode: 0o700 });
67
+ let acquired = false;
68
+ try {
69
+ writeFileSync(join(candidate, owner), '', { mode: 0o600 });
70
+ const start = Date.now();
71
+ for (;;) {
72
+ try {
73
+ renameSync(candidate, lock);
74
+ acquired = true;
75
+ break;
76
+ } catch (error) {
77
+ if (!['EEXIST', 'ENOTEMPTY'].includes(error.code)) throw error;
78
+ }
79
+ try {
80
+ for (const other of readdirSync(lock)) {
81
+ const pid = /^(\d+)-[a-f0-9-]+$/.exec(other)?.[1];
82
+ if (!pid) continue;
83
+ try {
84
+ process.kill(Number(pid), 0);
85
+ } catch (error) {
86
+ if (error.code === 'ESRCH') releaseLock(lock, other);
87
+ else if (error.code !== 'EPERM') throw error;
88
+ }
89
+ }
90
+ } catch (error) {
91
+ if (error.code !== 'ENOENT') throw error;
92
+ }
93
+ if (Date.now() - start > LOCK_WAIT_MS) throw new Error('could not lock settings: another limitcast command is changing settings');
94
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 2 + Math.floor(Math.random() * 8));
95
+ }
96
+ return change();
97
+ } finally {
98
+ if (acquired) releaseLock(lock, owner);
99
+ rmSync(candidate, { recursive: true, force: true });
100
+ }
101
+ }
35
102
 
36
103
  /**
37
104
  * Change config.json under a lock: read it, let `change` return the new settings (or the same object to leave the file
38
105
  * alone), write it. Without the lock, two commands that each read the file and then each write it lose one change.
39
- * shortcut: two waiters that break the same stale lock in the same instant can both write; fix with a lockfile library if seen.
40
106
  * @param {(cfg: any) => any} change
41
107
  */
42
108
  export function updateConfig(change) {
43
- const dir = stateDir();
44
- mkdirSync(dir, { recursive: true });
45
- const file = join(dir, 'config.json');
46
- const lock = `${file}.lock`;
47
- const start = Date.now();
48
- for (;;) {
49
- try {
50
- mkdirSync(lock); // atomic: exactly one process creates it
51
- break;
52
- } catch (e) {
53
- if (/** @type {NodeJS.ErrnoException} */ (e).code !== 'EEXIST') throw e;
54
- try {
55
- if (Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) rmSync(lock, { recursive: true, force: true });
56
- } catch {
57
- /* released while we looked */
58
- }
59
- if (Date.now() - start > LOCK_WAIT_MS) throw new Error(`could not lock ${file}: another limitcast command is changing settings`);
60
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
61
- }
62
- }
63
- try {
109
+ return withStateLock(() => {
110
+ const file = join(stateDir(), 'config.json');
64
111
  let cfg = {};
65
112
  try {
66
113
  cfg = JSON.parse(readFileSync(file, 'utf8'));
67
- } catch {
68
- /* new or corrupt: start fresh */
114
+ } catch (error) {
115
+ if (error.code !== 'ENOENT') throw new Error('cannot read settings JSON; preserve config.json and repair it before retrying');
69
116
  }
70
- if (!cfg || typeof cfg !== 'object') cfg = {};
117
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) throw new Error('settings JSON must be an object; preserve config.json');
71
118
  const next = change(cfg);
72
119
  if (next !== cfg) writeAtomic(file, JSON.stringify(next));
73
- } finally {
74
- rmSync(lock, { recursive: true, force: true });
75
- }
120
+ });
76
121
  }
77
122
 
78
123
  /**
package/src/toollimit.mjs CHANGED
@@ -4,13 +4,12 @@ import { join } from 'node:path';
4
4
  import { stateDir, writeAtomic } from './store.mjs';
5
5
  import { toolKey } from './toolcheck.mjs';
6
6
 
7
- // PreToolUse: a tool whose recent results are fat, and whose call sets no limit, is denied before it runs.
7
+ // PreToolUse: a native Read/Grep whose recent results are fat is bounded before it runs.
8
8
  // Rewriting a limit that is already present but huge keeps the call and caps it. Bash and WebFetch are left
9
9
  // alone: they have no limit argument, so a missing one is every call. Stats come from `report --why` / `--jobs`.
10
10
 
11
11
  export const FAT_AVG = 5_000;
12
12
  export const MIN_CALLS = 3;
13
- const MCP_CAP = 100;
14
13
  const READ_CAP = 400;
15
14
  const LIMIT_KEYS = new Set(['limit', 'max_results', 'maxresults', 'page_size', 'pagesize', 'top_k', 'topk', 'first']);
16
15
 
@@ -142,6 +141,8 @@ const k = (/** @type {number} */ n) => `${Math.max(1, Math.round(n / 1000))}k`;
142
141
  */
143
142
  export function toolLimitDecision(toolName, input, stats, { host = 'claude', rewrite = true } = {}) {
144
143
  const key = toolKey(toolName, host);
144
+ // MCP argument names do not establish pagination or read-only semantics. Their PostToolUse notices remain available.
145
+ if (toolName.startsWith('mcp__') || key.startsWith('mcp:')) return null;
145
146
  const stat = stats?.[key];
146
147
  if (!stat || stat.calls < MIN_CALLS || stat.avg < FAT_AVG) return null;
147
148
  const args = typeof input === 'string' ? tryJson(input) : input;
@@ -154,9 +155,9 @@ export function toolLimitDecision(toolName, input, stats, { host = 'claude', rew
154
155
  deny: `limitcast: Grep results average ≈${k(stat.avg)} tokens a call over ${stat.calls} calls. Add a path or a glob, then retry. Set LIMITCAST_ALLOW=1 to run it as written.`,
155
156
  };
156
157
  }
157
- if (toolName !== 'Read' && key !== 'Read' && !toolName.startsWith('mcp__') && !key.startsWith('mcp:')) return null;
158
- const cap = toolName === 'Read' || key === 'Read' ? READ_CAP : MCP_CAP;
159
- const limits = findLimits(obj);
158
+ if (toolName !== 'Read' && key !== 'Read') return null;
159
+ const cap = READ_CAP;
160
+ const limits = findLimits({ limit: obj.limit });
160
161
  if (limits.some((f) => f.value > 0 && f.value <= cap)) return null;
161
162
  const big = limits.find((f) => f.value > cap);
162
163
  const label = toolName === 'Read' || key === 'Read' ? 'Read' : key.replace(/^mcp:/, '');
@@ -0,0 +1,93 @@
1
+ import { lstatSync, readFileSync, unlinkSync } from 'node:fs';
2
+ import { writeAtomic } from './store.mjs';
3
+
4
+ export function readText(path) {
5
+ try {
6
+ if (!lstatSync(path).isFile()) throw new Error('refusing non-file configuration or recovery record');
7
+ return readFileSync(path, 'utf8');
8
+ } catch (error) {
9
+ if (error.code === 'ENOENT') return null;
10
+ throw error;
11
+ }
12
+ }
13
+
14
+ export function readLedger(path) {
15
+ const text = readText(path);
16
+ if (text === null) return [];
17
+ try {
18
+ const entries = JSON.parse(text);
19
+ if (Array.isArray(entries) && entries.every((e) => e && typeof e === 'object' && !Array.isArray(e))) return entries;
20
+ } catch {
21
+ /* preserve invalid recovery evidence */
22
+ }
23
+ throw new Error('invalid trim ledger; preserve it and repair before retrying');
24
+ }
25
+
26
+ export function editText(path, edit) {
27
+ const before = readText(path);
28
+ return { path, before, after: edit(before) };
29
+ }
30
+
31
+ export function editJson(path, edit) {
32
+ return editText(path, (before) => {
33
+ let cfg;
34
+ try {
35
+ cfg = JSON.parse(before ?? '{}');
36
+ } catch {
37
+ throw new Error('invalid configuration JSON; original bytes preserved');
38
+ }
39
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) throw new Error('configuration must be an object');
40
+ edit(cfg);
41
+ return `${JSON.stringify(cfg, null, 2)}\n`;
42
+ });
43
+ }
44
+
45
+ const write = (path, text) => (text === null ? unlinkSync(path) : writeAtomic(path, text));
46
+
47
+ /** Called under the state lock. Resolve a fully committed operation, or roll back a partial one without overwriting edits. */
48
+ export function recoverTransaction(ledger) {
49
+ const journal = `${ledger}.pending.json`;
50
+ const text = readText(journal);
51
+ if (text === null) return;
52
+ let tx;
53
+ try {
54
+ tx = JSON.parse(text);
55
+ } catch {
56
+ throw new Error('invalid trim recovery record; preserve it for manual recovery');
57
+ }
58
+ if (
59
+ tx.version !== 1 ||
60
+ !Array.isArray(tx.changes) ||
61
+ !tx.changes.length ||
62
+ tx.changes.at(-1)?.path !== ledger ||
63
+ tx.changes.some((c) => !c || typeof c.path !== 'string' || ![c.before, c.after].every((v) => v === null || typeof v === 'string'))
64
+ )
65
+ throw new Error('unsupported trim recovery record; preserve it for manual recovery');
66
+ const current = tx.changes.map((c) => readText(c.path));
67
+ if (tx.changes.some((c, i) => current[i] !== c.before && current[i] !== c.after))
68
+ throw new Error('configuration changed after interrupted trim; recovery record retained, reconcile manually');
69
+ if (!tx.changes.every((c, i) => current[i] === c.after)) {
70
+ for (const c of tx.changes.toReversed()) {
71
+ if (readText(c.path) === c.after && c.before !== c.after) write(c.path, c.before);
72
+ }
73
+ }
74
+ unlinkSync(journal);
75
+ }
76
+
77
+ /** Journal all original bytes before the first write, including the undo ledger. Caller holds the state lock. */
78
+ export function commitTransaction(ledger, entries, updates) {
79
+ const changes = [...updates, editText(ledger, () => `${JSON.stringify(entries, null, 2)}\n`)];
80
+ if (changes.some((c) => readText(c.path) !== c.before)) throw new Error('configuration changed during trim; retry after reviewing it');
81
+ const journal = `${ledger}.pending.json`;
82
+ writeAtomic(journal, JSON.stringify({ version: 1, changes }));
83
+ try {
84
+ for (const c of changes) {
85
+ if (readText(c.path) !== c.before) throw new Error('configuration changed during trim');
86
+ if (c.before !== c.after) write(c.path, c.after);
87
+ }
88
+ unlinkSync(journal);
89
+ } catch (error) {
90
+ recoverTransaction(ledger);
91
+ throw error;
92
+ }
93
+ }