@mainwave/cli 0.13.1 → 0.15.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.
@@ -5,10 +5,12 @@ import { countTrust, readCodexTrust } from './codex-trust.js';
5
5
  import { activeHierarchy, effectiveEnv } from './effective-settings.js';
6
6
  import { color, renderDiff } from './format.js';
7
7
  import { claudeHookShellMissing, GIT_BASH_FIX, GIT_BASH_MISSING_REASON } from './git-bash.js';
8
- import { activeManagedScans, BOOTSTRAP_KEY, commandGeneration, copyHookScripts, DEFAULT_MARKER_TOOL, deliveryKey, describeMarkersPlan, hooksBlocked, hostRunsBootstrap, installedHooksDir, isPlanSnapshot, isPlanSnapshotRoute, legacyCommandSends, managedDeliversEntry, managedDeliversPlanSnapshot, managedHooksDir, managedMarkerDeliveries, matchersForTool, packagedHooksDir, planMarkers, prepareMarkersFile, readPackagedMatchers, routeLabel, scanForMarkers, scanRoutes, selectHookMatchers, syncManagedHooks, syncOrgDelivered, userHookGroups, writeOptOutFlags, } from './markers.js';
8
+ import { activeManagedScans, BOOTSTRAP_KEY, codexRefreshCommand, commandGeneration, copyHookScripts, DEFAULT_MARKER_TOOL, deliveryKey, describeMarkersPlan, hooksBlocked, hostRunsBootstrap, installedHooksDir, isPlanSnapshot, isPlanSnapshotRoute, legacyCommandSends, managedDeliversEntry, managedDeliversPlanSnapshot, managedHooksDir, managedMarkerDeliveries, matchersForTool, packagedHooksDir, planMarkers, prepareMarkersFile, readPackagedMatchers, routeLabel, scanForMarkers, scanRoutes, selectHookMatchers, syncManagedHooks, syncOrgDelivered, userHookGroups, writeOptOutFlags, } from './markers.js';
9
+ import { hasCredentialShape } from './headers.js';
9
10
  import { isManagedLayer } from './layer-policy.js';
10
- import { adapterEffective } from './status.js';
11
- import { applyUpdate, prepareUpdate, readExistingEnv } from './settings.js';
11
+ import { adapterEffective, statusSetups } from './status.js';
12
+ import { applyUpdate, isSamePath, prepareUpdate, readExistingEnv, removeSettingsFile, } from './settings.js';
13
+ import { planSetupRemoval } from './setup-removal.js';
12
14
  import { say } from './ui.js';
13
15
  import { VERSION } from './version.js';
14
16
  const hasAnyChange = (diff) => diff.added.length > 0 || diff.changed.length > 0 || diff.removed.length > 0;
@@ -16,7 +18,7 @@ export const teamUcidStanding = async (adapter, ucid, stored) => {
16
18
  if (stored?.id === ucid)
17
19
  return stored.pinned ? 'pinned' : 'stored';
18
20
  const others = Object.values(adapters).filter((a) => a.name !== adapter.name);
19
- const carried = await Promise.all(others.map(async (a) => (await adapterEffective(a)).ucid));
21
+ const carried = await Promise.all(others.flatMap(statusSetups).map(async (s) => (await adapterEffective(s.adapter)).ucid));
20
22
  return carried.includes(ucid) ? 'shared' : 'own';
21
23
  };
22
24
  const writeTargets = (adapter) => ({
@@ -140,9 +142,11 @@ export const planAdapter = async (adapter, answers, context = {}) => {
140
142
  const delivered = managedMarkerDeliveries(managedScans);
141
143
  orgDeliversEntry = managedDeliversEntry(managedScans);
142
144
  planSnapshotOrgDelivered = planSnapshotOn !== null && managedDeliversPlanSnapshot(managedScans);
143
- const groups = hookShellMissing ? [] : userHookGroups(hosted, on, delivered, hookHost);
145
+ const groups = hookShellMissing
146
+ ? []
147
+ : userHookGroups(hosted, on, delivered, hookHost, adapter.markers?.hookArgs);
144
148
  const hooksFile = adapter.markers?.hooksFile;
145
- if (hooksFile) {
149
+ if (hooksFile && !isSamePath(hooksFile.path, primary)) {
146
150
  const prepared = await prepareMarkersFile(hooksFile.path, hooksFile.codec, groups);
147
151
  markersPlan = prepared.plan;
148
152
  separateMarkersUpdate = prepared.update;
@@ -168,7 +172,14 @@ export const planAdapter = async (adapter, answers, context = {}) => {
168
172
  codec: aw.codec,
169
173
  mode: aw.mode,
170
174
  })));
175
+ const replaced = (await Promise.all((adapter.replaces ?? []).map((r) => planSetupRemoval(r)))).flat();
171
176
  const labeled = [
177
+ ...replaced.map(({ update, remove, linkTarget }) => ({
178
+ label: update.path,
179
+ update,
180
+ ...(remove ? { remove } : {}),
181
+ ...(linkTarget !== undefined ? { linkTarget } : {}),
182
+ })),
172
183
  { label: primary, update: primaryUpdate },
173
184
  ...(separateMarkersUpdate
174
185
  ? [{ label: separateMarkersUpdate.path, update: separateMarkersUpdate }]
@@ -179,7 +190,9 @@ export const planAdapter = async (adapter, answers, context = {}) => {
179
190
  })),
180
191
  ];
181
192
  const markersChanged = markersPlan?.changed ?? false;
182
- const changed = labeled.filter(({ update }) => hasAnyChange(update.diff) || (update === markersCarrier && markersChanged));
193
+ const changed = labeled.filter(({ update }) => hasAnyChange(update.diff) ||
194
+ (update === markersCarrier && markersChanged) ||
195
+ replaced.some((r) => r.update === update && r.markersPlan?.changed === true));
183
196
  return {
184
197
  adapter,
185
198
  primaryPath: primary,
@@ -190,6 +203,8 @@ export const planAdapter = async (adapter, answers, context = {}) => {
190
203
  planSnapshotOrgDelivered,
191
204
  markersPlan,
192
205
  markersCarrier,
206
+ replaced: replaced.filter((r) => changed.some((c) => c.update === r.update)),
207
+ replacedHooksFiles: (adapter.replaces ?? []).flatMap((r) => r.markers?.hooksFile ? [r.markers.hooksFile.path] : []),
193
208
  hookHost,
194
209
  stageHooks,
195
210
  hookEvents,
@@ -245,14 +260,17 @@ export const renderPlan = (plan) => {
245
260
  say(color.dim(`${plan.adapter.displayName}: no changes needed in ${plan.primaryPath}.`));
246
261
  return;
247
262
  }
248
- for (const { label, update } of plan.changed) {
263
+ for (const { label, update, remove, linkTarget } of plan.changed) {
249
264
  say('');
250
265
  say(color.bold(`Changes to ${label}:`));
251
266
  const body = renderDiff(update.diff);
252
267
  if (body)
253
268
  say(body);
254
- if (update === plan.markersCarrier && plan.markersPlan?.changed) {
255
- for (const line of describeMarkersPlan(plan.markersPlan)) {
269
+ const markersPlan = update === plan.markersCarrier
270
+ ? plan.markersPlan
271
+ : plan.replaced.find((r) => r.update === update)?.markersPlan;
272
+ if (markersPlan?.changed) {
273
+ for (const line of describeMarkersPlan(markersPlan)) {
256
274
  const painted = line.startsWith('+')
257
275
  ? color.green(line)
258
276
  : line.startsWith('-')
@@ -261,6 +279,20 @@ export const renderPlan = (plan) => {
261
279
  say(painted);
262
280
  }
263
281
  }
282
+ if (remove) {
283
+ say(color.dim(' Nothing else is in it, so setup removes the file and keeps a backup beside it.'));
284
+ }
285
+ if (linkTarget !== undefined) {
286
+ say(color.dim(` Nothing else is in it, but it links to ${linkTarget}, so setup keeps the link ` +
287
+ 'and leaves that file empty ({}), which Codex reads as no hooks. It keeps a backup ' +
288
+ 'beside the link.'));
289
+ }
290
+ const moved = markersPlan?.movedForeign ?? 0;
291
+ if (plan.hookHost === 'codex' && moved > 0) {
292
+ say(color.yellow(` Removing Mainwave's hooks from ${update.path} moves ${moved} of your other ` +
293
+ 'hooks there to a new position, so Codex will ask you to trust them again ("Hooks need review", ' +
294
+ 'or /hooks) the next time it starts.'));
295
+ }
264
296
  }
265
297
  };
266
298
  export const planHasChanges = (plans) => plans.some((p) => p.changed.length > 0);
@@ -289,15 +321,47 @@ export const writePlan = async (plan, dirs = defaultHookDirs(), holdFlat = false
289
321
  say('');
290
322
  say(color.dim(`Hook scripts refreshed in ${dest}.`));
291
323
  }
292
- for (const { update } of plan.changed) {
293
- const result = await applyUpdate(update);
324
+ const done = [];
325
+ for (const { update, remove } of plan.changed) {
326
+ let result;
327
+ try {
328
+ result = remove
329
+ ? { backupPath: await removeSettingsFile(update.path), written: update.path }
330
+ : await applyUpdate(update);
331
+ }
332
+ catch (err) {
333
+ if (done.length > 0)
334
+ say(color.yellow(partialWriteNote(plan.adapter, done)));
335
+ throw err;
336
+ }
337
+ done.push({ update, result });
294
338
  say('');
295
- say(color.green(`✓ Wrote ${result.written}`));
339
+ say(color.green(`✓ ${remove ? 'Removed' : 'Wrote'} ${result.written}`));
296
340
  if (result.backupPath) {
297
341
  say(color.dim(` backup: ${result.backupPath}`));
298
342
  }
299
343
  }
300
344
  };
345
+ const setupCommand = (adapter) => ['mainwave-cli setup', adapter.name, ...(adapter.setupArgs ?? [])].join(' ');
346
+ const partialWriteNote = (adapter, done) => {
347
+ const lines = [
348
+ '',
349
+ '! Setup stopped before it finished. It had already changed these files:',
350
+ ...done.map(({ result }) => result.backupPath
351
+ ? ` ${result.written}, backup at ${result.backupPath}`
352
+ : ` ${result.written}, a new file`),
353
+ ];
354
+ const keyHolder = done.find(({ update, result }) => result.backupPath !== null &&
355
+ update.diff.removed.some(({ key, before }) => hasCredentialShape(`${key} ${before}`)));
356
+ if (keyHolder !== undefined) {
357
+ const { written } = keyHolder.result;
358
+ const command = setupCommand(adapter);
359
+ lines.push(` This run removed your Mainwave API key from ${written}. Its backup still holds the key.`, ` To recover, copy that backup back to ${written}, or run \`${command} --api-key <your key>\` again. ` +
360
+ `If you are signed in (\`mainwave-cli login\`), running \`${command}\` again is enough, since setup ` +
361
+ "then uses this machine's saved key or makes a new one.");
362
+ }
363
+ return lines.join('\n');
364
+ };
301
365
  export const printMarkerCoexistenceNotes = async (adapter, targetPath, markersOn = true) => {
302
366
  const scans = await scanForMarkers(await activeHierarchy(adapter));
303
367
  const activeManaged = new Set(activeManagedScans(scans));
@@ -358,12 +422,14 @@ export const printMarkerCoexistenceNotes = async (adapter, targetPath, markersOn
358
422
  }
359
423
  }
360
424
  };
361
- const codexTrustNote = (reading, hooksPath) => {
362
- const how = 'Start Codex and choose "Trust all" at the "Hooks need review" prompt, or open /hooks and trust each ' +
425
+ const codexTrustNote = (reading, hooksPath, profile) => {
426
+ const run = profile === undefined ? 'codex' : `codex --profile ${profile}`;
427
+ const exec = profile === undefined ? 'codex exec' : `codex exec --profile ${profile}`;
428
+ const how = `Start \`${run}\` and choose "Trust all" at the "Hooks need review" prompt, or open /hooks and trust each ` +
363
429
  'Mainwave hook, the session-start hook included. Codex asks again whenever a Mainwave hook changes, such as ' +
364
430
  'when a setup run adds a route or a release changes a command, so approve again after such a run; a run that ' +
365
431
  "removes a Mainwave hook moves the hooks after it, so Codex may ask about other tools' hooks too. " +
366
- '`codex exec` skips them unless it runs with --dangerously-bypass-hook-trust. ' +
432
+ `\`${exec}\` skips them unless it runs with --dangerously-bypass-hook-trust. ` +
367
433
  '`mainwave-cli doctor` reports the hooks Codex skips.';
368
434
  if (reading?.state === 'read') {
369
435
  const n = countTrust(reading.hooks);
@@ -396,7 +462,7 @@ export const printPostSetup = (plan) => {
396
462
  if (plan.hookEvents.includes('SessionStart')) {
397
463
  say('');
398
464
  say(color.dim(plan.hookHost === 'codex'
399
- ? `${plan.adapter.displayName} also runs \`npx @mainwave/cli@latest install-hooks --host codex\` in the background ` +
465
+ ? `${plan.adapter.displayName} also runs \`${codexRefreshCommand(plan.adapter.markers?.hookArgs)}\` in the background ` +
400
466
  'when a session starts, resumes or forks: it refreshes the hook scripts from the latest release and adds hooks ' +
401
467
  'a later release brings to the events above, never changing one you approved.'
402
468
  : `${plan.adapter.displayName} also runs \`npx @mainwave/cli@latest install-hooks\` in the background when a session ` +
@@ -407,9 +473,9 @@ export const printPostSetup = (plan) => {
407
473
  const hooksFile = plan.adapter.markers?.hooksFile;
408
474
  const reading = hooksFile === undefined
409
475
  ? undefined
410
- : readCodexTrust(hooksFile.path, plan.adapter.paths.global);
476
+ : readCodexTrust(hooksFile.path, plan.adapter.trustFiles ?? [], hooksFile.path, hooksFile.codec);
411
477
  say('');
412
- say(color.dim(codexTrustNote(reading, hooksFile?.path)));
478
+ say(color.dim(codexTrustNote(reading, hooksFile?.path, plan.adapter.codexProfile)));
413
479
  }
414
480
  const snippet = plan.adapter.printPostSetupInstructions?.(plan.input);
415
481
  if (snippet) {
@@ -0,0 +1,239 @@
1
+ import { tomlOtelCodec } from './toml-otel.js';
2
+ const RAW = Symbol('toml-profile:raw');
3
+ const CODEX_HOOK_EVENTS = new Set([
4
+ 'PreModelRequest',
5
+ 'PostModelRequest',
6
+ 'PreToolUse',
7
+ 'PermissionRequest',
8
+ 'PostToolUse',
9
+ 'PreCompact',
10
+ 'PostCompact',
11
+ 'SessionStart',
12
+ 'SessionEnd',
13
+ 'UserPromptSubmit',
14
+ 'SubagentStart',
15
+ 'SubagentStop',
16
+ 'Stop',
17
+ 'Interrupt',
18
+ ]);
19
+ const HANDLER_KEY_ORDER = ['type', 'command', 'commandWindows', 'timeout', 'async', 'statusMessage'];
20
+ const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
21
+ const keySegments = (raw) => {
22
+ const out = [];
23
+ let rest = raw.trim();
24
+ while (rest.length > 0) {
25
+ const m = /^(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|([A-Za-z0-9_-]+))\s*/.exec(rest);
26
+ if (m === null)
27
+ return undefined;
28
+ out.push(m[1] !== undefined ? unescapeBasic(m[1]) : (m[2] ?? m[3]));
29
+ rest = rest.slice(m[0].length);
30
+ if (rest.length === 0)
31
+ break;
32
+ if (!rest.startsWith('.'))
33
+ return undefined;
34
+ rest = rest.slice(1).trimStart();
35
+ }
36
+ return out;
37
+ };
38
+ const unescapeBasic = (s) => s.replace(/\\(u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)/g, (_m, c) => {
39
+ if (c[0] === 'u' || c[0] === 'U')
40
+ return String.fromCodePoint(parseInt(c.slice(1), 16));
41
+ return { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', '"': '"', '\\': '\\' }[c] ?? c;
42
+ });
43
+ const escapeBasic = (s) => '"' +
44
+ s.replace(/[\\"\u0000-\u001f\u007f]/g, (c) => {
45
+ const named = {
46
+ '\\': '\\\\',
47
+ '"': '\\"',
48
+ '\n': '\\n',
49
+ '\t': '\\t',
50
+ '\r': '\\r',
51
+ };
52
+ return named[c] ?? `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`;
53
+ }) +
54
+ '"';
55
+ const header = (line) => {
56
+ const m = /^\s*(\[\[?)\s*([^\]]*?)\s*\]\]?\s*(?:#.*)?$/.exec(line);
57
+ if (m === null)
58
+ return undefined;
59
+ return { array: m[1] === '[[', key: keySegments(m[2]) };
60
+ };
61
+ const assignment = (line) => {
62
+ const eq = /^\s*((?:"(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z0-9_.\s-])+?)\s*=\s*(.*)$/.exec(line);
63
+ if (eq === null)
64
+ return undefined;
65
+ const key = keySegments(eq[1]);
66
+ if (key === undefined)
67
+ return undefined;
68
+ const raw = eq[2];
69
+ const tail = (rest) => /^\s*(?:#.*)?$/.test(rest);
70
+ let m = /^"((?:[^"\\]|\\.)*)"(.*)$/.exec(raw);
71
+ if (m !== null && tail(m[2]))
72
+ return { key, value: unescapeBasic(m[1]) };
73
+ m = /^'([^']*)'(.*)$/.exec(raw);
74
+ if (m !== null && !raw.startsWith("'''") && tail(m[2]))
75
+ return { key, value: m[1] };
76
+ m = /^(true|false)(.*)$/.exec(raw);
77
+ if (m !== null && tail(m[2]))
78
+ return { key, value: m[1] === 'true' };
79
+ m = /^([+-]?\d+)(.*)$/.exec(raw);
80
+ if (m !== null && tail(m[2]))
81
+ return { key, value: Number(m[1]) };
82
+ return undefined;
83
+ };
84
+ const isEventKey = (key, length) => key !== undefined &&
85
+ key.length >= length &&
86
+ key[0] === 'hooks' &&
87
+ CODEX_HOOK_EVENTS.has(key[1] ?? '');
88
+ const splitHooks = (body, path) => {
89
+ const hooks = {};
90
+ const rest = [];
91
+ let group;
92
+ let handler;
93
+ let table = [];
94
+ const close = () => {
95
+ if (group === undefined)
96
+ return;
97
+ const lines = [...group.lines];
98
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '')
99
+ lines.pop();
100
+ Object.defineProperty(group.value, RAW, { value: lines.join('\n') });
101
+ (hooks[group.event] ??= []).push(group.value);
102
+ group = undefined;
103
+ handler = undefined;
104
+ };
105
+ const lines = body.split('\n');
106
+ for (const [i, line] of lines.entries()) {
107
+ if (line.includes('"""') || line.includes("'''")) {
108
+ throw new Error(`${path}:${i + 1}: has """ or ''', which opens a multi-line string; setup does not edit a ` +
109
+ 'profile file with one, even in a comment. Write that value on one line or move it out of ' +
110
+ 'this file, then re-run');
111
+ }
112
+ const h = header(line);
113
+ if (h !== undefined) {
114
+ if (h.array && isEventKey(h.key, 2) && h.key.length === 2) {
115
+ close();
116
+ group = { event: h.key[1], value: { hooks: [] }, lines: [line] };
117
+ continue;
118
+ }
119
+ const sameEvent = group !== undefined && isEventKey(h.key, 3) && h.key[1] === group.event;
120
+ if (sameEvent && h.array && h.key.length === 3 && h.key[2] === 'hooks') {
121
+ handler = {};
122
+ group.value.hooks.push(handler);
123
+ group.lines.push(line);
124
+ continue;
125
+ }
126
+ if (sameEvent && h.key[2] === 'hooks') {
127
+ handler = undefined;
128
+ group.lines.push(line);
129
+ continue;
130
+ }
131
+ close();
132
+ table = h.key ?? [];
133
+ rest.push(line);
134
+ continue;
135
+ }
136
+ if (group !== undefined) {
137
+ group.lines.push(line);
138
+ const a = assignment(line);
139
+ if (a === undefined || a.key.length !== 1)
140
+ continue;
141
+ const name = a.key[0];
142
+ if (handler !== undefined)
143
+ handler[name] = a.value;
144
+ else if (group.value.hooks.length === 0 &&
145
+ name === 'matcher' &&
146
+ typeof a.value === 'string') {
147
+ group.value.matcher = a.value;
148
+ }
149
+ continue;
150
+ }
151
+ const key = /^\s*[^#\s[]/.test(line) ? /^\s*([^=]+?)\s*=/.exec(line)?.[1] : undefined;
152
+ const full = key === undefined ? undefined : [...table, ...(keySegments(key) ?? [])];
153
+ if (full !== undefined &&
154
+ (full.join('.') === 'hooks' || (full[0] === 'hooks' && CODEX_HOOK_EVENTS.has(full[1] ?? '')))) {
155
+ throw new Error(`${path}:${i + 1}: holds Codex hooks in a form setup does not edit (${full.join('.')}); ` +
156
+ 'write them as [[hooks.<Event>]] tables or remove them, then re-run setup');
157
+ }
158
+ rest.push(line);
159
+ }
160
+ close();
161
+ return { hooks, rest: rest.join('\n') };
162
+ };
163
+ const renderValue = (v) => (typeof v === 'string' ? escapeBasic(v) : String(v));
164
+ const renderKey = (k) => (/^[A-Za-z0-9_-]+$/.test(k) ? k : escapeBasic(k));
165
+ const renderGroup = (event, group) => {
166
+ const lines = [`[[hooks.${event}]]`];
167
+ for (const [k, v] of Object.entries(group)) {
168
+ if (k === 'hooks')
169
+ continue;
170
+ if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {
171
+ lines.push(`${renderKey(k)} = ${renderValue(v)}`);
172
+ }
173
+ }
174
+ const handlers = Array.isArray(group.hooks) ? group.hooks : [];
175
+ for (const h of handlers) {
176
+ if (!isRecord(h))
177
+ continue;
178
+ lines.push('', `[[hooks.${event}.hooks]]`);
179
+ const keys = [
180
+ ...HANDLER_KEY_ORDER.filter((k) => k in h),
181
+ ...Object.keys(h).filter((k) => !HANDLER_KEY_ORDER.includes(k)),
182
+ ];
183
+ for (const k of keys) {
184
+ const v = h[k];
185
+ if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {
186
+ lines.push(`${renderKey(k)} = ${renderValue(v)}`);
187
+ }
188
+ }
189
+ }
190
+ return lines.join('\n');
191
+ };
192
+ const parse = (body, path) => {
193
+ const split = splitHooks(body, path);
194
+ const root = tomlOtelCodec.parse(split.rest, path);
195
+ if (Object.keys(split.hooks).length > 0)
196
+ root.hooks = split.hooks;
197
+ return root;
198
+ };
199
+ const withoutHooks = (doc) => {
200
+ if (!isRecord(doc))
201
+ throw new Error('expected a TOML table at the top level');
202
+ const { hooks: _hooks, ...rest } = doc;
203
+ return rest;
204
+ };
205
+ const serialize = (doc) => {
206
+ const rest = tomlOtelCodec.serialize(withoutHooks(doc));
207
+ const hooks = isRecord(doc) && isRecord(doc.hooks) ? doc.hooks : {};
208
+ const blocks = [];
209
+ for (const [event, groups] of Object.entries(hooks)) {
210
+ if (!Array.isArray(groups))
211
+ continue;
212
+ for (const g of groups) {
213
+ if (!isRecord(g))
214
+ continue;
215
+ const raw = g[RAW];
216
+ blocks.push(raw ?? renderGroup(event, g));
217
+ }
218
+ }
219
+ const hooksText = blocks.length > 0 ? blocks.join('\n\n') + '\n' : '';
220
+ if (rest.trim() === '')
221
+ return hooksText;
222
+ if (hooksText === '')
223
+ return rest;
224
+ return rest.replace(/\s+$/, '') + '\n\n' + hooksText;
225
+ };
226
+ const applyEnv = (doc, newEnv, managedKeys) => {
227
+ const next = tomlOtelCodec.applyEnv(withoutHooks(doc), newEnv, managedKeys);
228
+ if (isRecord(doc) && doc.hooks !== undefined)
229
+ next.hooks = doc.hooks;
230
+ return next;
231
+ };
232
+ export const tomlProfileCodec = {
233
+ format: 'toml',
234
+ parse,
235
+ serialize,
236
+ empty: tomlOtelCodec.empty,
237
+ readEnv: (doc) => tomlOtelCodec.readEnv(withoutHooks(doc)),
238
+ applyEnv,
239
+ };
@@ -116,26 +116,10 @@ const readText = (path) => {
116
116
  }
117
117
  };
118
118
  const isRecord = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
119
- export const readCodexTrust = (hooksPath, configPath) => {
120
- const body = readText(hooksPath);
121
- let doc;
122
- try {
123
- doc = body === undefined ? undefined : JSON.parse(body);
124
- }
125
- catch {
126
- return { state: 'no-hooks' };
127
- }
128
- if (!isRecord(doc) || !isRecord(doc.hooks))
129
- return { state: 'no-hooks' };
130
- const states = readHookStates(readText(configPath) ?? '');
131
- if (states === undefined) {
132
- return {
133
- state: 'unreadable',
134
- reason: `${configPath} records hook state in a form doctor does not read`,
135
- };
136
- }
137
- const hooks = [];
138
- for (const [event, groups] of Object.entries(doc.hooks)) {
119
+ export const hookTrustKey = (sourceFile, event, group, handler) => `${sourceFile}:${eventLabel(event)}:${group}:${handler}`;
120
+ const mainwaveHooks = (hooks, keySource) => {
121
+ const out = [];
122
+ for (const [event, groups] of Object.entries(hooks)) {
139
123
  if (!Array.isArray(groups))
140
124
  continue;
141
125
  for (const [gi, group] of groups.entries()) {
@@ -146,9 +130,7 @@ export const readCodexTrust = (hooksPath, configPath) => {
146
130
  continue;
147
131
  if (commandOwnership(handler.command) !== 'cli')
148
132
  continue;
149
- const key = `${hooksPath}:${eventLabel(event)}:${gi}:${hi}`;
150
- const state = states.get(key);
151
- const current = codexHookHash(event, typeof group.matcher === 'string' ? group.matcher : undefined, {
133
+ const hash = codexHookHash(event, typeof group.matcher === 'string' ? group.matcher : undefined, {
152
134
  type: 'command',
153
135
  command: handler.command,
154
136
  ...(typeof handler.timeout === 'number' ? { timeout: handler.timeout } : {}),
@@ -157,17 +139,126 @@ export const readCodexTrust = (hooksPath, configPath) => {
157
139
  ? { statusMessage: handler.statusMessage }
158
140
  : {}),
159
141
  });
160
- const trust = state?.trustedHash === undefined
161
- ? 'untrusted'
162
- : state.trustedHash !== current
163
- ? 'modified'
164
- : state.enabled === false
165
- ? 'disabled'
166
- : 'trusted';
167
- hooks.push({ key, event, trust });
142
+ out.push({ key: hookTrustKey(keySource, event, gi, hi), event, hash });
143
+ }
144
+ }
145
+ }
146
+ return out;
147
+ };
148
+ export const mainwaveHookKeys = (doc, keySource) => isRecord(doc) && isRecord(doc.hooks) ? mainwaveHooks(doc.hooks, keySource).map((h) => h.key) : [];
149
+ export const withoutHookStates = (toml, keys) => {
150
+ if (keys.size === 0)
151
+ return { text: toml, dropped: 0 };
152
+ const kept = [];
153
+ const dropped = new Set();
154
+ let path = [];
155
+ let skipping = false;
156
+ let pending = [];
157
+ for (const raw of toml.split('\n')) {
158
+ const line = raw.trim();
159
+ if (line.startsWith('[')) {
160
+ path = line.startsWith('[[') ? undefined : tablePath(line);
161
+ const skipNext = path?.length === 3 && keys.has(path[2]);
162
+ if (skipping && !skipNext) {
163
+ const lastBlank = kept.length === 0 || kept[kept.length - 1].trim() === '';
164
+ const first = lastBlank ? pending.findIndex((l) => l.trim() !== '') : 0;
165
+ if (first >= 0)
166
+ kept.push(...pending.slice(first));
168
167
  }
168
+ pending = [];
169
+ skipping = skipNext;
170
+ if (skipping)
171
+ dropped.add(path[2]);
172
+ else
173
+ kept.push(raw);
174
+ continue;
175
+ }
176
+ if (skipping) {
177
+ if (line === '' || line.startsWith('#'))
178
+ pending.push(raw);
179
+ else
180
+ pending = [];
181
+ continue;
169
182
  }
183
+ if (path !== undefined && path.length < 3 && line !== '' && !line.startsWith('#')) {
184
+ const lead = ['hooks', 'state'].slice(Math.min(path.length, 2));
185
+ const prefix = lead.map((part) => `${part}${DOT}`).join('');
186
+ const field = new RegExp(String.raw `^${prefix}${QUOTED_KEY}${DOT}(?:trusted_hash|enabled)\s*=`).exec(line);
187
+ if (field !== null && keys.has(quotedKey(field, 1))) {
188
+ dropped.add(quotedKey(field, 1));
189
+ continue;
190
+ }
191
+ }
192
+ kept.push(raw);
193
+ }
194
+ if (dropped.size === 0)
195
+ return { text: toml, dropped: 0 };
196
+ if (skipping) {
197
+ while (kept.length > 0 && kept[kept.length - 1].trim() === '')
198
+ kept.pop();
199
+ if (toml.endsWith('\n') && kept.length > 0)
200
+ kept.push('');
201
+ }
202
+ return { text: kept.join('\n'), dropped: dropped.size };
203
+ };
204
+ const mergedStates = (trustFiles) => {
205
+ const merged = new Map();
206
+ for (const file of trustFiles) {
207
+ const states = readHookStates(readText(file) ?? '');
208
+ if (states === undefined)
209
+ return { unreadable: file };
210
+ for (const [key, state] of states) {
211
+ const into = merged.get(key) ?? {};
212
+ if (state.trustedHash !== undefined)
213
+ into.trustedHash = state.trustedHash;
214
+ if (state.enabled !== undefined)
215
+ into.enabled = state.enabled;
216
+ merged.set(key, into);
217
+ }
218
+ }
219
+ return { states: merged };
220
+ };
221
+ export const approvedHookKeys = (trustFiles) => {
222
+ const merged = mergedStates(trustFiles);
223
+ if ('unreadable' in merged)
224
+ return undefined;
225
+ return new Set([...merged.states].filter(([, s]) => s.trustedHash !== undefined).map(([key]) => key));
226
+ };
227
+ export const readCodexTrust = (hooksPath, trustFiles, keySource = hooksPath, codec) => {
228
+ const body = readText(hooksPath);
229
+ let doc;
230
+ try {
231
+ doc =
232
+ body === undefined
233
+ ? undefined
234
+ : codec === undefined
235
+ ? JSON.parse(body)
236
+ : codec.parse(body, hooksPath);
237
+ }
238
+ catch {
239
+ return { state: 'no-hooks' };
240
+ }
241
+ if (!isRecord(doc) || !isRecord(doc.hooks))
242
+ return { state: 'no-hooks' };
243
+ const merged = mergedStates(trustFiles);
244
+ if ('unreadable' in merged) {
245
+ return {
246
+ state: 'unreadable',
247
+ reason: `${merged.unreadable} records hook state in a form doctor does not read`,
248
+ };
170
249
  }
250
+ const { states } = merged;
251
+ const hooks = mainwaveHooks(doc.hooks, keySource).map(({ key, event, hash }) => {
252
+ const state = states.get(key);
253
+ const trust = state?.trustedHash === undefined
254
+ ? 'untrusted'
255
+ : state.trustedHash !== hash
256
+ ? 'modified'
257
+ : state.enabled === false
258
+ ? 'disabled'
259
+ : 'trusted';
260
+ return { key, event, trust };
261
+ });
171
262
  return hooks.length === 0 ? { state: 'no-hooks' } : { state: 'read', hooks };
172
263
  };
173
264
  export const countTrust = (hooks) => {
@@ -1,6 +1,7 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { existsSync, readdirSync } from 'node:fs';
2
+ import { accessSync, constants as fsConstants, existsSync, readdirSync } from 'node:fs';
3
3
  import { platform as osPlatform } from 'node:os';
4
+ import { delimiter, isAbsolute, join } from 'node:path';
4
5
  export const hasPath = (path) => existsSync(path);
5
6
  export const hasBinary = (name) => {
6
7
  const finder = osPlatform() === 'win32' ? 'where' : 'which';
@@ -20,3 +21,21 @@ export const hasEntryPrefixed = (dir, prefix) => {
20
21
  return false;
21
22
  }
22
23
  };
24
+ export const trustedPath = (env = process.env) => (env.PATH ?? '')
25
+ .split(delimiter)
26
+ .filter((dir) => dir && isAbsolute(dir) && !/[\\/]node_modules[\\/]\.bin[\\/]?$/.test(dir))
27
+ .join(delimiter);
28
+ export const trustedBinary = (name, env = process.env) => {
29
+ for (const dir of trustedPath(env).split(delimiter)) {
30
+ if (!dir)
31
+ continue;
32
+ const candidate = join(dir, name);
33
+ try {
34
+ accessSync(candidate, fsConstants.X_OK);
35
+ return candidate;
36
+ }
37
+ catch {
38
+ }
39
+ }
40
+ return undefined;
41
+ };