limitcast 0.18.2 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -38,6 +38,8 @@
38
38
 
39
39
  - **Start lighter.** Inspect unused skills and MCP servers, then trim with backups and undo. Apply turns off only MCP servers quiet for 30 days. `limitcast trim`
40
40
 
41
+ - **Learn from repository evidence.** Opt into repeated-failure detection, safe check-command learning, reversible built-in capability pruning and a bounded source map. `limitcast install --optimize` — see [the optimizer guide](docs/optimizer.md) for scope, safeguards and verification limits. Optional model-backed judging/learning and Copilot/Pi adapters are available; model calls consume your Codex plan.
42
+
41
43
  <a id="free-and-open-source"></a>
42
44
 
43
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+**.
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,
@@ -68,6 +68,7 @@ import { doctor, install, installedFeatures, readSettings, settingsPath, uninsta
68
68
  import { memoryCheck, memoryDir, memoryReport, scanMemory } from '../src/memory.mjs';
69
69
  import { buildNotifierApp, loadChannels, notifierApp, notifyChanges, notifyEnabled, send, setChannel, setNotify } from '../src/notify.mjs';
70
70
  import { onboardingReport } from '../src/onboarding.mjs';
71
+ import { runOptimizationHook, runOptimize } from '../src/optimize-cli.mjs';
71
72
  import { driftMessage, loadOverhead, recordOverhead, savedPerSession, savedSummary, snapshot } from '../src/overhead.mjs';
72
73
  import { advise, getPlan, loadPeaks, PLANS, planPrices, planStats, recordPeaks, setPlan } from '../src/plan.mjs';
73
74
  import { costOf, fmtUsd } from '../src/prices.mjs';
@@ -112,6 +113,13 @@ const HELP = `limitcast ${VERSION}: stretch your Claude Code, Codex and Grok pla
112
113
  limitcast trim --grok the same for Grok: system prompt size and MCP servers you haven't used
113
114
  limitcast grok-usage [on|off] Grok's weekly % used, from grok.com with the login Grok holds (off by default)
114
115
  limitcast memory [dir] check this project's auto-memory: load cap, broken links, unlinked and oversized files
116
+ limitcast install --optimize opt-in local loop detection and repository optimizer hooks
117
+ limitcast optimize install --copilot|--pi install the optional host adapter (--undo removes it)
118
+ limitcast optimize model on|off opt into bounded Codex-backed learning/judging (uses your plan)
119
+ limitcast optimize status inspect repository evidence, proposals and optimization receipts
120
+ limitcast optimize learn on|off learn safe check-command alternatives; three independent sessions to promote
121
+ limitcast optimize map [on|off] show a bounded source-symbol map or opt into session-start injection
122
+ limitcast optimize capabilities --codex preview unused built-in packages; --apply <names> / --undo
115
123
  limitcast results [--days N] limits you reached, how far ahead limitcast warned, what the guard blocked
116
124
  [--share] totals only, safe to post
117
125
  limitcast license show the MIT license status
@@ -190,7 +198,22 @@ const days = () => {
190
198
  return Math.max(1, n);
191
199
  };
192
200
 
193
- if (cmd === 'status') {
201
+ if (cmd === '_optimize-hook') {
202
+ try {
203
+ if (process.env.LIMITCAST_ALLOW !== '1') console.log(JSON.stringify(runOptimizationHook(JSON.parse(readStdin()), flag('--src') ?? 'claude')));
204
+ } catch {
205
+ // Hook payloads and settings can contain secrets; never echo a failed parse or its input.
206
+ console.error('limitcast optimizer skipped: invalid hook, repository or state; run optimize status to inspect');
207
+ }
208
+ } else if (cmd === 'optimize') {
209
+ try {
210
+ const result = runOptimize(args);
211
+ console.log(result.text ?? JSON.stringify(result, null, 2));
212
+ } catch (error) {
213
+ console.error(error instanceof SyntaxError ? 'Invalid optimizer JSON; preserve the file and repair it before retrying.' : error.message);
214
+ process.exitCode = 1;
215
+ }
216
+ } else if (cmd === 'status') {
194
217
  if (grokQuotaEnabled() && grokPresent()) await refreshGrokQuota(now);
195
218
  const rows = forecastAll(oneClaudeAccount([...load(now - KEEP_MS), ...(await readCodex(now - KEEP_MS)), ...grokSamples(now)]), now);
196
219
  if (args.includes('--json')) console.log(JSON.stringify(rows, null, 2));
@@ -598,7 +621,7 @@ if (cmd === 'status') {
598
621
  } else if (cmd === 'install') {
599
622
  const wantGuard = args.includes('--guard');
600
623
  const wantAlerts = args.includes('--alerts');
601
- for (const c of install({ guard: wantGuard, alerts: wantAlerts })) console.log(`✓ ${c}`);
624
+ for (const c of install({ guard: wantGuard, alerts: wantAlerts, optimize: args.includes('--optimize') })) console.log(`✓ ${c}`);
602
625
  if (ensureDefaultKeep().seeded) console.log('Kept ego-browser: trim --apply will not turn it off. Add more with limitcast trim keep <name>.');
603
626
  console.log('Restart Claude Code, Codex and Grok to load it. Then: limitcast doctor');
604
627
  if (wantGuard && grokPresent() && !getGrokBudget())
@@ -659,7 +682,7 @@ if (cmd === 'status') {
659
682
  const f = installedFeatures();
660
683
  if (!f.statusLine) console.log('limitcast is not installed. Run `limitcast install` first.');
661
684
  else {
662
- for (const c of install({ guard: f.guard, alerts: f.alerts })) console.log(`✓ ${c}`);
685
+ for (const c of install({ guard: f.guard, alerts: f.alerts, optimize: f.optimize })) console.log(`✓ ${c}`);
663
686
  ensureDefaultKeep();
664
687
  console.log('Restart Claude Code, Codex and Grok to load it. Codex asks you to approve the guard again: start Codex and accept it.');
665
688
  }
@@ -723,7 +746,7 @@ if (cmd === 'status') {
723
746
  .split(',')
724
747
  .map((n) => n.trim())
725
748
  .filter(Boolean);
726
- if (names.length) setKeep(drop ? getKeep().filter((k) => !isKept(names, k)) : [...getKeep(), ...names]);
749
+ if (names.length) editKeep((keep) => (drop ? keep.filter((k) => !isKept(names, k)) : [...keep, ...names]));
727
750
  const keep = getKeep();
728
751
  console.log(keep.length ? `Kept by \`trim --apply\`: ${keep.join(', ')}` : 'Nothing on the keep-list. Example: limitcast trim keep ego-browser');
729
752
  process.exit(0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "limitcast",
3
- "version": "0.18.2",
3
+ "version": "0.19.1",
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, writeAtomic } 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
- writeAtomic(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
 
@@ -0,0 +1,125 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';
3
+ import { dirname, join, relative, sep } from 'node:path';
4
+ import { capabilityProposals, changeOptimization, digest, readOptimization, saveOptimization } from './optimize.mjs';
5
+ import { writeAtomic } from './store.mjs';
6
+
7
+ const KEYS = { collaboration: ['multi_agent'], goals: ['goals'], image_media: ['view_image'] };
8
+ const configPath = (repo, host) => join(repo.root, host === 'codex' ? '.codex/config.toml' : '.claude/settings.local.json');
9
+
10
+ function safePath(repo, file) {
11
+ for (let path = file; path !== repo.root; path = dirname(path)) {
12
+ if (!path.startsWith(`${repo.root}${sep}`)) throw new Error('configuration escapes the repository');
13
+ if (existsSync(path) && lstatSync(path).isSymbolicLink()) throw new Error('refusing symlinked configuration');
14
+ }
15
+ const tracked = execFileSync('git', ['-C', repo.root, 'ls-files', '--', relative(repo.root, file)], { encoding: 'utf8', timeout: 2000 });
16
+ if (tracked.trim()) throw new Error('refusing to change a tracked project configuration');
17
+ }
18
+
19
+ export function patchCodexCapabilities(text, names) {
20
+ if (names.some((n) => !Object.hasOwn(KEYS, n))) throw new Error('unsupported Codex capability');
21
+ const lines = text.split('\n');
22
+ const headers = lines.flatMap((line, i) => (/^\s*\[features\]\s*(?:#.*)?$/.test(line) ? [i] : []));
23
+ if (headers.length > 1 || /\[\s*["']features["']\s*\]|^\s*features\s*=/m.test(text)) throw new Error('ambiguous features table');
24
+ const start = headers[0];
25
+ const end = start === undefined ? lines.length : lines.findIndex((l, i) => i > start && /^\s*\[/.test(l));
26
+ const at = end < 0 ? lines.length : end;
27
+ const body = start === undefined ? '' : lines.slice(start + 1, at).join('\n');
28
+ const additions = [];
29
+ for (const key of names.flatMap((n) => KEYS[n])) {
30
+ if (new RegExp(`^\\s*["']?${key}["']?\\s*=`, 'm').test(body)) throw new Error(`preserve explicit ${key} setting; change it yourself`);
31
+ additions.push(`${key} = false # limitcast optimizer`);
32
+ }
33
+ lines.splice(at, 0, ...(start === undefined ? ['', '[features]'] : []), ...additions);
34
+ return `${lines.join('\n').trimEnd()}\n`;
35
+ }
36
+
37
+ export function validateCodex(repo, disabled = []) {
38
+ // `features list` ignores -C on Codex 0.167; its actual cwd decides which project config is loaded.
39
+ const output = execFileSync('codex', ['features', 'list'], { cwd: repo.root, encoding: 'utf8', timeout: 5000, maxBuffer: 100_000 });
40
+ for (const key of Object.values(KEYS).flat()) {
41
+ if (!new RegExp(`^${key}\\s+(?:stable|experimental|under development)\\s+(?:true|false)$`, 'm').test(output))
42
+ throw new Error(`Codex does not expose supported ${key} control`);
43
+ }
44
+ for (const key of disabled.flatMap((name) => KEYS[name] ?? [])) {
45
+ if (!new RegExp(`^${key}\\s+.*\\s+false$`, 'm').test(output)) throw new Error(`Codex ignored the project ${key} setting; check project trust`);
46
+ }
47
+ }
48
+
49
+ export function applyCapabilities(repo, host, names, { validate = validateCodex } = {}) {
50
+ if (!['claude', 'codex'].includes(host) || !names.length) throw new Error('choose proposed Claude tools or Codex capabilities');
51
+ const file = configPath(repo, host);
52
+ safePath(repo, file);
53
+ if (host === 'codex') validate(repo);
54
+ const result = changeOptimization(repo, (state) => {
55
+ const proposal = capabilityProposals(state, host);
56
+ if (names.some((n) => !proposal.includes(n))) throw new Error('selection is protected, used, or lacks evidence; preview again');
57
+ if (state.applied?.[host]) throw new Error('restore the previous capability change before applying another');
58
+ if (existsSync(file) && statSync(file).size > 100_000) throw new Error('project configuration exceeds safe editing limit');
59
+ const before = existsSync(file) ? readFileSync(file, 'utf8') : null;
60
+ let after;
61
+ if (host === 'codex') after = patchCodexCapabilities(before ?? '', names);
62
+ else {
63
+ const cfg = JSON.parse(before ?? '{}');
64
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) throw new Error('settings must be an object');
65
+ if (cfg.permissions && (typeof cfg.permissions !== 'object' || Array.isArray(cfg.permissions))) throw new Error('invalid permissions');
66
+ cfg.permissions ??= {};
67
+ if (cfg.permissions.deny && !Array.isArray(cfg.permissions.deny)) throw new Error('invalid deny list');
68
+ if ((cfg.permissions.deny ?? []).some((name) => typeof name !== 'string')) throw new Error('invalid deny-list entry');
69
+ cfg.permissions.deny = [...new Set([...(cfg.permissions.deny ?? []), ...names])];
70
+ after = `${JSON.stringify(cfg, null, 2)}\n`;
71
+ }
72
+ state.applied ??= {};
73
+ state.applied[host] = { before, after: digest(after), names };
74
+ // Journal before changing the host: a killed process still leaves enough evidence to restore.
75
+ saveOptimization(repo, state);
76
+ try {
77
+ mkdirSync(dirname(file), { recursive: true });
78
+ if ((existsSync(file) ? readFileSync(file, 'utf8') : null) !== before) throw new Error('configuration changed during apply');
79
+ writeAtomic(file, after);
80
+ } catch (error) {
81
+ if (existsSync(file) && readFileSync(file, 'utf8') === after) {
82
+ if (before === null) unlinkSync(file);
83
+ else writeAtomic(file, before);
84
+ }
85
+ delete state.applied[host];
86
+ saveOptimization(repo, state);
87
+ throw error;
88
+ }
89
+ return { path: file, names, restart: true };
90
+ });
91
+ try {
92
+ if (host === 'codex') validate(repo, names);
93
+ } catch (error) {
94
+ restoreCapabilities(repo, host, { protect: false });
95
+ throw error;
96
+ }
97
+ return result;
98
+ }
99
+
100
+ export function restoreCapabilities(repo, host, { protect = true } = {}) {
101
+ const file = configPath(repo, host);
102
+ safePath(repo, file);
103
+ return changeOptimization(repo, (state) => {
104
+ const saved = state.applied?.[host];
105
+ if (!saved) return { restored: false };
106
+ const current = existsSync(file) ? readFileSync(file, 'utf8') : null;
107
+ if (current === saved.before) {
108
+ delete state.applied[host];
109
+ return { restored: true, recovered: true };
110
+ }
111
+ if (current === null || digest(current) !== saved.after)
112
+ throw new Error('configuration changed after apply; preserve your edits and reconcile manually');
113
+ if (saved.before === null) unlinkSync(file);
114
+ else writeAtomic(file, saved.before);
115
+ delete state.applied[host];
116
+ if (protect) state.config.keep = [...new Set([...state.config.keep, ...saved.names])];
117
+ return { restored: true, protected: saved.names };
118
+ });
119
+ }
120
+
121
+ export function capabilityStatus(repo, host) {
122
+ const state = readOptimization(repo);
123
+ if (host === 'codex') validateCodex(repo);
124
+ return { host, proposed: capabilityProposals(state, host), applied: state.applied?.[host]?.names ?? [], keep: state.config.keep };
125
+ }
package/src/flags.mjs CHANGED
@@ -5,6 +5,8 @@ export const KNOWN_FLAGS = [
5
5
  '--alerts',
6
6
  '--apply',
7
7
  '--codex',
8
+ '--copilot',
9
+ '--pi',
8
10
  '--days',
9
11
  '--detach',
10
12
  '--fix',
@@ -17,6 +19,7 @@ export const KNOWN_FLAGS = [
17
19
  '--json',
18
20
  '--no-open',
19
21
  '--out',
22
+ '--optimize',
20
23
  '--refresh',
21
24
  '--remove',
22
25
  '--share',
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, writeAtomic } 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
- writeAtomic(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
- writeAtomic(configFile(), JSON.stringify({ ...cfg, grokQuota: on }));
232
+ updateConfig((cfg) => ({ ...cfg, grokQuota: on }));
245
233
  }
246
234
 
247
235
  /** @returns {QuotaState} */
package/src/install.mjs CHANGED
@@ -78,9 +78,17 @@ export function launcherTargets(path) {
78
78
  * Idempotent; backs up settings.json first; remembers the original status line for uninstall.
79
79
  * With `guard`, Codex gets the guard too when ~/.codex exists. With `alerts`, a SessionStart hook tells you
80
80
  * (never the model) when your starting context grew.
81
- * @param {{guard:boolean, alerts?:boolean, path?:string, codexPath?:string, grokDir?:string, self?:string}} opts
81
+ * @param {{guard:boolean, alerts?:boolean, optimize?:boolean, path?:string, codexPath?:string, grokDir?:string, self?:string}} opts
82
82
  */
83
- export function install({ guard, alerts = false, path = settingsPath(), codexPath = codexHooksPath(), grokDir = grokHome(), self = selfCommand() }) {
83
+ export function install({
84
+ guard,
85
+ alerts = false,
86
+ optimize = false,
87
+ path = settingsPath(),
88
+ codexPath = codexHooksPath(),
89
+ grokDir = grokHome(),
90
+ self = selfCommand(),
91
+ }) {
84
92
  const cfg = readSettings(path);
85
93
  backup(path);
86
94
  const changes = [];
@@ -120,6 +128,10 @@ export function install({ guard, alerts = false, path = settingsPath(), codexPat
120
128
  );
121
129
  changes.push('added the fat-tool limit check');
122
130
  }
131
+ if (optimize) {
132
+ addOptimizerHooks(cfg, self, 'claude');
133
+ changes.push('added opt-in repository optimizer hooks (learning and map injection remain off until enabled per repository)');
134
+ }
123
135
  writeSettings(path, cfg);
124
136
  if (guard && existsSync(join(codexPath, '..'))) {
125
137
  const codex = readSettings(codexPath);
@@ -129,9 +141,43 @@ export function install({ guard, alerts = false, path = settingsPath(), codexPat
129
141
  changes.push('added the Codex subagent guard (Codex runs it after you trust it: start Codex and approve the new hook)');
130
142
  }
131
143
  if (grokPresent(grokDir)) changes.push(...installGrok({ guard, self, home: grokDir }));
144
+ if (optimize && existsSync(join(codexPath, '..'))) {
145
+ const codex = readSettings(codexPath);
146
+ backup(codexPath);
147
+ addOptimizerHooks(codex, self, 'codex');
148
+ writeSettings(codexPath, codex);
149
+ changes.push('added Codex optimizer hooks; review and trust the new hooks in Codex, then restart');
150
+ }
151
+ if (optimize && grokPresent(grokDir)) {
152
+ const optimizerPath = join(grokDir, 'hooks', 'limitcast-optimize.json');
153
+ const grok = readSettings(optimizerPath);
154
+ backup(optimizerPath);
155
+ addOptimizerHooks(grok, self, 'grok');
156
+ writeSettings(optimizerPath, grok);
157
+ changes.push('added Grok optimizer hooks');
158
+ }
132
159
  return changes;
133
160
  }
134
161
 
162
+ function addOptimizerHooks(cfg, self, host) {
163
+ const events = ['SessionStart', 'UserPromptSubmit', 'PostToolUse', 'PostToolUseFailure', 'Stop', 'SessionEnd'];
164
+ // Codex reports failed calls through PostToolUse; its native hook schema has no failure event.
165
+ for (const event of events.filter((e) => host !== 'codex' || e !== 'PostToolUseFailure'))
166
+ upsertHook(
167
+ cfg,
168
+ event,
169
+ {
170
+ matcher: '',
171
+ hooks: [{ type: 'command', command: `${self} _optimize-hook --src ${host}`, timeout: host === 'codex' && event === 'SessionEnd' ? 3 : 10 }],
172
+ },
173
+ isOptimizer,
174
+ );
175
+ }
176
+
177
+ function removeOptimizerHooks(cfg) {
178
+ for (const [event, entries] of Object.entries(cfg.hooks ?? {})) cfg.hooks[event] = entries.filter((entry) => !isOptimizer(entry));
179
+ }
180
+
135
181
  /**
136
182
  * Put the guard in PreToolUse: update it where it is, else append.
137
183
  * Codex trusts hooks by their position, so existing hooks must keep their places.
@@ -188,18 +234,26 @@ export function uninstall({ path = settingsPath(), codexPath = codexHooksPath(),
188
234
  cfg.hooks[event] = cfg.hooks[event].filter((/** @type {any} */ h) => !mine(h));
189
235
  if (cfg.hooks[event].length < n) changes.push(`removed ${what}`);
190
236
  }
237
+ removeOptimizerHooks(cfg);
191
238
  writeSettings(path, cfg);
192
239
  if (existsSync(codexPath)) {
193
240
  const codex = readSettings(codexPath);
194
241
  const list = codex.hooks?.PreToolUse ?? [];
195
- if (list.some(isGuard)) {
242
+ if (list.some(isGuard) || Object.values(codex.hooks ?? {}).some((entries) => entries.some(isOptimizer))) {
196
243
  backup(codexPath);
197
244
  codex.hooks.PreToolUse = list.filter((/** @type {any} */ h) => !isGuard(h));
245
+ removeOptimizerHooks(codex);
198
246
  writeSettings(codexPath, codex);
199
247
  changes.push('removed the Codex subagent guard');
200
248
  }
201
249
  }
202
250
  changes.push(...uninstallGrok({ home: grokDir }));
251
+ const optimizerPath = join(grokDir, 'hooks', 'limitcast-optimize.json');
252
+ if (existsSync(optimizerPath)) {
253
+ const grok = readSettings(optimizerPath);
254
+ removeOptimizerHooks(grok);
255
+ writeSettings(optimizerPath, grok);
256
+ }
203
257
  return changes;
204
258
  }
205
259
 
@@ -226,6 +280,7 @@ export function installedFeatures(path = settingsPath()) {
226
280
  statusLine: Boolean(cfg.statusLine?.command?.includes(MARK)),
227
281
  guard: (cfg.hooks?.PreToolUse ?? []).some(isGuard),
228
282
  alerts: (cfg.hooks?.SessionStart ?? []).some(isAlert),
283
+ ...((cfg.hooks?.SessionStart ?? []).some(isOptimizer) ? { optimize: true } : {}),
229
284
  };
230
285
  }
231
286
 
@@ -240,6 +295,7 @@ const isPromptCheck = runs(/\bprompt-check\b/);
240
295
  const isReceipt = runs(/\bsubagent-receipt\b/);
241
296
  const isToolCheck = runs(/\btool-check\b/);
242
297
  const isToolLimit = runs(/\btool-limit\b/);
298
+ const isOptimizer = runs(/\b_optimize-hook\b/);
243
299
 
244
300
  /** @param {string} path */
245
301
  export function readSettings(path) {
@@ -332,6 +388,11 @@ export function doctor({ path = settingsPath(), codexPath = codexHooksPath(), sa
332
388
  });
333
389
  }
334
390
  const hooks = /** @type {any} */ (cfg).hooks ?? {};
391
+ if ((hooks.SessionStart ?? []).some(isOptimizer))
392
+ out.push({
393
+ ok: true,
394
+ line: 'Repository optimizer hooks configured (runtime delivery unmeasured); learning and map injection are per-repository opt-ins',
395
+ });
335
396
  const guard = (hooks.PreToolUse ?? []).some(isGuard);
336
397
  out.push({
337
398
  ok: true,