@memnexus-ai/mx-agent-cli 0.1.246 → 0.1.247

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.
Files changed (68) hide show
  1. package/dist/__tests__/codex-agent-gate.test.d.ts +2 -0
  2. package/dist/__tests__/codex-agent-gate.test.d.ts.map +1 -0
  3. package/dist/__tests__/codex-agent-gate.test.js +182 -0
  4. package/dist/__tests__/codex-agent-gate.test.js.map +1 -0
  5. package/dist/__tests__/runtime-claude-adapter.test.d.ts +2 -0
  6. package/dist/__tests__/runtime-claude-adapter.test.d.ts.map +1 -0
  7. package/dist/__tests__/runtime-claude-adapter.test.js +70 -0
  8. package/dist/__tests__/runtime-claude-adapter.test.js.map +1 -0
  9. package/dist/__tests__/runtime-codex-adapter.test.d.ts +2 -0
  10. package/dist/__tests__/runtime-codex-adapter.test.d.ts.map +1 -0
  11. package/dist/__tests__/runtime-codex-adapter.test.js +475 -0
  12. package/dist/__tests__/runtime-codex-adapter.test.js.map +1 -0
  13. package/dist/__tests__/runtime-codex-config.test.d.ts +2 -0
  14. package/dist/__tests__/runtime-codex-config.test.d.ts.map +1 -0
  15. package/dist/__tests__/runtime-codex-config.test.js +523 -0
  16. package/dist/__tests__/runtime-codex-config.test.js.map +1 -0
  17. package/dist/__tests__/runtime-codex-version-pin.test.d.ts +2 -0
  18. package/dist/__tests__/runtime-codex-version-pin.test.d.ts.map +1 -0
  19. package/dist/__tests__/runtime-codex-version-pin.test.js +69 -0
  20. package/dist/__tests__/runtime-codex-version-pin.test.js.map +1 -0
  21. package/dist/__tests__/runtime-resolve.test.d.ts +2 -0
  22. package/dist/__tests__/runtime-resolve.test.d.ts.map +1 -0
  23. package/dist/__tests__/runtime-resolve.test.js +172 -0
  24. package/dist/__tests__/runtime-resolve.test.js.map +1 -0
  25. package/dist/__tests__/start-rebase-never-ran.test.d.ts +25 -0
  26. package/dist/__tests__/start-rebase-never-ran.test.d.ts.map +1 -0
  27. package/dist/__tests__/start-rebase-never-ran.test.js +227 -0
  28. package/dist/__tests__/start-rebase-never-ran.test.js.map +1 -0
  29. package/dist/__tests__/start-runtime-wiring.test.d.ts +31 -0
  30. package/dist/__tests__/start-runtime-wiring.test.d.ts.map +1 -0
  31. package/dist/__tests__/start-runtime-wiring.test.js +498 -0
  32. package/dist/__tests__/start-runtime-wiring.test.js.map +1 -0
  33. package/dist/commands/codex-agent-gate.d.ts +23 -0
  34. package/dist/commands/codex-agent-gate.d.ts.map +1 -0
  35. package/dist/commands/codex-agent-gate.js +139 -0
  36. package/dist/commands/codex-agent-gate.js.map +1 -0
  37. package/dist/commands/start.d.ts +21 -0
  38. package/dist/commands/start.d.ts.map +1 -1
  39. package/dist/commands/start.js +190 -25
  40. package/dist/commands/start.js.map +1 -1
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +23 -1
  43. package/dist/index.js.map +1 -1
  44. package/dist/lib/claude.d.ts +72 -10
  45. package/dist/lib/claude.d.ts.map +1 -1
  46. package/dist/lib/claude.js +71 -32
  47. package/dist/lib/claude.js.map +1 -1
  48. package/dist/lib/runtime/claude-adapter.d.ts +16 -0
  49. package/dist/lib/runtime/claude-adapter.d.ts.map +1 -0
  50. package/dist/lib/runtime/claude-adapter.js +43 -0
  51. package/dist/lib/runtime/claude-adapter.js.map +1 -0
  52. package/dist/lib/runtime/codex-adapter.d.ts +90 -0
  53. package/dist/lib/runtime/codex-adapter.d.ts.map +1 -0
  54. package/dist/lib/runtime/codex-adapter.js +357 -0
  55. package/dist/lib/runtime/codex-adapter.js.map +1 -0
  56. package/dist/lib/runtime/codex-config.d.ts +254 -0
  57. package/dist/lib/runtime/codex-config.d.ts.map +1 -0
  58. package/dist/lib/runtime/codex-config.js +620 -0
  59. package/dist/lib/runtime/codex-config.js.map +1 -0
  60. package/dist/lib/runtime/resolve.d.ts +46 -0
  61. package/dist/lib/runtime/resolve.d.ts.map +1 -0
  62. package/dist/lib/runtime/resolve.js +113 -0
  63. package/dist/lib/runtime/resolve.js.map +1 -0
  64. package/dist/lib/runtime/types.d.ts +81 -0
  65. package/dist/lib/runtime/types.d.ts.map +1 -0
  66. package/dist/lib/runtime/types.js +39 -0
  67. package/dist/lib/runtime/types.js.map +1 -0
  68. package/package.json +1 -1
@@ -0,0 +1,620 @@
1
+ /**
2
+ * Codex configuration generators (#4227 Phase 1, tasks 1.5, 1.10, 1.11).
3
+ *
4
+ * Produces, from the same sources the Claude path already uses:
5
+ * `.codex/config.toml` — MemNexus MCP server + CLAUDE.md instruction fallback (FR-7)
6
+ * `.codex/hooks.json` — the two containment guards, Bash-matched (FR-9, task 1.10)
7
+ * `AGENTS.override.md` — Codex's CLAUDE.local.md equivalent (FR-7, FR-16)
8
+ * plus the instruction-chain byte measurement FR-5 warns on.
9
+ *
10
+ * ────────────────────────────────────────────────────────────────────────────
11
+ * EMPIRICAL BASIS (codex-cli 0.145.0, this machine, 2026-07-30). Every shape
12
+ * below was probed, not inferred from documentation:
13
+ *
14
+ * 1. `.codex/hooks.json` is read from the project directory. Its top level
15
+ * accepts `description` and `hooks` ONLY; `hooks` maps a PascalCase event name
16
+ * (`PreToolUse`, `PostToolUse`, `PermissionRequest`, `PreCompact`,
17
+ * `PostCompact`, `SessionStart`, `SessionEnd`, `SubagentStart`,
18
+ * `SubagentStop`) to an array of `{ matcher?, hooks: [{ type, command }] }`
19
+ * groups. A wrong top-level key produced
20
+ * `failed to parse hooks config …: unknown field 'PreToolUse', expected
21
+ * 'description' or 'hooks'` as an error item in the `codex exec --json`
22
+ * stream — and the session then RAN ON with hooks inert. Parse failure is
23
+ * fail-open, which is why FR-9 requires a live paired proof and forbids
24
+ * treating config inspection as evidence.
25
+ *
26
+ * 2. The PreToolUse payload Codex delivers is Claude-Code-compatible:
27
+ * `{session_id, turn_id, transcript_path, cwd, hook_event_name, model,
28
+ * permission_mode, tool_name: "Bash", tool_input: {command}, tool_use_id}`.
29
+ * `tool_name` is literally `Bash`, so the existing `.claude/hooks/*.sh`
30
+ * guards parse it unmodified and `matcher: "Bash"` is the correct matcher.
31
+ *
32
+ * 3. Exit 2 + stderr from the hook BLOCKS the command
33
+ * (`Command blocked by PreToolUse hook: …`) while a permitted command in the
34
+ * same session succeeds — the same allow/block contract the guards already
35
+ * implement for Claude.
36
+ *
37
+ * 4. HOOKS DO NOT RUN WITHOUT PERSISTED HOOK TRUST. With a valid hooks.json and
38
+ * no trust record, the guards were silently inert in three separate runs — no
39
+ * warning, no error, no stream event. Trust is either persisted in the Codex
40
+ * config (`hooks.state."<key>".trusted_hash` + `enabled`) or bypassed per
41
+ * invocation with `--dangerously-bypass-hook-trust`. Project-local hooks
42
+ * additionally require the project to be trusted
43
+ * (`[projects."<path>"] trust_level`), or "project-local config, hooks, and
44
+ * exec policies are disabled … until the project is trusted".
45
+ * `codexHookTrustPreconditions()` below reports this state; choosing WHICH
46
+ * mechanism we use is a security decision left to gate G-7, not guessed here.
47
+ *
48
+ * 5. EXACTLY ONE PROJECT DOC IS READ, AND `AGENTS.override.md` REPLACES
49
+ * `AGENTS.md` RATHER THAN ADDING TO IT (probed 2026-07-30 via
50
+ * `codex debug prompt-input`, which renders the model-visible prompt with no
51
+ * model call). With both files present, only the override's content appeared in
52
+ * the prompt at caps of 200, 600, 1000 and 32768 bytes; with the override
53
+ * removed, AGENTS.md appeared. A parent-directory AGENTS.md was likewise not
54
+ * appended when running from a subdirectory.
55
+ *
56
+ * This CORRECTS the PRD's instruction-file model, which called
57
+ * `AGENTS.override.md` the `CLAUDE.local.md` equivalent. On Claude those two
58
+ * files are ADDITIVE — both are read. On Codex the override is a REPLACEMENT, so
59
+ * writing only the local-override content there would have left a Codex session
60
+ * reading the isolation context and behavioral markers while never seeing the
61
+ * canonical instructions at all. `buildAgentsOverride` therefore emits the
62
+ * canonical AGENTS.md content followed by the local override.
63
+ *
64
+ * Consequence for FR-5: the 32 KiB `project_doc_max_bytes` cap applies to that
65
+ * ONE file, and it truncates silently (a 433-byte file was cut at a 200-byte
66
+ * cap). `measureInstructionChain` measures the file Codex will actually read
67
+ * rather than summing files it will not.
68
+ * ────────────────────────────────────────────────────────────────────────────
69
+ */
70
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'fs';
71
+ import { dirname, join } from 'path';
72
+ import { buildClaudeLocalContent, } from '../claude.js';
73
+ /**
74
+ * Model the CodexAdapter selects (PRD Open Question 2, Option A — one known-good
75
+ * model for Phase 1; a per-worktree/profile setting is Phase 3 work).
76
+ */
77
+ export const CODEX_DEFAULT_MODEL = 'gpt-5.5';
78
+ /**
79
+ * Codex CLI version whose behaviour was actually probed for this adapter: hooks
80
+ * file schema, hook payload shape, hook trust requirement, stdin behaviour.
81
+ *
82
+ * This is NOT "the version we happened to have installed". Same discipline as
83
+ * `REVIEWED_CODEX_VERSION` in dev-tools/scripts/codex-review.sh: bumping it
84
+ * without re-running the probes is precisely how the 0.142.4 → 0.145.0 sandbox
85
+ * reimplementation silently removed containment the wrapper relied on.
86
+ */
87
+ export const VERIFIED_CODEX_VERSION = '0.145.0';
88
+ /** Codex's default `project_doc_max_bytes`. FR-5's budget. */
89
+ export const PROJECT_DOC_MAX_BYTES = 32 * 1024;
90
+ /** Codex's local instruction-override file — the `CLAUDE.local.md` equivalent. */
91
+ export const AGENTS_OVERRIDE_FILENAME = 'AGENTS.override.md';
92
+ export const CODEX_DIR = '.codex';
93
+ export const CODEX_CONFIG_FILENAME = join(CODEX_DIR, 'config.toml');
94
+ export const CODEX_HOOKS_FILENAME = join(CODEX_DIR, 'hooks.json');
95
+ /**
96
+ * The two containment guards Phase 1 must port AND prove (task 1.10, gate G-7).
97
+ *
98
+ * Scope is deliberately these two and no more. They are the guards whose absence
99
+ * removes an agent's ONLY containment (git-expert → git-mutation-guard;
100
+ * memory-creator/dogfood-auditor → named-memory-write-guard), which is why rev 3
101
+ * moved them out of Phase 2. The remaining category-(a) hooks (worktree-guard,
102
+ * mx-guard-hook, ci-validate-hook, workflow-dispatch-guard,
103
+ * deploy-verification-reminder) are Phase 2 task 2.1 and extend this generator.
104
+ */
105
+ export const PHASE1_PORTED_GUARDS = [
106
+ 'git-mutation-guard.sh',
107
+ 'named-memory-write-guard.sh',
108
+ ];
109
+ /** MemNexus MCP server invocation. Matches `.mcp.json`'s `memnexus` entry. */
110
+ const MEMNEXUS_MCP_COMMAND = 'mx';
111
+ const MEMNEXUS_MCP_ARGS = ['mcp', 'serve'];
112
+ /**
113
+ * Read the MemNexus MCP server definition from the project's `.mcp.json` so the
114
+ * two runtimes are configured from ONE source (design principle 2). Falls back to
115
+ * the known-good invocation when `.mcp.json` is absent or unparseable — a Codex
116
+ * session with no memory server is worse than one configured from the default.
117
+ */
118
+ export function resolveMemnexusMcpServer(projectRoot) {
119
+ const fallback = {
120
+ name: 'memnexus',
121
+ command: MEMNEXUS_MCP_COMMAND,
122
+ args: [...MEMNEXUS_MCP_ARGS],
123
+ };
124
+ try {
125
+ const raw = readFileSync(join(projectRoot, '.mcp.json'), 'utf-8');
126
+ const parsed = JSON.parse(raw);
127
+ const entry = parsed.mcpServers?.memnexus;
128
+ if (!entry || typeof entry.command !== 'string')
129
+ return fallback;
130
+ const args = Array.isArray(entry.args) ? entry.args.filter((a) => typeof a === 'string') : [];
131
+ return { name: 'memnexus', command: entry.command, args };
132
+ }
133
+ catch {
134
+ return fallback;
135
+ }
136
+ }
137
+ /**
138
+ * TOML basic-string literal (security review S5).
139
+ *
140
+ * A basic string may not contain a raw newline, carriage return, tab or any other
141
+ * control character — TOML rejects the document, and Codex's config load then fails
142
+ * in a way that takes the MCP server and every setting below it with it. Escaping the
143
+ * quote and backslash alone was not enough: a newline smuggled in through
144
+ * `.mcp.json`'s `command` or `args` would emit a broken file. All C0 controls plus
145
+ * DEL are escaped using TOML's own escape sequences.
146
+ */
147
+ export function tomlString(value) {
148
+ let out = '';
149
+ for (const ch of value) {
150
+ const code = ch.codePointAt(0) ?? 0;
151
+ if (ch === '\\')
152
+ out += '\\\\';
153
+ else if (ch === '"')
154
+ out += '\\"';
155
+ else if (ch === '\n')
156
+ out += '\\n';
157
+ else if (ch === '\r')
158
+ out += '\\r';
159
+ else if (ch === '\t')
160
+ out += '\\t';
161
+ else if (ch === '\b')
162
+ out += '\\b';
163
+ else if (ch === '\f')
164
+ out += '\\f';
165
+ else if (code < 0x20 || code === 0x7f)
166
+ out += `\\u${code.toString(16).padStart(4, '0')}`;
167
+ else
168
+ out += ch;
169
+ }
170
+ return `"${out}"`;
171
+ }
172
+ /**
173
+ * Sandbox mode the adapter declares (security review MF3a).
174
+ *
175
+ * `workspace-write` confines model-driven writes to the worktree — the boundary
176
+ * R-5's clearance re-established and the one R-2's mitigation leans on while the
177
+ * file-write hook gap (#16732) is open. Declaring it explicitly matters because the
178
+ * previous generator declared NO sandbox mode at all: the session inherited whatever
179
+ * the operator's `~/.codex/config.toml` happened to say, which on this machine is a
180
+ * `trust_level = "trusted"` project entry. "No danger flag is passed" is not the same
181
+ * property as "a boundary is declared", and only the second one is checkable.
182
+ */
183
+ export const CODEX_SANDBOX_MODE = 'workspace-write';
184
+ /**
185
+ * Approval policy the adapter declares (security review MF3a).
186
+ *
187
+ * `never` means Codex does not stop to ask a human. That is not a relaxation here —
188
+ * it is the only coherent setting for `codex exec`, which is non-interactive: an
189
+ * approval prompt in a session with no human at the terminal is an indefinite hang,
190
+ * not a control. The boundary is therefore the sandbox above plus the ported guard
191
+ * hooks, and the launch banner says so. `untrusted` or `on-request` would convert
192
+ * every escalation into the 7m16s-style stall FR-6 exists to prevent.
193
+ */
194
+ export const CODEX_APPROVAL_POLICY = 'never';
195
+ /**
196
+ * Generate `.codex/config.toml` (FR-7, MF3a).
197
+ *
198
+ * `project_doc_fallback_filenames = ["CLAUDE.md"]` is the transitional bridge for
199
+ * a worktree that has not yet regenerated its AGENTS.md — belt-and-braces during
200
+ * the Phase 0 migration, per the PRD's instruction-file model.
201
+ *
202
+ * DELIBERATELY NOT SET: `sandbox_workspace_write.network_access`. Denying network
203
+ * would cut the `mx` CLI off from core-api, so a Codex session could not write the
204
+ * memories the dogfooding standard requires, and MemNexus reaches the model over MCP
205
+ * in a separate process regardless. Narrowing egress is a Phase 2 question that needs
206
+ * its own design, not a flag flipped in passing.
207
+ */
208
+ export function buildCodexConfigToml(opts) {
209
+ const mcp = resolveMemnexusMcpServer(opts.projectRoot);
210
+ const args = mcp.args.map(tomlString).join(', ');
211
+ return [
212
+ '# GENERATED by mx-agent start --runtime codex (#4227). Do not hand-edit —',
213
+ '# regenerated every session from mx-agent-system/cli/src/lib/runtime/codex-config.ts.',
214
+ `model = ${tomlString(opts.model ?? CODEX_DEFAULT_MODEL)}`,
215
+ '',
216
+ '# Write boundary. Declared explicitly rather than inherited from the operator\'s',
217
+ '# ~/.codex/config.toml, whose project trust_level would otherwise decide it.',
218
+ `sandbox_mode = ${tomlString(CODEX_SANDBOX_MODE)}`,
219
+ '',
220
+ '# Instruction budget. Declared for the same reason as sandbox_mode above: an',
221
+ '# inherited default is not a boundary this code can check. FR-5 measures the',
222
+ '# instruction file against THIS number, so the value measured and the value in',
223
+ '# effect are the same constant (PROJECT_DOC_MAX_BYTES).',
224
+ `project_doc_max_bytes = ${PROJECT_DOC_MAX_BYTES}`,
225
+ '',
226
+ '# Non-interactive session: an approval prompt nobody can answer is a hang, not a',
227
+ '# control. The boundary is sandbox_mode above plus the ported guard hooks.',
228
+ `approval_policy = ${tomlString(CODEX_APPROVAL_POLICY)}`,
229
+ '',
230
+ '# Instruction files: AGENTS.md is canonical (Phase 0). CLAUDE.md is accepted as a',
231
+ '# fallback so a worktree that has not regenerated yet still gets instructions.',
232
+ '# NOTE: AGENTS.override.md, when present, REPLACES AGENTS.md (probed on 0.145.0),',
233
+ '# which is why the generator folds the canonical content into that file.',
234
+ 'project_doc_fallback_filenames = ["CLAUDE.md"]',
235
+ '',
236
+ `[mcp_servers.${mcp.name}]`,
237
+ `command = ${tomlString(mcp.command)}`,
238
+ `args = [${args}]`,
239
+ '',
240
+ ].join('\n');
241
+ }
242
+ /**
243
+ * Hook-script filenames are embedded in a single-quoted shell command, so they are
244
+ * constrained to a conservative character class. The Phase 1 set is a hard-coded
245
+ * constant, but `buildCodexHooksJson` accepts caller-supplied entries and a future
246
+ * caller must not be able to smuggle a quote or a shell metacharacter through
247
+ * (security review S4).
248
+ */
249
+ const SAFE_SCRIPT_NAME = /^[A-Za-z0-9._-]+\.sh$/;
250
+ /** The Phase 1 hook set: the two containment guards, PreToolUse, Bash-matched. */
251
+ export function phase1HookEntries() {
252
+ return PHASE1_PORTED_GUARDS.map((script) => ({
253
+ script,
254
+ event: 'PreToolUse',
255
+ matcher: 'Bash',
256
+ }));
257
+ }
258
+ /** Command the SubagentStart gate hook runs. See src/commands/codex-agent-gate.ts. */
259
+ export const CODEX_AGENT_GATE_COMMAND = 'mx-agent internal-codex-agent-gate';
260
+ /**
261
+ * Wrapper command for one ported guard.
262
+ *
263
+ * NO PATH INTERPOLATION (security review S4). The previous version embedded the
264
+ * worktree path inside a single-quoted shell string twice, so a worktree directory
265
+ * containing an apostrophe — `/workspaces/harry's-repo` — closed the quote and the
266
+ * remainder of the path was executed as shell words. Worktree names are derived from
267
+ * team slugs today, but the path comes from the filesystem, not from a validated
268
+ * allowlist, and "no team will ever have an apostrophe in its checkout path" is not a
269
+ * property this code can assert.
270
+ *
271
+ * The command now reads `CLAUDE_PROJECT_DIR` from the environment, which
272
+ * `CodexAdapter.launch` sets to the worktree path. The only interpolated value is the
273
+ * script filename, constrained by SAFE_SCRIPT_NAME.
274
+ *
275
+ * Fail-OPEN when the script is absent (`|| exit 0`) mirrors the wrapper
276
+ * `.claude/settings.json` uses for the same script: the Codex port reproduces the
277
+ * Claude semantics rather than inventing a different failure model on a security
278
+ * path. `deployCodexConfig` warns by name for each guard script that is missing, so
279
+ * the silent case is at least announced (security review S9).
280
+ */
281
+ export function codexHookCommand(script) {
282
+ if (!SAFE_SCRIPT_NAME.test(script)) {
283
+ throw new Error(`refusing to generate a Codex hook for an unsafe script name: ${script}`);
284
+ }
285
+ return (`bash -c 'H="$CLAUDE_PROJECT_DIR/.claude/hooks/${script}"; ` +
286
+ `[ -f "$H" ] && exec bash "$H" || exit 0'`);
287
+ }
288
+ /**
289
+ * Generate `.codex/hooks.json` (FR-9, task 1.10).
290
+ *
291
+ * Shape verified on codex-cli 0.145.0 — see finding 1 in the file header.
292
+ */
293
+ export function buildCodexHooksJson(opts) {
294
+ const entries = opts.entries ?? phase1HookEntries();
295
+ const hooks = {};
296
+ for (const entry of entries) {
297
+ const group = (hooks[entry.event] ??= []);
298
+ group.push({
299
+ matcher: entry.matcher,
300
+ hooks: [{ type: 'command', command: codexHookCommand(entry.script) }],
301
+ });
302
+ }
303
+ // ── SubagentStart: the FR-14b / FR-15 eligibility gate (security review MF2) ──
304
+ // Without this entry, checkCodexAgentEligibility has no runtime call site and the
305
+ // review-gate exclusion and the per-agent allowlist are documentation. No matcher:
306
+ // the gate must see every subagent spawn, then decide.
307
+ //
308
+ // The proven-guard list is passed on the command line by THIS generator, so an
309
+ // empty list — the pre-G-7 state — means every hook-gated agent is refused. The
310
+ // generated file is consequently the trust anchor for that decision, which is why
311
+ // the G-7 proof must include the tamper check described below.
312
+ // Leading `-` is rejected as well as metacharacters: `--proven-guards` itself
313
+ // matches an identifier pattern, so a value that looks like a flag must not be
314
+ // passed through as a guard name.
315
+ const guardArgs = (opts.provenGuards ?? []).filter((g) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(g));
316
+ hooks.SubagentStart = [
317
+ {
318
+ hooks: [
319
+ {
320
+ type: 'command',
321
+ command: guardArgs.length
322
+ ? `${CODEX_AGENT_GATE_COMMAND} --proven-guards ${guardArgs.join(',')}`
323
+ : CODEX_AGENT_GATE_COMMAND,
324
+ },
325
+ ],
326
+ },
327
+ ];
328
+ const doc = {
329
+ description: 'GENERATED by mx-agent start --runtime codex (#4227 task 1.10). Ported Bash-matched ' +
330
+ 'containment guards plus the SubagentStart eligibility gate. NOT ENFORCED unless Codex ' +
331
+ 'hook trust is established — see codexHookTrustPreconditions().',
332
+ hooks,
333
+ };
334
+ return `${JSON.stringify(doc, null, 2)}\n`;
335
+ }
336
+ /**
337
+ * Split a TOML document into sections, dropping comment lines first.
338
+ *
339
+ * A line-based pass rather than one regex, because the predicates below need the
340
+ * VALUE inside a specific section, and "does this string appear anywhere in the file"
341
+ * is what made both of them wrong (security review NEW-12/NEW-13). Whole-line
342
+ * comments only: a `#` inside a quoted value is data, and this parser never has to
343
+ * decide the difference because it only reads quoted strings and bare booleans.
344
+ */
345
+ function parseTomlSections(text) {
346
+ const sections = [];
347
+ let current = null;
348
+ for (const raw of text.split('\n')) {
349
+ const line = raw.trim();
350
+ if (line === '' || line.startsWith('#'))
351
+ continue;
352
+ const header = line.match(/^\[\s*(.+?)\s*\]/);
353
+ if (header) {
354
+ current = { header: header[1], body: [] };
355
+ sections.push(current);
356
+ continue;
357
+ }
358
+ if (current)
359
+ current.body.push(line);
360
+ }
361
+ return sections;
362
+ }
363
+ /**
364
+ * For a header like `projects."/some/path"`, return the quoted key when the prefix
365
+ * matches (`projects`) and null otherwise. Whitespace around the dot is tolerated
366
+ * because Codex's own writer emits it in some versions; the key itself is compared
367
+ * verbatim, so a path containing spaces or dots still matches exactly.
368
+ */
369
+ function tableQuotedKey(header, prefix) {
370
+ const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
371
+ const match = header.match(new RegExp(`^${escaped}\\s*\\.\\s*"(.*)"$`));
372
+ return match ? match[1] : null;
373
+ }
374
+ /** Value of `key = "…"` in a section body, or null when absent. */
375
+ function sectionString(body, key) {
376
+ for (const line of body) {
377
+ const match = line.match(new RegExp(`^${key}\\s*=\\s*"([^"]*)"`));
378
+ if (match)
379
+ return match[1];
380
+ }
381
+ return null;
382
+ }
383
+ /** True only when the section body says `key = true`. */
384
+ function sectionBoolTrue(body, key) {
385
+ return body.some((line) => new RegExp(`^${key}\\s*=\\s*true\\b`).test(line));
386
+ }
387
+ export function codexHookTrustPreconditions(opts) {
388
+ const codexHome = opts.codexHome ?? join(process.env.HOME ?? '', '.codex');
389
+ let configText = '';
390
+ try {
391
+ configText = readFileSync(join(codexHome, 'config.toml'), 'utf-8');
392
+ }
393
+ catch {
394
+ configText = '';
395
+ }
396
+ const sections = parseTomlSections(configText);
397
+ // PROJECT TRUST: read the VALUE, never the header (security review NEW-12).
398
+ // The previous predicate tested for the presence of a `[projects."<path>"]` header,
399
+ // so `trust_level = "untrusted"` — the value Codex itself writes when an operator
400
+ // DECLINES the trust prompt — reported satisfied, as did a commented-out header and
401
+ // a section with no trust_level at all. Round 2 promoted this predicate to the
402
+ // launch decision, which made "declined" indistinguishable from "trusted".
403
+ const projectSection = sections.find((s) => tableQuotedKey(s.header, 'projects') === opts.worktreePath);
404
+ const trustLevel = projectSection ? sectionString(projectSection.body, 'trust_level') : null;
405
+ // HOOK TRUST: same defect, same fix (security review NEW-13). Advisory today, a
406
+ // control at G-7, so it gets the value check now rather than after it starts
407
+ // carrying weight. A record counts only when it is switched on AND carries a hash.
408
+ const hookTrusted = sections.some((s) => tableQuotedKey(s.header, 'hooks.state') !== null &&
409
+ sectionBoolTrue(s.body, 'enabled') &&
410
+ (sectionString(s.body, 'trusted_hash') ?? '') !== '');
411
+ return [
412
+ {
413
+ id: 'hook-trust',
414
+ satisfied: hookTrusted,
415
+ detail: 'Codex runs hooks only with a persisted trust record (hooks.state."<key>".trusted_hash) ' +
416
+ 'or --dangerously-bypass-hook-trust. Without one, .codex/hooks.json is SILENTLY inert ' +
417
+ '(verified on codex-cli 0.145.0: three runs, no warning).',
418
+ },
419
+ {
420
+ id: 'project-trust',
421
+ satisfied: trustLevel === 'trusted',
422
+ detail: 'Until this project directory is trusted, Codex disables the ENTIRE project-local ' +
423
+ 'configuration — not just .codex/hooks.json but .codex/config.toml (so the declared ' +
424
+ 'sandbox_mode, approval_policy and the MemNexus MCP server are all ignored) and the exec ' +
425
+ 'policies too. Skills still load. ' +
426
+ `Trust is [projects."${opts.worktreePath}"] trust_level = "trusted" in the Codex config; ` +
427
+ `this project reads ${trustLevel === null ? 'no trust_level' : `trust_level = "${trustLevel}"`}.`,
428
+ },
429
+ ];
430
+ }
431
+ /**
432
+ * Generate `AGENTS.override.md` content (FR-7, FR-16).
433
+ *
434
+ * Carries the CLAUDE.local.md generator output — one source, so a behavioral-marker
435
+ * change cannot land on Claude and miss Codex — plus a notice naming the declared
436
+ * degradation: on Claude the marker block is re-injected every turn by a hook; Codex
437
+ * reads this file once, at session start.
438
+ *
439
+ * AND IT CARRIES THE CANONICAL AGENTS.md CONTENT TOO, because on Codex this file
440
+ * REPLACES AGENTS.md rather than adding to it (probed on codex-cli 0.145.0 — see
441
+ * finding 5 in the file header). The PRD called `AGENTS.override.md` the
442
+ * `CLAUDE.local.md` equivalent, but those two files are ADDITIVE on Claude and this
443
+ * one is a REPLACEMENT, so emitting only the local-override content would have left a
444
+ * Codex session reading its isolation context and behavioral markers while never
445
+ * seeing the canonical instructions.
446
+ */
447
+ export const CODEX_MARKER_DEGRADATION_NOTICE = '<!-- GENERATED by mx-agent start --runtime codex (#4227 FR-16). Generated from the same ' +
448
+ 'source as CLAUDE.local.md. DECLARED DEGRADATION: Codex reads this file once, at session ' +
449
+ 'start. The behavioral checks below are NOT re-injected per turn as they are on Claude. -->';
450
+ export const CODEX_CANONICAL_FOLD_NOTICE = '<!-- The canonical AGENTS.md content is reproduced below because Codex treats this file as a ' +
451
+ 'REPLACEMENT for AGENTS.md, not an addition to it (verified codex-cli 0.145.0). Regenerated ' +
452
+ 'every session; edit mx-agent-system/agent-config/AGENTS.md.template instead. -->';
453
+ export function buildAgentsOverride(opts) {
454
+ const built = buildClaudeLocalContent(opts);
455
+ let canonical = '';
456
+ try {
457
+ canonical = readFileSync(join(opts.worktreePath, 'AGENTS.md'), 'utf-8');
458
+ }
459
+ catch {
460
+ canonical = '';
461
+ }
462
+ // ORDER IS A SECURITY PROPERTY (security review NEW-4). `project_doc_max_bytes`
463
+ // truncates this file from the END, silently. Canonical AGENTS.md carries the
464
+ // standing security policy (worktree isolation, agent-config protection, the
465
+ // exclusion list); the worktree-local override carries this session's context.
466
+ // Losing the tail must therefore cost local context, not policy — so canonical
467
+ // content goes first, local override last.
468
+ // THIS ORDERING IS A MITIGATION, NOT THE PROTECTION (security review NEW-16): a
469
+ // truncated session is still running on instructions nobody has seen in full. The
470
+ // actual protection is the over-budget refusal in CodexAdapter.deployConfig — do
471
+ // not relax that throw on the grounds that the ordering makes truncation survivable.
472
+ const parts = [CODEX_MARKER_DEGRADATION_NOTICE, ''];
473
+ if (canonical.trim()) {
474
+ parts.push(CODEX_CANONICAL_FOLD_NOTICE, '', canonical, '', '---', '');
475
+ }
476
+ parts.push(built.content);
477
+ return {
478
+ content: `${parts.join('\n')}\n`,
479
+ ...(built.warning ? { warning: built.warning } : {}),
480
+ diagnostics: built.diagnostics,
481
+ hasBehavioralBlock: built.hasBehavioralBlock,
482
+ hasCanonicalContent: canonical.trim() !== '',
483
+ };
484
+ }
485
+ /**
486
+ * Measure the instruction bytes a Codex session reads (FR-5, security review S10).
487
+ *
488
+ * EXACTLY ONE FILE IS READ, in this precedence order, probed on codex-cli 0.145.0
489
+ * (finding 5 in the file header): `AGENTS.override.md`, else `AGENTS.md`, else
490
+ * `CLAUDE.md` via `project_doc_fallback_filenames`. The override REPLACES the
491
+ * canonical file rather than being appended to it, so the previous version of this
492
+ * function — which SUMMED AGENTS.md and the override — reported a total for a chain
493
+ * that does not exist. It over-counted by the size of a file Codex ignores, and it
494
+ * hid the fact that the ignored file was the canonical one.
495
+ *
496
+ * `project_doc_max_bytes` truncates that single file silently (a 433-byte file was
497
+ * cut at a 200-byte cap), so per-file and total are the same number today. Both are
498
+ * reported: `bytes` is what counts against the cap, `files` carries every candidate's
499
+ * own size so a warning can name which file is the problem.
500
+ */
501
+ export function measureInstructionChain(worktreePath,
502
+ /**
503
+ * Cap to measure against. Defaults to — and callers pass — PROJECT_DOC_MAX_BYTES,
504
+ * the same constant `buildCodexConfigToml` writes into `project_doc_max_bytes`, so
505
+ * the declared cap and the measured cap cannot drift apart (security review NEW-1).
506
+ */
507
+ cap = PROJECT_DOC_MAX_BYTES) {
508
+ // Precedence order — first match wins, the rest are recorded but not read.
509
+ const candidates = [AGENTS_OVERRIDE_FILENAME, 'AGENTS.md', 'CLAUDE.md'];
510
+ const files = [];
511
+ let readFile = null;
512
+ for (const rel of candidates) {
513
+ try {
514
+ const st = statSync(join(worktreePath, rel));
515
+ if (!st.isFile())
516
+ continue;
517
+ const isWinner = readFile === null;
518
+ if (isWinner)
519
+ readFile = rel;
520
+ files.push({ path: rel, bytes: st.size, read: isWinner });
521
+ }
522
+ catch {
523
+ /* absent — not a candidate */
524
+ }
525
+ }
526
+ const bytes = files.find((f) => f.read)?.bytes ?? 0;
527
+ return {
528
+ bytes,
529
+ cap,
530
+ overBudget: bytes > cap,
531
+ readFile,
532
+ files,
533
+ };
534
+ }
535
+ function writeFileEnsuringDir(absPath, content) {
536
+ mkdirSync(dirname(absPath), { recursive: true });
537
+ writeFileSync(absPath, content);
538
+ }
539
+ /**
540
+ * Deploy every Codex config artifact into the worktree. Idempotent — each file is
541
+ * regenerated in full, so a stale artifact cannot survive a restart.
542
+ */
543
+ export function deployCodexConfig(opts) {
544
+ const warnings = [];
545
+ const written = [];
546
+ const configPath = join(opts.worktreePath, CODEX_CONFIG_FILENAME);
547
+ try {
548
+ writeFileEnsuringDir(configPath, buildCodexConfigToml({ projectRoot: opts.projectRoot, model: opts.model }));
549
+ written.push(CODEX_CONFIG_FILENAME);
550
+ }
551
+ catch {
552
+ warnings.push(`Could not write ${CODEX_CONFIG_FILENAME} — Codex has no MemNexus MCP server configured.`);
553
+ }
554
+ // Each ported guard's script must actually be on disk. The generated wrapper fails
555
+ // OPEN when it is not (matching the Claude wrapper), so an absent script is a guard
556
+ // that silently does nothing — name it (security review S9).
557
+ for (const script of PHASE1_PORTED_GUARDS) {
558
+ if (!existsSync(join(opts.worktreePath, '.claude', 'hooks', script))) {
559
+ warnings.push(`Guard script .claude/hooks/${script} is MISSING — its Codex hook is registered but will ` +
560
+ `do nothing (the wrapper fails open, exactly as it does on Claude). Run \`mx-agent start\` ` +
561
+ `on this worktree to redeploy hooks, or check the config generator.`);
562
+ }
563
+ }
564
+ const hooksPath = join(opts.worktreePath, CODEX_HOOKS_FILENAME);
565
+ try {
566
+ writeFileEnsuringDir(hooksPath, buildCodexHooksJson({
567
+ worktreePath: opts.worktreePath,
568
+ ...(opts.provenGuards ? { provenGuards: opts.provenGuards } : {}),
569
+ }));
570
+ written.push(CODEX_HOOKS_FILENAME);
571
+ }
572
+ catch {
573
+ warnings.push(`Could not write ${CODEX_HOOKS_FILENAME} — no containment guards are registered.`);
574
+ }
575
+ const overridePath = join(opts.worktreePath, AGENTS_OVERRIDE_FILENAME);
576
+ const override = buildAgentsOverride({
577
+ projectRoot: opts.projectRoot,
578
+ worktreePath: opts.worktreePath,
579
+ worktreeName: opts.worktreeName,
580
+ branch: opts.branch,
581
+ slot: opts.slot,
582
+ ...(opts.projectSlug ? { projectSlug: opts.projectSlug } : {}),
583
+ ...(opts.teamSlug ? { teamSlug: opts.teamSlug } : {}),
584
+ ...(opts.baseBranch ? { baseBranch: opts.baseBranch } : {}),
585
+ ...(opts.gitRemote ? { gitRemote: opts.gitRemote } : {}),
586
+ });
587
+ // Every warn-level line, not just the missing-block one: #4707's rule is that a
588
+ // read from a stale local tree is NEVER silent, and the Codex path has the same
589
+ // failure mode as the Claude path. `override.warning` is one of these entries.
590
+ for (const d of override.diagnostics) {
591
+ if (d.level === 'warn')
592
+ warnings.push(d.message);
593
+ }
594
+ if (!override.hasCanonicalContent) {
595
+ warnings.push(`No AGENTS.md found to fold into ${AGENTS_OVERRIDE_FILENAME} — because Codex treats that ` +
596
+ `file as a REPLACEMENT for AGENTS.md, this session gets isolation context and behavioral ` +
597
+ `markers but NO canonical instructions.`);
598
+ }
599
+ try {
600
+ writeFileEnsuringDir(overridePath, override.content);
601
+ written.push(AGENTS_OVERRIDE_FILENAME);
602
+ }
603
+ catch {
604
+ warnings.push(`Could not write ${AGENTS_OVERRIDE_FILENAME} — this Codex session has no local override context.`);
605
+ }
606
+ // Measured AFTER the override is written, since that file is the one Codex reads.
607
+ const chain = measureInstructionChain(opts.worktreePath, PROJECT_DOC_MAX_BYTES);
608
+ if (chain.overBudget) {
609
+ warnings.push(`Codex reads ${chain.readFile} (${chain.bytes} bytes), over the ${chain.cap}-byte ` +
610
+ `project_doc_max_bytes — it will be TRUNCATED silently. Per-file sizes: ` +
611
+ `${chain.files.map((f) => `${f.path} ${f.bytes}B${f.read ? ' (read)' : ' (ignored)'}`).join(', ')}.`);
612
+ }
613
+ const trust = codexHookTrustPreconditions({ worktreePath: opts.worktreePath });
614
+ return { written, warnings, chain, trust };
615
+ }
616
+ /** Does the worktree carry a generated Codex config tree? Used by tests and doctor-style checks. */
617
+ export function hasCodexConfig(worktreePath) {
618
+ return existsSync(join(worktreePath, CODEX_CONFIG_FILENAME));
619
+ }
620
+ //# sourceMappingURL=codex-config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex-config.js","sourceRoot":"","sources":["../../../src/lib/runtime/codex-config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AACH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AAClF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EACL,uBAAuB,GAGxB,MAAM,cAAc,CAAC;AAEtB;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,SAAS,CAAC;AAE7C;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,SAAS,CAAC;AAEhD,8DAA8D;AAC9D,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,GAAG,IAAI,CAAC;AAE/C,kFAAkF;AACl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