@mainwave/cli 0.12.0 → 0.13.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
@@ -141,9 +141,13 @@ npx @mainwave/cli setup claude-code --opt-in none
141
141
  ```
142
142
 
143
143
  For Claude Code that still leaves every activity view working — tool names, tokens, cost, sessions
144
- and per-person activity are all metadata. **Codex is different:** it reports tool names, success and
145
- approvals only when tool logging is on, so `--opt-in none` leaves Codex's tool views empty. Keep
146
- `--opt-in tool-details` for Codex if you want those without sending prompt text or tool output.
144
+ and per-person activity are all metadata. **Codex is different:** its config has one content switch, the
145
+ prompt text (`otel.log_user_prompt`). It exports tool commands and results whatever `--opt-in` says,
146
+ so `--opt-in none` stops Codex's prompt text only. Codex caps each tool result at 2,048 bytes by
147
+ default (its `[otel.tool_result] max_bytes`). An earlier CLI version also wrote
148
+ `otel.log_system_prompt`, `log_tool_payloads`, `log_mcp_interactions` and `log_governance_events`,
149
+ which Codex ignores and reports at start as unrecognized settings; setup removes them, and `doctor`
150
+ reports them while they remain.
147
151
 
148
152
  Or pick exactly what you want: `--opt-in tool-details`, `--opt-in prompts,tool-details`,
149
153
  `--opt-in tool-details,repository`, and so on.
@@ -440,6 +444,42 @@ an earlier version copied into `~/.mainwave/hooks/` once nothing runs them. To d
440
444
  the plan snapshot included, re-run setup with `--no-markers` — the entries are removed cleanly. `doctor` checks that the entry is installed, that it names an installed release with every
441
445
  script, and that every Mainwave hook group is in the background and narrowed by its matcher.
442
446
 
447
+ Codex keeps its config in `$CODEX_HOME` when that is set, and in `~/.codex` otherwise. Setup,
448
+ `doctor` and the hooks follow the same rule, so run setup with the `CODEX_HOME` you run Codex
449
+ with, for example `CODEX_HOME=~/.codex-work npx @mainwave/cli setup codex`. Each Codex home gets
450
+ its own config and hooks. Setup says where it writes when `CODEX_HOME` is set, and warns when that
451
+ directory belongs to a launcher: Orca sets `CODEX_HOME` to its own copy of `~/.codex` in every
452
+ terminal it opens, so run setup from there with `env -u CODEX_HOME` to set up the Codex you start
453
+ yourself.
454
+
455
+ Codex gets the same session-start hook in its `hooks.json`, with `--host codex` added to the
456
+ command (on Windows, where Codex runs hooks through `cmd.exe`, an equivalent `cmd` command). It
457
+ installs the latest release's scripts and adds any hook that setup told you about and the file
458
+ lacks. It never edits or removes a hook already in the file, because Codex trusts each hook by a
459
+ hash of its definition and skips a changed hook until you approve it again in `/hooks`. Codex also
460
+ skips a hook it hasn't seen, so approve each new Mainwave hook there after setup. Hooks an earlier
461
+ CLI version wrote keep their 5-second timeout until you re-run setup; `doctor` reports them, and a
462
+ hooks file without the session-start hook, as warnings.
463
+
464
+ Codex also gets hooks that record when each turn starts and ends, so Developer Work can show Codex
465
+ turns and the time split between working, waiting for your approval and away: on a prompt, a stop
466
+ or interrupt, a permission request, a subagent starting or stopping, a tool call, a model request
467
+ and a session start. They send one span per turn, per approval wait and per subagent run, when it
468
+ ends: the session, turn and subagent ids, the subagent's type, the working directory, the name of the
469
+ tool waiting for your approval, and the start and end times. They never send your prompt, Codex's
470
+ reply, a tool's input or output, or the transcript path. They run in the background, except the
471
+ stop and interrupt hooks: Codex waits for those at the end of each turn while they send it (1.2 s at
472
+ most for the send, 1 s for an interrupt), because `codex exec` exits without waiting for a background hook. They keep a
473
+ small state file per session in `~/.mainwave/state/codex-turns/`, deleted after seven days.
474
+
475
+ Codex runs a hook only after you trust it. The first Codex session after setup shows "Hooks need
476
+ review": choose "Trust all", or open `/hooks` and trust each Mainwave hook, the session-start hook
477
+ included. Until then no Mainwave hook runs in Codex, and `codex exec` skips them unless it is run
478
+ with `--dangerously-bypass-hook-trust`. Codex checks each hook's definition against what you
479
+ approved, so it asks again after any change to a Mainwave hook, such as a setup run that adds a
480
+ route or a release that changes a command. Setup says all of this when it finishes, and `doctor`
481
+ lists the Mainwave hooks Codex is skipping, read from the trust records in Codex's `config.toml`.
482
+
443
483
  On Windows, the Claude Code hooks need Git for Windows. Claude Code runs hook commands through Git
444
484
  Bash, and through PowerShell when it finds none, where the entry's shell command can't run. Without
445
485
  Git Bash, setup installs no Claude Code hooks and says why, and `doctor` reports it as an error;
@@ -1,9 +1,50 @@
1
+ import { realpathSync } from 'node:fs';
1
2
  import { homedir } from 'node:os';
2
- import { join } from 'node:path';
3
+ import { join, resolve } from 'node:path';
3
4
  import { jsonEnvCodec } from '../core/codecs/json-env.js';
4
5
  import { hasBinary, hasPath } from '../core/detect.js';
5
6
  import { tomlOtelCodec } from '../core/codecs/toml-otel.js';
6
7
  import { UCID_SOURCE_EXPLICIT } from '../core/headers.js';
8
+ export const codexHome = (env = process.env) => {
9
+ const dir = env.CODEX_HOME;
10
+ if (dir === undefined || dir === '')
11
+ return join(homedir(), '.codex');
12
+ try {
13
+ return realpathSync(resolve(dir));
14
+ }
15
+ catch {
16
+ return resolve(dir);
17
+ }
18
+ };
19
+ const LAUNCHER_HOME_MARKERS = [
20
+ { file: '.orca-managed-home', launcher: 'Orca' },
21
+ ];
22
+ export const codexHomeIssues = (env = process.env) => {
23
+ if (env.CODEX_HOME === undefined || env.CODEX_HOME === '')
24
+ return [];
25
+ const dir = codexHome(env);
26
+ const managed = LAUNCHER_HOME_MARKERS.find((m) => hasPath(join(dir, m.file)));
27
+ if (managed === undefined) {
28
+ return [
29
+ hasPath(dir)
30
+ ? { level: 'info', message: `CODEX_HOME is set, so Codex config and hooks live in ${dir}.` }
31
+ : {
32
+ level: 'warn',
33
+ message: `CODEX_HOME is set to ${dir}, which doesn't exist. Codex refuses to start until it does; ` +
34
+ 'setup creates it. Check the path if you expected an existing Codex home.',
35
+ },
36
+ ];
37
+ }
38
+ return [
39
+ {
40
+ level: 'warn',
41
+ message: `CODEX_HOME is set to ${dir}, a Codex home that ${managed.launcher} manages (it holds ${managed.file}). ` +
42
+ `Codex started outside ${managed.launcher} reads ~/.codex instead, and ${managed.launcher} may overwrite them when it syncs that copy. ` +
43
+ 'To set up the Codex you start yourself, run setup again with CODEX_HOME unset (`env -u CODEX_HOME …`) ' +
44
+ 'or set to the home you start Codex with.',
45
+ },
46
+ ];
47
+ };
7
48
  const SOURCE_VALUE = 'coding_agent.codex_cli';
8
49
  const SIGNAL_BLOCKS = ['exporter', 'trace_exporter', 'metrics_exporter'];
9
50
  const SIGNAL_PATH = {
@@ -23,29 +64,24 @@ const protocolKey = (block) => `otel.${block}.otlp-http.protocol`;
23
64
  const headerKey = (block, name) => `otel.${block}.otlp-http.headers.${name}`;
24
65
  const MANAGED_ENV_KEYS = [
25
66
  'otel.log_user_prompt',
26
- 'otel.log_system_prompt',
27
- 'otel.log_tool_payloads',
28
- 'otel.log_mcp_interactions',
29
- 'otel.log_governance_events',
30
67
  ...SIGNAL_BLOCKS.flatMap((b) => [
31
68
  endpointKey(b),
32
69
  protocolKey(b),
33
70
  ...HEADER_NAMES.map((h) => headerKey(b, h)),
34
71
  ]),
35
72
  ];
73
+ const RETIRED_ENV_KEYS = [
74
+ 'otel.log_system_prompt',
75
+ 'otel.log_tool_payloads',
76
+ 'otel.log_mcp_interactions',
77
+ 'otel.log_governance_events',
78
+ ];
36
79
  const stripTrailingSlash = (url) => url.replace(/\/+$/, '');
37
80
  const buildEnv = ({ ucid, collectorUrl, apiKey, optIns, userEmail, }) => {
38
81
  const base = stripTrailingSlash(collectorUrl);
39
82
  const out = {};
40
- if (optIns.userPrompts) {
83
+ if (optIns.userPrompts)
41
84
  out['otel.log_user_prompt'] = 'true';
42
- out['otel.log_system_prompt'] = 'true';
43
- }
44
- if (optIns.toolDetails || optIns.toolContent) {
45
- out['otel.log_tool_payloads'] = 'true';
46
- out['otel.log_mcp_interactions'] = 'true';
47
- out['otel.log_governance_events'] = 'true';
48
- }
49
85
  for (const block of SIGNAL_BLOCKS) {
50
86
  out[endpointKey(block)] = `${base}${SIGNAL_PATH[block]}`;
51
87
  out[protocolKey(block)] = 'binary';
@@ -98,8 +134,8 @@ const parseEnv = (env) => {
98
134
  out.userEmail = userEmail;
99
135
  out.optIns = {
100
136
  userPrompts: env['otel.log_user_prompt'] === 'true',
101
- toolDetails: env['otel.log_tool_payloads'] === 'true',
102
- toolContent: env['otel.log_tool_payloads'] === 'true',
137
+ toolDetails: true,
138
+ toolContent: true,
103
139
  };
104
140
  return out;
105
141
  };
@@ -135,7 +171,7 @@ const collectFileChecks = (scans) => {
135
171
  return issues;
136
172
  };
137
173
  const collectChecks = (env) => {
138
- const issues = [];
174
+ const issues = [...codexHomeIssues()];
139
175
  if (!env[endpointKey('metrics_exporter')]) {
140
176
  issues.push({
141
177
  level: 'warn',
@@ -145,7 +181,7 @@ const collectChecks = (env) => {
145
181
  }
146
182
  issues.push({
147
183
  level: 'warn',
148
- message: 'Codex ships full tool stdout in `codex.tool_result.output` by default and exposes no opt-out flag. ' +
184
+ message: 'Codex exports tool output in `codex.tool_result.output`, capped at 2,048 bytes by default (`[otel.tool_result] max_bytes`), and has no switch to turn it off. ' +
149
185
  'If your workflow runs commands over sensitive files, scrub at the collector or avoid Codex for those flows.',
150
186
  });
151
187
  return issues;
@@ -160,7 +196,7 @@ const HIERARCHY = [
160
196
  {
161
197
  id: 'user',
162
198
  label: 'User (global)',
163
- path: join(homedir(), '.codex', 'config.toml'),
199
+ path: join(codexHome(), 'config.toml'),
164
200
  kind: 'file',
165
201
  },
166
202
  ];
@@ -168,20 +204,22 @@ export const codexCli = {
168
204
  name: 'codex',
169
205
  displayName: 'Codex CLI',
170
206
  runInstruction: 'codex',
171
- detect: () => hasPath(join(homedir(), '.codex')) || hasBinary('codex'),
207
+ detect: () => hasPath(codexHome()) || hasBinary('codex'),
172
208
  instructionSurface: {
173
209
  kind: 'instructions-file',
174
- global: join(homedir(), '.codex', 'AGENTS.md'),
210
+ global: join(codexHome(), 'AGENTS.md'),
175
211
  local: 'AGENTS.md',
176
212
  label: 'AGENTS.md',
177
213
  },
178
214
  paths: {
179
215
  local: join('.codex', 'config.toml'),
180
- global: join(homedir(), '.codex', 'config.toml'),
216
+ global: join(codexHome(), 'config.toml'),
181
217
  },
182
218
  injectsIdentity: true,
183
219
  codec: tomlOtelCodec,
184
220
  managedEnvKeys: MANAGED_ENV_KEYS,
221
+ retiredEnvKeys: RETIRED_ENV_KEYS,
222
+ alwaysOnOptIns: { toolDetails: true, toolContent: true },
185
223
  hierarchy: HIERARCHY,
186
224
  buildEnv,
187
225
  parseEnv,
@@ -189,9 +227,12 @@ export const codexCli = {
189
227
  collectFileChecks,
190
228
  normalizeForGenericChecks,
191
229
  markers: {
192
- disclosure: 'Sends Linear/Jira issue ids and GitHub PR / GitLab MR urls to the collector — never ticket bodies or diff content.',
230
+ disclosure: 'Sends Linear/Jira issue ids and GitHub PR / GitLab MR urls to the collector — never ticket bodies or diff content. ' +
231
+ 'It also sends, for each Codex turn, the session, turn and subagent ids, the working directory, the name of a tool ' +
232
+ 'call waiting for your approval, and when the turn, the wait and the subagent started and ended — ids and ' +
233
+ 'timestamps, never prompt or response text.',
193
234
  hooksFile: {
194
- path: join(homedir(), '.codex', 'hooks.json'),
235
+ path: join(codexHome(), 'hooks.json'),
195
236
  localPath: join('.codex', 'hooks.json'),
196
237
  codec: jsonEnvCodec,
197
238
  },
package/dist/commands.js CHANGED
@@ -163,17 +163,19 @@ export const COMMANDS = [
163
163
  },
164
164
  {
165
165
  name: 'install-hooks',
166
- usage: '[--quiet] [--redaction-packs <list>]',
166
+ usage: '[--quiet] [--host codex] [--redaction-packs <list>]',
167
167
  summary: [
168
168
  'install or refresh the Mainwave hook entry and the',
169
169
  "latest release's hook scripts, with no prompts or",
170
170
  "sign-in (run at session start by an org's managed",
171
171
  "settings, and by setup's own session-start hook).",
172
+ "--host codex: refresh Codex's hooks file instead of Claude",
173
+ "Code's settings (run by the session-start hook in it)",
172
174
  "--redaction-packs: the packs an org's managed settings",
173
175
  'apply to every Mainwave hook; recorded only from them',
174
176
  ],
175
177
  adapters: 'none',
176
- flags: [f('--quiet'), f('--redaction-packs')],
178
+ flags: [f('--quiet'), f('--host'), f('--redaction-packs')],
177
179
  },
178
180
  ];
179
181
  export const isCommand = (name) => COMMANDS.some((c) => c.name === name);
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { dirname, resolve } from 'node:path';
3
3
  import { adapters } from '../adapters/index.js';
4
+ import { countTrust, readCodexTrust } from './codex-trust.js';
4
5
  import { activeHierarchy, effectiveEnv } from './effective-settings.js';
5
6
  import { color, renderDiff } from './format.js';
6
7
  import { claudeHookShellMissing, GIT_BASH_FIX, GIT_BASH_MISSING_REASON } from './git-bash.js';
@@ -66,7 +67,10 @@ const decideTeamUcid = async (adapter, existing, stored) => {
66
67
  }
67
68
  return { status: 'kept', id: existing };
68
69
  };
69
- export const effectiveOptIns = (adapter, optIns, explicit) => explicit ? optIns : { ...optIns, ...adapter.defaultOptIns };
70
+ export const effectiveOptIns = (adapter, optIns, explicit) => ({
71
+ ...(explicit ? optIns : { ...optIns, ...adapter.defaultOptIns }),
72
+ ...adapter.alwaysOnOptIns,
73
+ });
70
74
  export const planAdapter = async (adapter, answers, context = {}) => {
71
75
  const { primary, additional } = writeTargets(adapter);
72
76
  const explicitUcid = adapter.carriesNoUcid ? undefined : answers.ucid;
@@ -94,7 +98,7 @@ export const planAdapter = async (adapter, answers, context = {}) => {
94
98
  const primaryUpdate = await prepareUpdate({
95
99
  path: primary,
96
100
  newEnv: adapter.buildEnv(input),
97
- managedKeys: adapter.managedEnvKeys,
101
+ managedKeys: [...adapter.managedEnvKeys, ...(adapter.retiredEnvKeys ?? [])],
98
102
  codec: adapter.codec,
99
103
  });
100
104
  const markersOn = adapter.markers ? answers.markers : null;
@@ -354,6 +358,29 @@ export const printMarkerCoexistenceNotes = async (adapter, targetPath, markersOn
354
358
  }
355
359
  }
356
360
  };
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 ' +
363
+ 'Mainwave hook, the session-start hook included. Codex asks again whenever a Mainwave hook changes, such as ' +
364
+ 'when a setup run adds a route or a release changes a command, so approve again after such a run; a run that ' +
365
+ "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. ' +
367
+ '`mainwave-cli doctor` reports the hooks Codex skips.';
368
+ if (reading?.state === 'read') {
369
+ const n = countTrust(reading.hooks);
370
+ if (n.trusted === n.total)
371
+ return `Codex already trusts the Mainwave hooks in ${hooksPath}.`;
372
+ const why = [
373
+ n.untrusted > 0 ? `${n.untrusted} not yet approved` : '',
374
+ n.modified > 0 ? `${n.modified} changed since you approved them` : '',
375
+ n.disabled > 0 ? `${n.disabled} turned off in /hooks` : '',
376
+ ].filter((p) => p !== '');
377
+ return `Codex skips ${n.total - n.trusted} of ${n.total} Mainwave hooks until you trust them (${why.join(', ')}). ${how}`;
378
+ }
379
+ if (reading?.state === 'unreadable') {
380
+ return `Codex skips a hook until you trust it, and setup can't tell which Mainwave hooks Codex trusts: ${reading.reason}. ${how}`;
381
+ }
382
+ return `Codex skips a hook until you trust it. ${how}`;
383
+ };
357
384
  export const printPostSetup = (plan) => {
358
385
  if (plan.hookShellMissing && plan.markersOn === true) {
359
386
  say('');
@@ -368,9 +395,21 @@ export const printPostSetup = (plan) => {
368
395
  }
369
396
  if (plan.hookEvents.includes('SessionStart')) {
370
397
  say('');
371
- say(color.dim(`${plan.adapter.displayName} also runs \`npx @mainwave/cli@latest install-hooks\` in the background when a session ` +
372
- 'starts, resumes or forks: it refreshes the hook scripts from the latest release and keeps the hooks above ' +
373
- 'current, on the same events only — a new kind of hook waits for your next setup run.'));
398
+ say(color.dim(plan.hookHost === 'codex'
399
+ ? `${plan.adapter.displayName} also runs \`npx @mainwave/cli@latest install-hooks --host codex\` in the background ` +
400
+ 'when a session starts, resumes or forks: it refreshes the hook scripts from the latest release and adds hooks ' +
401
+ 'a later release brings to the events above, never changing one you approved.'
402
+ : `${plan.adapter.displayName} also runs \`npx @mainwave/cli@latest install-hooks\` in the background when a session ` +
403
+ 'starts, resumes or forks: it refreshes the hook scripts from the latest release and keeps the hooks above ' +
404
+ 'current, on the same events only — a new kind of hook waits for your next setup run.'));
405
+ }
406
+ if (plan.hookHost === 'codex' && plan.markersOn === true && !plan.hookShellMissing) {
407
+ const hooksFile = plan.adapter.markers?.hooksFile;
408
+ const reading = hooksFile === undefined
409
+ ? undefined
410
+ : readCodexTrust(hooksFile.path, plan.adapter.paths.global);
411
+ say('');
412
+ say(color.dim(codexTrustNote(reading, hooksFile?.path)));
374
413
  }
375
414
  const snippet = plan.adapter.printPostSetupInstructions?.(plan.input);
376
415
  if (snippet) {
@@ -0,0 +1,178 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import { commandOwnership } from './markers.js';
4
+ const EVENTS_WITHOUT_MATCHER = new Set([
5
+ 'PreModelRequest',
6
+ 'PostModelRequest',
7
+ 'UserPromptSubmit',
8
+ 'Stop',
9
+ 'Interrupt',
10
+ ]);
11
+ const eventLabel = (event) => event.replace(/(?<!^)([A-Z])/g, '_$1').toLowerCase();
12
+ const sortedJson = (value) => {
13
+ if (Array.isArray(value))
14
+ return `[${value.map(sortedJson).join(',')}]`;
15
+ if (value !== null && typeof value === 'object') {
16
+ const entries = Object.entries(value)
17
+ .filter(([, v]) => v !== undefined)
18
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
19
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${sortedJson(v)}`).join(',')}}`;
20
+ }
21
+ return JSON.stringify(value);
22
+ };
23
+ export const codexHookHash = (event, matcher, handler) => {
24
+ const sessionEnd = event === 'SessionEnd' || event === 'Interrupt';
25
+ const timeout = sessionEnd
26
+ ? Math.min(Math.max(handler.timeout ?? 1, 1), 3)
27
+ : Math.max(handler.timeout ?? 600, 1);
28
+ const identity = {
29
+ event_name: eventLabel(event),
30
+ hooks: [
31
+ {
32
+ type: 'command',
33
+ command: handler.command,
34
+ timeout,
35
+ async: handler.async === true,
36
+ statusMessage: handler.statusMessage,
37
+ },
38
+ ],
39
+ matcher: EVENTS_WITHOUT_MATCHER.has(event) ? undefined : matcher,
40
+ };
41
+ return `sha256:${createHash('sha256').update(sortedJson(identity)).digest('hex')}`;
42
+ };
43
+ const unescapeBasic = (s) => s.replace(/\\(u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)/g, (_m, c) => {
44
+ if (c[0] === 'u' || c[0] === 'U')
45
+ return String.fromCodePoint(parseInt(c.slice(1), 16));
46
+ return { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', '"': '"', '\\': '\\' }[c] ?? c;
47
+ });
48
+ const QUOTED_KEY = String.raw `(?:"((?:[^"\\]|\\.)*)"|'([^']*)')`;
49
+ const DOT = String.raw `\s*\.\s*`;
50
+ const quotedKey = (m, at) => m[at] !== undefined ? unescapeBasic(m[at]) : m[at + 1];
51
+ const tablePath = (line) => {
52
+ const header = new RegExp(String.raw `^\[\s*hooks(?:${DOT}state(?:${DOT}${QUOTED_KEY})?)?\s*\]\s*(?:#.*)?$`).exec(line);
53
+ if (header === null)
54
+ return undefined;
55
+ if (header[1] !== undefined || header[2] !== undefined) {
56
+ return ['hooks', 'state', quotedKey(header, 1)];
57
+ }
58
+ return /state\s*\]/.test(line) ? ['hooks', 'state'] : ['hooks'];
59
+ };
60
+ export const readHookStates = (toml) => {
61
+ const states = new Map();
62
+ const stateOf = (key) => {
63
+ const found = states.get(key);
64
+ if (found !== undefined)
65
+ return found;
66
+ const created = {};
67
+ states.set(key, created);
68
+ return created;
69
+ };
70
+ let path = [];
71
+ for (const raw of toml.split(/\r?\n/)) {
72
+ const line = raw.trim();
73
+ if (line.startsWith('[')) {
74
+ path = line.startsWith('[[') ? undefined : tablePath(line);
75
+ if (path?.length === 3)
76
+ stateOf(path[2]);
77
+ continue;
78
+ }
79
+ if (path === undefined || line === '' || line.startsWith('#'))
80
+ continue;
81
+ const lead = ['hooks', 'state'].slice(Math.min(path.length, 2));
82
+ const prefix = lead.map((part) => `${part}${DOT}`).join('');
83
+ const keyPart = path.length === 3 ? '' : `${QUOTED_KEY}${DOT}`;
84
+ const field = new RegExp(String.raw `^${prefix}${keyPart}(trusted_hash|enabled)\s*=\s*(.*)$`).exec(line);
85
+ if (field !== null) {
86
+ const key = path.length === 3 ? path[2] : quotedKey(field, 1);
87
+ const name = path.length === 3 ? field[1] : field[3];
88
+ const value = path.length === 3 ? field[2] : field[4];
89
+ const state = stateOf(key);
90
+ if (name === 'trusted_hash') {
91
+ const hash = /^"([^"]*)"/.exec(value);
92
+ if (hash !== null)
93
+ state.trustedHash = hash[1];
94
+ }
95
+ else {
96
+ const enabled = /^(true|false)\b/.exec(value);
97
+ if (enabled !== null)
98
+ state.enabled = enabled[1] === 'true';
99
+ }
100
+ continue;
101
+ }
102
+ const along = [...lead, QUOTED_KEY].slice(0, path.length === 3 ? 0 : undefined);
103
+ const inline = along.map((_, i) => along.slice(0, i + 1).join(DOT));
104
+ if (inline.some((lhs) => new RegExp(String.raw `^${lhs}\s*=\s*\{`).test(line))) {
105
+ return undefined;
106
+ }
107
+ }
108
+ return states;
109
+ };
110
+ const readText = (path) => {
111
+ try {
112
+ return readFileSync(path, 'utf8');
113
+ }
114
+ catch {
115
+ return undefined;
116
+ }
117
+ };
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)) {
139
+ if (!Array.isArray(groups))
140
+ continue;
141
+ for (const [gi, group] of groups.entries()) {
142
+ if (!isRecord(group) || !Array.isArray(group.hooks))
143
+ continue;
144
+ for (const [hi, handler] of group.hooks.entries()) {
145
+ if (!isRecord(handler) || typeof handler.command !== 'string')
146
+ continue;
147
+ if (commandOwnership(handler.command) !== 'cli')
148
+ 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, {
152
+ type: 'command',
153
+ command: handler.command,
154
+ ...(typeof handler.timeout === 'number' ? { timeout: handler.timeout } : {}),
155
+ ...(handler.async === true ? { async: true } : {}),
156
+ ...(typeof handler.statusMessage === 'string'
157
+ ? { statusMessage: handler.statusMessage }
158
+ : {}),
159
+ });
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 });
168
+ }
169
+ }
170
+ }
171
+ return hooks.length === 0 ? { state: 'no-hooks' } : { state: 'read', hooks };
172
+ };
173
+ export const countTrust = (hooks) => {
174
+ const counts = { trusted: 0, untrusted: 0, modified: 0, disabled: 0, total: hooks.length };
175
+ for (const h of hooks)
176
+ counts[h.trust]++;
177
+ return counts;
178
+ };
@@ -2,6 +2,7 @@ import { spawnSync } from 'node:child_process';
2
2
  import { platform as osPlatform } from 'node:os';
3
3
  import { dirname, isAbsolute } from 'node:path';
4
4
  import { envFileCodec } from './codecs/env-file.js';
5
+ import { countTrust, readCodexTrust } from './codex-trust.js';
5
6
  import { activeHierarchy, computeEffective, effectiveFrom, flattenEffective, nativeIdentityReason, } from './effective-settings.js';
6
7
  import { ValidateError } from './errors.js';
7
8
  import { color, maskForDisplay } from './format.js';
@@ -420,6 +421,19 @@ const collectIssues = (effective, adapter, secondary = {}) => {
420
421
  });
421
422
  }
422
423
  }
424
+ const retiredKeys = adapter.retiredEnvKeys ?? [];
425
+ const userScans = effective.scans.filter((s) => s.layer.id === 'user');
426
+ const retired = userScans.flatMap((scan) => retiredKeys.filter((key) => key in scan.env).map((key) => ({ key, path: scan.path })));
427
+ if (retired.length > 0) {
428
+ const many = retired.length > 1;
429
+ issues.push({
430
+ level: 'warn',
431
+ message: `${retired.map((e) => e.key).join(', ')} ${many ? 'are' : 'is'} in ` +
432
+ `${[...new Set(retired.map((e) => e.path))].join(', ')}, but ${adapter.displayName} ` +
433
+ `ignores ${many ? 'them' : 'it'} and reports them as unrecognized settings at start. ` +
434
+ `Re-run \`mainwave-cli setup ${adapter.name}\` to remove ${many ? 'them' : 'it'}.`,
435
+ });
436
+ }
423
437
  if (adapter.collectChecks) {
424
438
  issues.push(...adapter.collectChecks(flattenEffective(effective)));
425
439
  }
@@ -531,12 +545,54 @@ const markerLayers = async (adapter) => {
531
545
  ];
532
546
  };
533
547
  const markerIssuesFor = async (adapter, effective, redaction) => adapter.markers
534
- ? collectMarkerIssues(await scanForMarkers(await markerLayers(adapter)), VERSION, markerMatchers(adapter, await readPackagedMatchers()), await skippedMarkerScans(effective), await hookChoices(adapter), adapter.markers.runtimeTool ?? DEFAULT_MARKER_TOOL, {
535
- managedDir: managedHooksDir(),
536
- hookShellMissing: await hookShellMissingFor(adapter, () => flattenEffective(effective)),
537
- redaction: redaction.state === 'off' ? 'off' : hasRulesFile(redaction) ? 'file' : 'default',
538
- })
548
+ ? [
549
+ ...(await collectMarkerIssues(await scanForMarkers(await markerLayers(adapter)), VERSION, markerMatchers(adapter, await readPackagedMatchers()), await skippedMarkerScans(effective), await hookChoices(adapter), adapter.markers.runtimeTool ?? DEFAULT_MARKER_TOOL, {
550
+ managedDir: managedHooksDir(),
551
+ hookShellMissing: await hookShellMissingFor(adapter, () => flattenEffective(effective)),
552
+ redaction: redaction.state === 'off' ? 'off' : hasRulesFile(redaction) ? 'file' : 'default',
553
+ })),
554
+ ...codexTrustIssues(adapter),
555
+ ]
539
556
  : [];
557
+ const codexTrustIssues = (adapter) => {
558
+ const hooksFile = adapter.markers?.hooksFile;
559
+ if (hooksFile === undefined || adapter.markers?.runtimeTool !== 'codex')
560
+ return [];
561
+ const reading = readCodexTrust(hooksFile.path, adapter.paths.global);
562
+ if (reading.state === 'no-hooks')
563
+ return [];
564
+ if (reading.state === 'unreadable') {
565
+ return [
566
+ {
567
+ level: 'info',
568
+ message: `Can't tell whether Codex trusts the Mainwave hooks: ${reading.reason}. Open /hooks in Codex to check.`,
569
+ },
570
+ ];
571
+ }
572
+ const n = countTrust(reading.hooks);
573
+ if (n.trusted === n.total) {
574
+ return [
575
+ {
576
+ level: 'info',
577
+ message: `Codex trusts all ${n.total} Mainwave hooks in ${hooksFile.path}.`,
578
+ },
579
+ ];
580
+ }
581
+ const parts = [
582
+ n.untrusted > 0 ? `${n.untrusted} with no approval on record` : '',
583
+ n.modified > 0 ? `${n.modified} whose approval doesn't match the hook as it is now` : '',
584
+ n.disabled > 0 ? `${n.disabled} turned off in /hooks` : '',
585
+ ].filter((p) => p !== '');
586
+ return [
587
+ {
588
+ level: 'warn',
589
+ message: `Codex skips ${n.total - n.trusted} of ${n.total} Mainwave hooks in ${hooksFile.path} (${parts.join(', ')}), ` +
590
+ 'so they send nothing. Start Codex and choose "Trust all" at the "Hooks need review" prompt, or open /hooks and trust each one. ' +
591
+ 'Every change to a Mainwave hook needs a new approval, such as setup adding a route or a release changing a command. ' +
592
+ '`codex exec` skips them too unless it runs with --dangerously-bypass-hook-trust.',
593
+ },
594
+ ];
595
+ };
540
596
  const skippedMarkerScans = async (effective) => {
541
597
  const out = [];
542
598
  for (const { layer, reason } of effective.skipped ?? []) {