@memnexus-ai/mx-agent-cli 0.1.269 → 0.1.270

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 (45) hide show
  1. package/dist/__tests__/codex-deploy-config.test.d.ts +2 -0
  2. package/dist/__tests__/codex-deploy-config.test.d.ts.map +1 -0
  3. package/dist/__tests__/codex-deploy-config.test.js +1170 -0
  4. package/dist/__tests__/codex-deploy-config.test.js.map +1 -0
  5. package/dist/__tests__/codex-trust-keys.test.d.ts +2 -0
  6. package/dist/__tests__/codex-trust-keys.test.d.ts.map +1 -0
  7. package/dist/__tests__/codex-trust-keys.test.js +731 -0
  8. package/dist/__tests__/codex-trust-keys.test.js.map +1 -0
  9. package/dist/__tests__/codex-write-race.test.d.ts +2 -0
  10. package/dist/__tests__/codex-write-race.test.d.ts.map +1 -0
  11. package/dist/__tests__/codex-write-race.test.js +372 -0
  12. package/dist/__tests__/codex-write-race.test.js.map +1 -0
  13. package/dist/__tests__/runtime-codex-guard-proof.test.js +75 -0
  14. package/dist/__tests__/runtime-codex-guard-proof.test.js.map +1 -1
  15. package/dist/commands/codex-deploy-config.d.ts +111 -0
  16. package/dist/commands/codex-deploy-config.d.ts.map +1 -0
  17. package/dist/commands/codex-deploy-config.js +400 -0
  18. package/dist/commands/codex-deploy-config.js.map +1 -0
  19. package/dist/commands/codex-prove-guards.d.ts +20 -0
  20. package/dist/commands/codex-prove-guards.d.ts.map +1 -1
  21. package/dist/commands/codex-prove-guards.js +54 -1
  22. package/dist/commands/codex-prove-guards.js.map +1 -1
  23. package/dist/commands/codex-trust-keys.d.ts +12 -0
  24. package/dist/commands/codex-trust-keys.d.ts.map +1 -0
  25. package/dist/commands/codex-trust-keys.js +169 -0
  26. package/dist/commands/codex-trust-keys.js.map +1 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +65 -0
  29. package/dist/index.js.map +1 -1
  30. package/dist/lib/runtime/codex-adapter.d.ts.map +1 -1
  31. package/dist/lib/runtime/codex-adapter.js +15 -15
  32. package/dist/lib/runtime/codex-adapter.js.map +1 -1
  33. package/dist/lib/runtime/codex-config.d.ts +211 -0
  34. package/dist/lib/runtime/codex-config.d.ts.map +1 -1
  35. package/dist/lib/runtime/codex-config.js +769 -40
  36. package/dist/lib/runtime/codex-config.js.map +1 -1
  37. package/dist/lib/runtime/codex-hooks-list.d.ts +91 -0
  38. package/dist/lib/runtime/codex-hooks-list.d.ts.map +1 -0
  39. package/dist/lib/runtime/codex-hooks-list.js +418 -0
  40. package/dist/lib/runtime/codex-hooks-list.js.map +1 -0
  41. package/dist/lib/runtime/codex-trust-keys.d.ts +95 -0
  42. package/dist/lib/runtime/codex-trust-keys.d.ts.map +1 -0
  43. package/dist/lib/runtime/codex-trust-keys.js +279 -0
  44. package/dist/lib/runtime/codex-trust-keys.js.map +1 -0
  45. package/package.json +1 -1
@@ -68,8 +68,9 @@
68
68
  * ────────────────────────────────────────────────────────────────────────────
69
69
  */
70
70
  import { spawnSync } from 'child_process';
71
- import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'fs';
72
- import { basename, dirname, isAbsolute, join, resolve, sep } from 'path';
71
+ import { randomBytes } from 'crypto';
72
+ import { closeSync, constants as fsConstants, existsSync, fchmodSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'fs';
73
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path';
73
74
  import { buildClaudeLocalContent, } from '../claude.js';
74
75
  /**
75
76
  * Model the CodexAdapter selects (PRD Open Question 2, Option A — one known-good
@@ -991,8 +992,15 @@ function sectionString(body, key) {
991
992
  function sectionBoolTrue(body, key) {
992
993
  return body.some((line) => new RegExp(`^${key}\\s*=\\s*true\\b`).test(line));
993
994
  }
994
- export function codexHookTrustPreconditions(opts) {
995
- const codexHome = opts.codexHome ?? join(process.env.HOME ?? '', '.codex');
995
+ /**
996
+ * Read every `[hooks.state."<key>"]` record from a Codex config (#4876).
997
+ *
998
+ * Exported so `mx-agent codex trust-keys` reports the same records the precondition
999
+ * decides on, rather than parsing the file a second way. `trust_level` is read here too,
1000
+ * because both callers need to know that an untrusted project makes every hook record
1001
+ * moot.
1002
+ */
1003
+ export function readCodexTrustState(codexHome) {
996
1004
  let configText = '';
997
1005
  try {
998
1006
  configText = readFileSync(join(codexHome, 'config.toml'), 'utf-8');
@@ -1001,14 +1009,33 @@ export function codexHookTrustPreconditions(opts) {
1001
1009
  configText = '';
1002
1010
  }
1003
1011
  const sections = parseTomlSections(configText);
1012
+ const records = new Map();
1013
+ for (const s of sections) {
1014
+ const key = tableQuotedKey(s.header, 'hooks.state');
1015
+ if (key === null)
1016
+ continue;
1017
+ records.set(key, {
1018
+ enabled: sectionBoolTrue(s.body, 'enabled'),
1019
+ hash: sectionString(s.body, 'trusted_hash') ?? '',
1020
+ });
1021
+ }
1022
+ const trustLevelFor = (path) => {
1023
+ const section = sections.find((s) => tableQuotedKey(s.header, 'projects') === path);
1024
+ return section ? sectionString(section.body, 'trust_level') : null;
1025
+ };
1026
+ return { records, trustLevelFor };
1027
+ }
1028
+ export function codexHookTrustPreconditions(opts) {
1029
+ const resolvedHome = resolveCodexHome();
1030
+ const codexHome = opts.codexHome ?? ('home' in resolvedHome ? resolvedHome.home : '');
1031
+ const trustState = readCodexTrustState(codexHome);
1004
1032
  // PROJECT TRUST: read the VALUE, never the header (security review NEW-12).
1005
1033
  // The previous predicate tested for the presence of a `[projects."<path>"]` header,
1006
1034
  // so `trust_level = "untrusted"` — the value Codex itself writes when an operator
1007
1035
  // DECLINES the trust prompt — reported satisfied, as did a commented-out header and
1008
1036
  // a section with no trust_level at all. Round 2 promoted this predicate to the
1009
1037
  // launch decision, which made "declined" indistinguishable from "trusted".
1010
- const projectSection = sections.find((s) => tableQuotedKey(s.header, 'projects') === opts.worktreePath);
1011
- const trustLevel = projectSection ? sectionString(projectSection.body, 'trust_level') : null;
1038
+ const trustLevel = trustState.trustLevelFor(opts.worktreePath);
1012
1039
  // HOOK TRUST: per ENTRY, and keyed to THIS worktree's hooks.json path (#4864, SF-2).
1013
1040
  //
1014
1041
  // The value check is NEW-13's (a record counts only when it is switched on AND
@@ -1022,19 +1049,11 @@ export function codexHookTrustPreconditions(opts) {
1022
1049
  // Codex hashes each entry's content into its record, and the hashing is internal to
1023
1050
  // the binary (a sha256 of the command, of the group, or of either serialization does
1024
1051
  // NOT reproduce the values a live grant wrote). So this checks PRESENCE, ENABLEMENT
1025
- // and a NON-EMPTY hash per key, and says plainly that hash agreement is Codex's own
1026
- // check — a stale hash still means the entry does not run, and it is not detectable
1027
- // from here.
1028
- const trustRecords = new Map();
1029
- for (const s of sections) {
1030
- const key = tableQuotedKey(s.header, 'hooks.state');
1031
- if (key === null)
1032
- continue;
1033
- trustRecords.set(key, {
1034
- enabled: sectionBoolTrue(s.body, 'enabled'),
1035
- hash: sectionString(s.body, 'trusted_hash') ?? '',
1036
- });
1037
- }
1052
+ // and a NON-EMPTY hash per key — and, when `observedHashes` is supplied (#4876),
1053
+ // AGREEMENT with the hash Codex itself reports for the entry. Without that input the
1054
+ // agreement half cannot be checked here, and the detail below says so rather than
1055
+ // implying the grant is current.
1056
+ const trustRecords = trustState.records;
1038
1057
  const hooksPath = join(opts.worktreePath, CODEX_HOOKS_FILENAME);
1039
1058
  const doc = readDeployedHooksDoc(opts.worktreePath);
1040
1059
  const requiredKeys = doc ? codexHookTrustKeysForDoc(hooksPath, doc) : [];
@@ -1042,9 +1061,35 @@ export function codexHookTrustPreconditions(opts) {
1042
1061
  const record = trustRecords.get(key);
1043
1062
  return !record || !record.enabled || record.hash === '';
1044
1063
  });
1064
+ // ── HASH AGREEMENT (#4876, KI-CODEX-TRUST-HASH-NOT-VERIFIED) ─────────────────
1065
+ // Only for keys that HAVE a usable record — an ungranted key is already reported, and
1066
+ // reporting it twice would bury the distinction between "never granted" and "granted
1067
+ // for bytes that changed". The second one is the dangerous state: it looks configured.
1068
+ const granted = requiredKeys.filter((k) => !ungranted.includes(k));
1069
+ const stale = [];
1070
+ const unverified = [];
1071
+ if (opts.observedHashes) {
1072
+ for (const key of granted) {
1073
+ const observed = opts.observedHashes.get(key);
1074
+ if (observed === undefined) {
1075
+ unverified.push(key);
1076
+ }
1077
+ else if (observed !== (trustRecords.get(key)?.hash ?? '')) {
1078
+ stale.push(key);
1079
+ }
1080
+ }
1081
+ }
1045
1082
  // No deployed hooks file, or a file with no entries, is NOT trust — there is nothing
1046
1083
  // registered to be trusted, so reporting "satisfied" would be an empty-set green.
1047
- const hookTrusted = requiredKeys.length > 0 && ungranted.length === 0;
1084
+ const hookTrusted = requiredKeys.length > 0 &&
1085
+ ungranted.length === 0 &&
1086
+ stale.length === 0 &&
1087
+ unverified.length === 0 &&
1088
+ // Changed bytes under existing grants is a KNOWN stale state, not an unchecked one.
1089
+ // Reporting it satisfied is the false green MF-2 names.
1090
+ opts.bytesChanged !== true &&
1091
+ // And an UNCHECKABLE state is not a satisfied one either (SF-B).
1092
+ opts.grantsUnverifiable !== true;
1048
1093
  return [
1049
1094
  {
1050
1095
  id: 'hook-trust',
@@ -1058,13 +1103,55 @@ export function codexHookTrustPreconditions(opts) {
1058
1103
  'so nothing is trusted. Run `mx-agent start <team> --runtime codex` to deploy it.'
1059
1104
  : requiredKeys.length === 0
1060
1105
  ? `${CODEX_HOOKS_FILENAME} registers no hook entries — no guard is in effect.`
1061
- : ungranted.length === 0
1062
- ? `All ${requiredKeys.length} entries are granted: ${requiredKeys.join(', ')}. ` +
1063
- 'Whether each recorded hash still MATCHES the current file is Codex\'s own check, ' +
1064
- 'not one this can make — a stale hash means that entry does not run.'
1065
- : `${ungranted.length} of ${requiredKeys.length} entries have NO usable trust record ` +
1066
- `(missing, disabled, or with an empty hash): ${ungranted.join(', ')}. ` +
1067
- 'A human grants these once, in the session where Codex prompts for them.'),
1106
+ : [
1107
+ ungranted.length > 0
1108
+ ? `${ungranted.length} of ${requiredKeys.length} entries have NO usable trust ` +
1109
+ `record (missing, disabled, or with an empty hash): ${ungranted.join(', ')}. ` +
1110
+ 'A human grants these once, in the session where Codex prompts for them.'
1111
+ : '',
1112
+ // A STALE grant is reported separately from a missing one on purpose: it is
1113
+ // the state that LOOKS configured. Codex will not run an entry whose hash
1114
+ // stopped matching, and it says nothing when it declines.
1115
+ stale.length > 0
1116
+ ? `${stale.length} entries carry a STALE trusted_hash — present and enabled, but ` +
1117
+ 'no longer equal to the hash Codex reports for the entry, so Codex SILENTLY ' +
1118
+ `does not run them: ${stale.join(', ')}. Re-grant with the current hash ` +
1119
+ '(`mx-agent codex trust-keys` prints it and a pasteable block).'
1120
+ : '',
1121
+ unverified.length > 0
1122
+ ? `${unverified.length} entries could not be checked against Codex's own hash ` +
1123
+ `— it reported none for them: ${unverified.join(', ')}. Reported as NOT ` +
1124
+ 'satisfied: an unverifiable grant is not a verified one.'
1125
+ : '',
1126
+ // SUPPRESSED when the bytes just changed (MF-2). This branch is the only
1127
+ // place the string "All N entries are granted" is produced, and it must
1128
+ // never be produced by a caller that cannot see hashes AND has just
1129
+ // rewritten the file the hashes are over.
1130
+ ungranted.length === 0 && stale.length === 0 && unverified.length === 0
1131
+ ? opts.bytesChanged === true
1132
+ ? `All ${requiredKeys.length} entries have a trust record, and every one of ` +
1133
+ 'them is now STALE: the bytes of the hooks file just changed, and a Codex ' +
1134
+ 'trust record is bound to the entry content it was granted for. Codex ' +
1135
+ 'silently does not run an entry whose hash stopped matching. Re-grant ' +
1136
+ 'before the next launch: `mx-agent codex trust-keys`.'
1137
+ : opts.grantsUnverifiable === true
1138
+ ? `All ${requiredKeys.length} entries have a trust record, and NONE of them ` +
1139
+ 'could be confirmed current on this run: either the hooks file could not be ' +
1140
+ 'read before it was rewritten, or the Codex config directory could not be ' +
1141
+ 'located. A record that no longer matches its entry is one Codex silently ' +
1142
+ 'does not run. Verify before the next launch: `mx-agent codex trust-keys`.'
1143
+ : `All ${requiredKeys.length} entries are granted: ${requiredKeys.join(', ')}. ` +
1144
+ (opts.observedHashes
1145
+ ? 'Each recorded hash was compared to the hash Codex reports for that entry ' +
1146
+ 'and matches.'
1147
+ : 'Whether each recorded hash still MATCHES the current file is Codex\'s own ' +
1148
+ 'check, and no observed hashes were supplied to this call — a stale hash ' +
1149
+ 'would mean that entry does not run, and would not be visible here. ' +
1150
+ 'Run `mx-agent codex trust-keys` to check.')
1151
+ : '',
1152
+ ]
1153
+ .filter(Boolean)
1154
+ .join(' ')),
1068
1155
  },
1069
1156
  {
1070
1157
  id: 'project-trust',
@@ -1182,9 +1269,404 @@ cap = PROJECT_DOC_MAX_BYTES) {
1182
1269
  files,
1183
1270
  };
1184
1271
  }
1185
- function writeFileEnsuringDir(absPath, content) {
1272
+ /**
1273
+ * Where the Codex config lives, in ONE place (security review SF-A).
1274
+ *
1275
+ * Four call sites hardcoded `join(process.env.HOME ?? '', '.codex')`, which is wrong on
1276
+ * any machine that sets `CODEX_HOME` — Codex's own override for exactly this directory.
1277
+ * The failure is silent and in the dangerous direction: the grants live in `CODEX_HOME`,
1278
+ * we read an empty file in `$HOME/.codex`, see no records, and a redeploy that just
1279
+ * invalidated every real grant reports `hookTrustInvalidated = false` (reviewer's probe 3,
1280
+ * executed).
1281
+ *
1282
+ * REFUSES rather than falling back to a relative path. `HOME` unset made the old
1283
+ * expression produce `.codex`, resolved against whatever the cwd happened to be — a read
1284
+ * that fails, and a failed read of the trust config is indistinguishable here from "no
1285
+ * grants exist".
1286
+ */
1287
+ export function resolveCodexHome(env = process.env) {
1288
+ const explicit = (env.CODEX_HOME ?? '').trim();
1289
+ if (explicit) {
1290
+ if (!isAbsolute(explicit)) {
1291
+ return {
1292
+ error: `CODEX_HOME is set to "${explicit}", which is not an absolute path. Codex resolves it ` +
1293
+ 'against its own working directory, so this tool cannot know which file it means.',
1294
+ };
1295
+ }
1296
+ return { home: explicit };
1297
+ }
1298
+ const home = (env.HOME ?? '').trim();
1299
+ if (!home || !isAbsolute(home)) {
1300
+ return {
1301
+ error: 'neither CODEX_HOME nor HOME names an absolute directory, so the Codex config directory ' +
1302
+ 'cannot be located. Set CODEX_HOME to the directory holding config.toml.',
1303
+ };
1304
+ }
1305
+ return { home: join(home, '.codex') };
1306
+ }
1307
+ /**
1308
+ * May this deploy write `absPath`, given that it is only allowed to write inside
1309
+ * `worktreeRoot`? Returns the refusal text, or null.
1310
+ *
1311
+ * ─── THE CHECK THAT WAS MISSING (security review MF-1) ────────────────────────
1312
+ * Round 1 contained the ARGUMENT (`--path`) and left the WRITES uncontained. The
1313
+ * reviewer executed four attacks that all succeeded and all ended in the main repo's
1314
+ * fleet-wide files:
1315
+ *
1316
+ * 1. `<worktree>/.codex` is a directory symlink to `<projectRoot>/.codex`.
1317
+ * 2. The same as a COMMITTED relative symlink (`.codex -> ../../.codex`,
1318
+ * `AGENTS.override.md -> ../../AGENTS.override.md`) — plantable by a PR.
1319
+ * 3. `<worktree>/.codex/hooks.json` is a single-FILE symlink to the main repo's.
1320
+ * 4. TOCTOU: the checked directory is swapped for a symlink to the project root
1321
+ * between `resolveCodexDeployTarget` and the write.
1322
+ *
1323
+ * `mkdirSync`/`writeFileSync` follow symlinks, so the containment test on the directory
1324
+ * name proved nothing about where the bytes landed. This walks EVERY component from the
1325
+ * worktree root down to the file with `lstatSync` (which does not follow), refuses on the
1326
+ * first symlink, and refuses when the path is not under the root at all. The worktree
1327
+ * root itself must be a real directory — that is what kills the TOCTOU swap, since the
1328
+ * root the caller resolved is re-lstat'd at write time.
1329
+ *
1330
+ * The refusal names the file AND its real destination: "could not write" is what shipped,
1331
+ * and it does not tell the operator that their deploy was aimed at `/workspace`.
1332
+ *
1333
+ * ─── AND HARDLINKS, WHICH ARE NOT SYMLINKS (security review NEW-MF-4) ─────────
1334
+ * The walk above refuses a second PATH to the file. A hardlink is a second NAME for the
1335
+ * same inode: `lstat` calls it a plain regular file and `O_NOFOLLOW` says nothing about
1336
+ * it. So the walk also refuses any non-directory component with `nlink > 1`, and the
1337
+ * write breaks the existing directory entry rather than writing through it.
1338
+ */
1339
+ export function containedWriteRefusal(worktreeRoot, absPath) {
1340
+ const describe = (path) => {
1341
+ try {
1342
+ const real = realpathSync(path);
1343
+ return real === path ? path : `${path} (which resolves to ${real})`;
1344
+ }
1345
+ catch {
1346
+ return path;
1347
+ }
1348
+ };
1349
+ let rootStat;
1350
+ try {
1351
+ rootStat = lstatSync(worktreeRoot);
1352
+ }
1353
+ catch (err) {
1354
+ return (`refusing to write ${absPath}: its worktree root ${worktreeRoot} could not be read ` +
1355
+ `(${err instanceof Error ? err.message : String(err)}).`);
1356
+ }
1357
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
1358
+ return (`refusing to write ${absPath}: the worktree root ${describe(worktreeRoot)} is not a real ` +
1359
+ 'directory. A symlinked worktree root sends every artifact this deploy writes to the ' +
1360
+ 'link\'s destination — under OpenAI bug #27133 the main repo\'s .codex/hooks.json governs ' +
1361
+ 'every Codex session in the fleet, so that is a fleet-wide write. ' +
1362
+ 'Nothing was written.');
1363
+ }
1364
+ const rel = relative(worktreeRoot, absPath);
1365
+ if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) {
1366
+ return (`refusing to write ${describe(absPath)}: it is outside the worktree ${worktreeRoot} this ` +
1367
+ 'deploy is allowed to write. Nothing was written.');
1368
+ }
1369
+ let walked = worktreeRoot;
1370
+ for (const part of rel.split(sep)) {
1371
+ walked = join(walked, part);
1372
+ let st;
1373
+ try {
1374
+ st = lstatSync(walked);
1375
+ }
1376
+ catch (err) {
1377
+ // ── ONLY "IT DOES NOT EXIST" IS AN ALLOW (security review SF-F) ───────────
1378
+ // This catch returned null — ALLOW — for EVERY error. The reviewer executed two:
1379
+ // a regular file at `.codex` with the path continuing below it (ENOTDIR) and an
1380
+ // unreadable parent (EACCES), both allowed. Neither escapes today because the
1381
+ // write then fails, but a containment predicate that answers "permitted" when it
1382
+ // could not look is answering a question it did not ask, and the next lstat
1383
+ // failure mode it meets will be an allow by default.
1384
+ const code = err.code ?? 'unknown';
1385
+ if (code !== 'ENOENT') {
1386
+ return (`refusing to write ${absPath}: the component ${walked} could not be examined (${code}: ` +
1387
+ `${err instanceof Error ? err.message : String(err)}), so this deploy cannot tell whether ` +
1388
+ 'the bytes would stay inside this worktree. Containment fails closed. Nothing was written.');
1389
+ }
1390
+ // Absent — `mkdirSync`/`writeFileSync` will create it as a real entry inside the
1391
+ // root. Nothing below it can exist either, so the walk is done.
1392
+ return null;
1393
+ }
1394
+ if (st.isSymbolicLink()) {
1395
+ return (`refusing to write ${absPath}: ${describe(walked)} is a SYMLINK, so the bytes would land ` +
1396
+ 'outside this worktree. Under OpenAI bug #27133 the main repo\'s .codex/hooks.json ' +
1397
+ 'governs every Codex session in the fleet and AGENTS.override.md there replaces AGENTS.md ' +
1398
+ 'for every main-repo session, so a symlinked artifact path is a fleet-wide write with a ' +
1399
+ 'worktree-shaped argument. Delete or replace the symlink with a real ' +
1400
+ `${walked === absPath ? 'file' : 'directory'} and redeploy. Nothing was written.`);
1401
+ }
1402
+ // ── A HARDLINK IS NOT A SYMLINK (security review NEW-MF-4) ─────────────────
1403
+ // The symlink check above proves nothing about a second NAME for the same inode.
1404
+ // `lstat` reports a hardlink as a plain regular file and `O_NOFOLLOW` only rejects
1405
+ // symlinks, so `ln <projectRoot>/AGENTS.override.md <worktree>/AGENTS.override.md`
1406
+ // — an operation an agent confined to its own worktree is fully entitled to perform
1407
+ // — made the next deploy write the main repo's fleet-wide files while reporting
1408
+ // ok=true and no refusals. The reviewer executed it: the attacker's own worktree
1409
+ // AGENTS.md text landed in the main repo's AGENTS.override.md, which REPLACES
1410
+ // AGENTS.md for every main-repo Codex session. `fs.protected_hardlinks` does not
1411
+ // help — the repo and the worktrees are one device and one uid.
1412
+ //
1413
+ // Directories are exempt: every directory has at least two links (its own name and
1414
+ // `.`), and hardlinked directories are not creatable on Linux.
1415
+ if (!st.isDirectory() && st.nlink > 1) {
1416
+ return (`refusing to write ${absPath}: ${walked} is a HARDLINK — the same file has ${st.nlink} names ` +
1417
+ 'on this filesystem, so the bytes would also land outside this worktree, at every other ' +
1418
+ 'name for that inode. Under OpenAI bug #27133 the main repo\'s .codex/hooks.json governs ' +
1419
+ 'every Codex session in the fleet and AGENTS.override.md there replaces AGENTS.md for ' +
1420
+ 'every main-repo session, so a second name for an artifact path is a fleet-wide write ' +
1421
+ 'with a worktree-shaped argument. Delete the extra link (or this entry) and redeploy. ' +
1422
+ 'Nothing was written.');
1423
+ }
1424
+ }
1425
+ return null;
1426
+ }
1427
+ /**
1428
+ * Thrown by `writeFileEnsuringDir` when the destination fails `containedWriteRefusal`, or
1429
+ * when the file it just created exclusively turns out to have more than one name.
1430
+ */
1431
+ export class ContainedWriteRefusal extends Error {
1432
+ }
1433
+ /**
1434
+ * The mode a freshly installed artifact gets, given whatever was at `absPath` before
1435
+ * (security review SF-2).
1436
+ *
1437
+ * `O_TRUNC` used to write into the existing inode and so kept its permissions. Creating a
1438
+ * new entry does not, and the previous fix hardcoded `0o644` — so a deliberately
1439
+ * restrictive artifact (0600) came back world-readable after a redeploy, silently. Nothing
1440
+ * generated here is secret today, so nothing is disclosed; a deploy that quietly widens a
1441
+ * file's permissions is still the wrong default, and the `open` mode argument is masked by
1442
+ * the process umask, so the mode a deploy produced was not even the same for two
1443
+ * operators.
1444
+ *
1445
+ * The rule: keep a pre-existing mode when it is no more permissive than 0644, otherwise
1446
+ * 0644. Preserving is the conservative direction for the case the finding is about;
1447
+ * clamping means a 0666 entry planted in the worktree is not adopted as the deployed mode.
1448
+ * Applied with `fchmod` at the call site, which the umask does not touch.
1449
+ *
1450
+ * ─── AND AN OWNER FLOOR, BECAUSE PRESERVING HAD NO BOTTOM (review SF-J) ───────
1451
+ * `(mode & ~0o644) === 0` is true of 0000 and of 0200: neither adds a bit beyond 0644, so
1452
+ * both were preserved verbatim. The reviewer executed it — a pre-planted 0000
1453
+ * `.codex/hooks.json` deployed as 0000 with ok=true and no warning. A hooks file the
1454
+ * session cannot READ registers no containment guard, and the failure is silent in the
1455
+ * direction that matters: Codex's hooks parse failure is fail-open (finding 1 in the file
1456
+ * header), so the artifact is there, the deploy says it wrote it, and the guards are
1457
+ * inert. `| 0o600` puts an owner read+write floor under the preserved mode. It cannot
1458
+ * widen anything beyond the owner — the clamp above still decides group and other — and
1459
+ * it strips setuid/setgid/sticky the same way the `& 0o777` mask always did.
1460
+ */
1461
+ function modeForInstalledArtifact(absPath) {
1462
+ let existing;
1463
+ try {
1464
+ existing = lstatSync(absPath);
1465
+ }
1466
+ catch {
1467
+ return 0o644; // absent, or unexaminable — the open below will report anything real
1468
+ }
1469
+ if (!existing.isFile())
1470
+ return 0o644;
1471
+ const mode = existing.mode & 0o777;
1472
+ return ((mode & ~0o644) === 0 ? mode : 0o644) | 0o600;
1473
+ }
1474
+ /**
1475
+ * ─── THE PARENT DIRECTORY IS RE-IDENTIFIED, NOT RE-CHECKED BY NAME (MUST FIX) ──
1476
+ *
1477
+ * `containedWriteRefusal` walks names. A name can stop describing the same directory the
1478
+ * instant after it is walked, and the write-aside-and-rename form made that window seven
1479
+ * syscalls wide (lstat, the second containment walk, open, fstat, fchmod, THE WHOLE
1480
+ * CONTENT WRITE, rename) where the destroy-first form was two. The reviewer measured what
1481
+ * that bought an attacker who swaps `<worktree>/.codex` for a symlink to the MAIN repo's
1482
+ * `.codex`, at 40,000 deploys per build under identical pressure: the predecessor took 5
1483
+ * window hits and overwrote the main repo 0 times; this build took 135 hits, overwrote the
1484
+ * main repo's `.codex/hooks.json` FOUR times — every one of them reported as WRITTEN by
1485
+ * the deploy — and left 33 `.mx-tmp-*` files inside the main repo besides.
1486
+ *
1487
+ * Comparing `{dev, ino}` against the identity captured before the open answers the
1488
+ * question the name cannot: is this still the SAME directory, or a different one wearing
1489
+ * the same name. It is checked twice — once with the temp file open and not yet written,
1490
+ * so a swap turns a 4983-byte fleet-wide write into a zero-byte temp that is then
1491
+ * unlinked; and once immediately before `renameSync`, which narrows the residual window to
1492
+ * the rename call itself, at or below the width the predecessor had.
1493
+ *
1494
+ * THIS IS A NARROWING, NOT A CLOSURE, AND MUST NOT BE DESCRIBED AS ONE. The complete fix
1495
+ * is to hold a file descriptor on the directory and use `openat`/`renameat` against it, so
1496
+ * the kernel resolves against the directory OBJECT and no name is ever re-resolved. Node
1497
+ * exposes neither. That residual stays in known-issues; step 4 at the call site is what
1498
+ * keeps the REPORT honest when the residual is hit.
1499
+ */
1500
+ function directoryIdentity(dir) {
1501
+ const st = lstatSync(dir, { bigint: true });
1502
+ if (!st.isDirectory() || st.isSymbolicLink()) {
1503
+ throw new ContainedWriteRefusal(`refusing to write into ${dir}: it is not a real directory. Nothing was written.`);
1504
+ }
1505
+ return { dev: st.dev, ino: st.ino };
1506
+ }
1507
+ /**
1508
+ * Refuse unless `dir` is still the very directory `expected` identifies.
1509
+ *
1510
+ * All three ways this can fail — the name now resolves to a different directory, to a
1511
+ * SYMLINK or other non-directory, or to nothing this process can examine — are ONE event
1512
+ * as far as the operator is concerned: the directory that passed containment is not the
1513
+ * directory about to be written into. They share a message for that reason, with the
1514
+ * measured difference appended, and every one of them is fail-closed.
1515
+ */
1516
+ function assertSameDirectory(dir, expected, absPath, when) {
1517
+ let observed;
1518
+ try {
1519
+ const st = lstatSync(dir, { bigint: true });
1520
+ if (st.dev === expected.dev && st.ino === expected.ino && st.isDirectory())
1521
+ return;
1522
+ observed = st.isSymbolicLink()
1523
+ ? 'a SYMLINK, which resolves wherever its target points'
1524
+ : !st.isDirectory()
1525
+ ? 'not a directory at all'
1526
+ : `device ${st.dev}/inode ${st.ino}`;
1527
+ }
1528
+ catch (err) {
1529
+ observed = `unexaminable (${err instanceof Error ? err.message : String(err)})`;
1530
+ }
1531
+ throw new ContainedWriteRefusal(`refusing to write ${absPath}: the directory ${dir} was REPLACED ${when} — it was ` +
1532
+ `device ${expected.dev}/inode ${expected.ino} when containment passed, and is now ` +
1533
+ `${observed}. The name still resolves, to something this deploy never checked, so the ` +
1534
+ 'bytes would land outside this worktree. Under OpenAI bug #27133 the main repo\'s ' +
1535
+ '.codex/hooks.json governs every Codex session in the fleet, and that is what a swapped ' +
1536
+ '.codex points at. Nothing was installed.');
1537
+ }
1538
+ function writeFileEnsuringDir(absPath, content, worktreeRoot) {
1539
+ const refusal = containedWriteRefusal(worktreeRoot, absPath);
1540
+ if (refusal)
1541
+ throw new ContainedWriteRefusal(refusal);
1186
1542
  mkdirSync(dirname(absPath), { recursive: true });
1187
- writeFileSync(absPath, content);
1543
+ const mode = modeForInstalledArtifact(absPath);
1544
+ // ── WRITE ASIDE, THEN RENAME (delta re-review MUST FIX) ──────────────────────
1545
+ // Two earlier forms of this write were wrong in opposite directions. `O_TRUNC` wrote
1546
+ // THROUGH the existing directory entry, into whatever inode the name pointed at — the
1547
+ // whole of the hardlink attack, and a race at the final hop besides. Replacing it with
1548
+ // `unlink` + `open(O_EXCL)` fixed that and broke something `O_TRUNC` had: the previous
1549
+ // artifact was destroyed BEFORE this code knew a replacement could be created, so any
1550
+ // failure of the open — EEXIST from a concurrent deploy, a raced symlink, ENOSPC,
1551
+ // EMFILE — left NO file at all. The reviewer executed it: two concurrent deploys
1552
+ // produced 74 failed writes, and with a racer 2466 of 2500 deploys left
1553
+ // AGENTS.override.md a ZERO-BYTE file, which Codex reads as a REPLACEMENT for
1554
+ // AGENTS.md — a worktree launching with no instructions.
1555
+ //
1556
+ // A temp file plus `rename` has both properties. `rename` is atomic and replaces the
1557
+ // DIRECTORY ENTRY rather than writing through it, so: nothing is destroyed until the
1558
+ // content exists in full; a reader sees the old file or the new one, never a truncated
1559
+ // one; and a second name for the old inode, from anywhere on the filesystem, keeps the
1560
+ // OLD inode and its old bytes.
1561
+ //
1562
+ // The `O_EXCL`/`O_NOFOLLOW`/`nlink` checks are all KEPT, on the destination and on the
1563
+ // temp path both. Rename makes some of them look redundant; the evidence three reviews
1564
+ // deep is against reasoning about what this path cannot be made to do, and the temp
1565
+ // path is a NEW path in the same directory, so it gets the same containment predicate
1566
+ // the destination gets.
1567
+ const tmpPath = `${absPath}.mx-tmp-${process.pid}-${randomBytes(6).toString('hex')}`;
1568
+ const tmpRefusal = containedWriteRefusal(worktreeRoot, tmpPath);
1569
+ if (tmpRefusal)
1570
+ throw new ContainedWriteRefusal(tmpRefusal);
1571
+ // Captured LAST, immediately after the walk that just proved every component of the temp
1572
+ // path, so the gap between "the name was checked" and "the object behind it was
1573
+ // identified" is as small as this code can make it. See `directoryIdentity`.
1574
+ const parentDir = dirname(absPath);
1575
+ const parentId = directoryIdentity(parentDir);
1576
+ let installed = false;
1577
+ try {
1578
+ const fd = openSync(tmpPath, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW,
1579
+ // 0o600 until the content is written — the final mode is set with `fchmod` below,
1580
+ // so the bytes are never briefly readable more widely than they end up.
1581
+ 0o600);
1582
+ let opened;
1583
+ try {
1584
+ // ── CHECK 1 OF 3: BEFORE A SINGLE BYTE IS WRITTEN (MUST FIX) ─────────────
1585
+ // `openSync` resolved `.../.codex/<name>.mx-tmp-…` by NAME. If `.codex` became a
1586
+ // symlink to the main repo's `.codex` between the containment walk and this open,
1587
+ // the file that now exists is in the MAIN REPO. Refusing here is what makes the
1588
+ // measured worst case a zero-byte temp instead of a 4983-byte fleet-wide write —
1589
+ // the `finally` below unlinks it.
1590
+ assertSameDirectory(parentDir, parentId, absPath, 'while the temporary file was being created');
1591
+ // DEFENCE IN DEPTH. `O_EXCL` should already make this impossible, so a link count
1592
+ // other than 1 on a file this call just created means an assumption above is wrong.
1593
+ // Refuse rather than write — the destination of the extra name is unknown, and on
1594
+ // this path an unknown destination has been the main repo three reviews running.
1595
+ opened = fstatSync(fd, { bigint: true });
1596
+ if (opened.nlink !== 1n) {
1597
+ throw new ContainedWriteRefusal(`refusing to write ${absPath}: the temporary file this deploy just created ` +
1598
+ `(${tmpPath}) already has ${opened.nlink} names, so the bytes would also land outside ` +
1599
+ 'this worktree. This should be unreachable (the entry was created exclusively) — treat ' +
1600
+ 'it as a filesystem or race condition and inspect the path by hand. Nothing was ' +
1601
+ `written, and ${absPath} is untouched.`);
1602
+ }
1603
+ fchmodSync(fd, mode);
1604
+ writeFileSync(fd, content);
1605
+ }
1606
+ finally {
1607
+ closeSync(fd);
1608
+ }
1609
+ // ── CHECK 2 OF 3: THE LAST THING BEFORE THE INSTALL (MUST FIX) ─────────────
1610
+ // `renameSync` resolves BOTH names afresh. Re-identifying the directory here leaves a
1611
+ // residual window exactly one rename call wide — narrower than the two-syscall window
1612
+ // the destroy-first predecessor had, and the smallest this can be without
1613
+ // `renameat` against a directory fd, which Node does not expose.
1614
+ assertSameDirectory(parentDir, parentId, absPath, 'just before the artifact was installed');
1615
+ renameSync(tmpPath, absPath);
1616
+ installed = true;
1617
+ // ── CHECK 3 OF 3: WHAT ACTUALLY LANDED, NOT WHAT WAS INTENDED (SF-I) ───────
1618
+ // The residual window above is not zero, and there is a second way to lose this race
1619
+ // that has nothing to do with the parent directory: the TEMP PATH itself can be
1620
+ // unlinked and replaced — with a symlink, or with a hardlink to a main-repo file —
1621
+ // between the write and the rename, in which case `renameSync` installs the
1622
+ // attacker's entry at the artifact path. `rename` does not follow symlinks, so what
1623
+ // arrives is the substituted object. The reviewer executed exactly that: over 3000
1624
+ // deploys per mode, 29 installed an attacker symlink at AGENTS.override.md and 37
1625
+ // installed a hardlink to the main repo's file, and ALL 66 reported ok=true and
1626
+ // listed the artifact as written. No privilege boundary is crossed — the content went
1627
+ // to the fd's own inode, not through the link — but the deploy ASSERTED SUCCESS over
1628
+ // an artifact it did not install, and a false ok is the part this project keeps
1629
+ // paying for.
1630
+ //
1631
+ // So the install is verified rather than assumed: the entry now at `absPath` must be
1632
+ // the very inode this call wrote, and a regular file. Anything else is a FAILED write
1633
+ // (`writeFailures`, never `written`), and the mixed-state report enumerates what is
1634
+ // really on disk. The bad entry is deliberately LEFT in place: it is not this
1635
+ // function's to delete, and the next deploy's containment walk refuses a symlink or a
1636
+ // hardlink at an artifact path, so the failure stays visible and fails closed.
1637
+ let landed;
1638
+ try {
1639
+ landed = lstatSync(absPath, { bigint: true });
1640
+ }
1641
+ catch (err) {
1642
+ throw new Error(`${absPath} was renamed into place but could not then be examined ` +
1643
+ `(${err instanceof Error ? err.message : String(err)}), so this deploy cannot confirm ` +
1644
+ 'that what is at that path is the file it wrote. Treating the write as FAILED.');
1645
+ }
1646
+ if (!landed.isFile() || landed.dev !== opened.dev || landed.ino !== opened.ino) {
1647
+ throw new Error(`${absPath} is NOT the file this deploy wrote. It installed inode ${opened.ino} on ` +
1648
+ `device ${opened.dev}, and the path now holds ` +
1649
+ `${landed.isSymbolicLink() ? 'a SYMLINK' : landed.isDirectory() ? 'a DIRECTORY' : !landed.isFile() ? 'a non-regular file' : `inode ${landed.ino} on device ${landed.dev}`}` +
1650
+ '. The temporary file was substituted between the write and the rename, or the ' +
1651
+ 'directory was replaced under it. The bytes went to the file this deploy created, so ' +
1652
+ 'nothing outside the worktree was written through it — but the artifact at that path ' +
1653
+ 'is NOT this deploy\'s output and the deploy must not report it as written. Remove the ' +
1654
+ 'entry at that path by hand and redeploy.');
1655
+ }
1656
+ }
1657
+ finally {
1658
+ // NO `.mx-tmp-*` LITTER, on any failure path — the refusal above, a write error, a
1659
+ // failed rename, or an open that never created the file at all (the unlink then
1660
+ // fails and is ignored, which is the correct outcome for a file that is not there).
1661
+ if (!installed) {
1662
+ try {
1663
+ unlinkSync(tmpPath);
1664
+ }
1665
+ catch {
1666
+ /* best effort — the error being propagated is the report that matters */
1667
+ }
1668
+ }
1669
+ }
1188
1670
  }
1189
1671
  /**
1190
1672
  * Deploy every Codex config artifact into the worktree. Idempotent — each file is
@@ -1193,6 +1675,30 @@ function writeFileEnsuringDir(absPath, content) {
1193
1675
  export function deployCodexConfig(opts) {
1194
1676
  const warnings = [];
1195
1677
  const written = [];
1678
+ const writeRefusals = [];
1679
+ const writeFailures = [];
1680
+ /**
1681
+ * Record a write failure. A CONTAINMENT refusal is not the same event as an I/O error
1682
+ * and must not be flattened into "could not write X": it means the bytes were aimed at
1683
+ * a destination outside this worktree, and the operator has to be told where.
1684
+ *
1685
+ * BOTH KINDS FAIL THE DEPLOY (delta re-review MUST FIX). The non-containment branch used
1686
+ * to push one warning line and nothing else, so a deploy that wrote no hooks file — or
1687
+ * left AGENTS.override.md, which Codex reads INSTEAD of AGENTS.md, absent — still
1688
+ * reported ok=true and exit 0. The error's own text is kept: "could not write X" without
1689
+ * the errno tells an operator nothing about whether to retry, free space, or fix a
1690
+ * permission.
1691
+ */
1692
+ const noteWriteFailure = (err, fallback) => {
1693
+ if (err instanceof ContainedWriteRefusal) {
1694
+ writeRefusals.push(err.message);
1695
+ warnings.push(err.message);
1696
+ return;
1697
+ }
1698
+ const detail = `${fallback} (${err instanceof Error ? err.message : String(err)})`;
1699
+ writeFailures.push(detail);
1700
+ warnings.push(detail);
1701
+ };
1196
1702
  const configPath = join(opts.worktreePath, CODEX_CONFIG_FILENAME);
1197
1703
  try {
1198
1704
  writeFileEnsuringDir(configPath, buildCodexConfigToml({
@@ -1205,11 +1711,11 @@ export function deployCodexConfig(opts) {
1205
1711
  if (d.level === 'warn')
1206
1712
  warnings.push(d.message);
1207
1713
  },
1208
- }));
1714
+ }), opts.worktreePath);
1209
1715
  written.push(CODEX_CONFIG_FILENAME);
1210
1716
  }
1211
- catch {
1212
- warnings.push(`Could not write ${CODEX_CONFIG_FILENAME} — Codex has no MemNexus MCP server configured.`);
1717
+ catch (err) {
1718
+ noteWriteFailure(err, `Could not write ${CODEX_CONFIG_FILENAME} — Codex has no MemNexus MCP server configured.`);
1213
1719
  }
1214
1720
  // Each ported guard's script must actually be on disk. Since the #4227 G-7 fix the
1215
1721
  // wrapper fails CLOSED when it is not, so an absent script no longer means a silently
@@ -1243,13 +1749,84 @@ export function deployCodexConfig(opts) {
1243
1749
  // It also restores the stated invariant that the generated file is byte-identical in
1244
1750
  // every worktree: a per-worktree proven list gives every worktree a distinct hash and
1245
1751
  // a separate human trust grant.
1752
+ // ── DEPLOYING IS NOT INERT (#4875 MF-2) ──────────────────────────────────────
1753
+ // The file was overwritten without ever being READ, and the header called the result
1754
+ // inert on the grounds that the artifacts do nothing until a human grants trust. That
1755
+ // is true of a FIRST deploy and false of a redeploy: Codex binds each trust record to
1756
+ // the entry's content, so a redeploy whose bytes differ makes every existing grant for
1757
+ // this file stale, and Codex says NOTHING when it declines to run an entry whose hash
1758
+ // stopped matching — including in a session that is running right now. So the bytes
1759
+ // are read first and compared after, and a change is reported.
1246
1760
  const hooksPath = join(opts.worktreePath, CODEX_HOOKS_FILENAME);
1761
+ // ONE resolver, honouring CODEX_HOME (SF-A). See `resolveCodexHome`.
1762
+ const homeResolution = opts.codexHome ? { home: opts.codexHome } : resolveCodexHome();
1763
+ let codexHome = null;
1764
+ if ('home' in homeResolution) {
1765
+ codexHome = homeResolution.home;
1766
+ }
1767
+ else {
1768
+ warnings.push(`The Codex config directory could not be located: ${homeResolution.error} No existing ` +
1769
+ 'hook-trust grant can be read, so this deploy cannot tell whether it just invalidated one. ' +
1770
+ 'Treat every grant for this worktree as UNVERIFIED: `mx-agent codex trust-keys`.');
1771
+ }
1772
+ let hooksBefore = null;
1247
1773
  try {
1248
- writeFileEnsuringDir(hooksPath, buildCodexHooksJson({ worktreePath: opts.worktreePath }));
1249
- written.push(CODEX_HOOKS_FILENAME);
1774
+ hooksBefore = readFileSync(hooksPath);
1250
1775
  }
1251
1776
  catch {
1252
- warnings.push(`Could not write ${CODEX_HOOKS_FILENAME} — no containment guards are registered.`);
1777
+ hooksBefore = null;
1778
+ }
1779
+ try {
1780
+ writeFileEnsuringDir(hooksPath, buildCodexHooksJson({ worktreePath: opts.worktreePath }), opts.worktreePath);
1781
+ written.push(CODEX_HOOKS_FILENAME);
1782
+ }
1783
+ catch (err) {
1784
+ noteWriteFailure(err, `Could not write ${CODEX_HOOKS_FILENAME} — no containment guards are registered.`);
1785
+ }
1786
+ let hooksBytesChanged = false;
1787
+ if (hooksBefore !== null) {
1788
+ try {
1789
+ hooksBytesChanged = !readFileSync(hooksPath).equals(hooksBefore);
1790
+ }
1791
+ catch {
1792
+ // Unreadable after a write we believed succeeded. Treat it as changed: the
1793
+ // conservative direction here is "your grants may be stale", never "they are fine".
1794
+ hooksBytesChanged = true;
1795
+ }
1796
+ }
1797
+ // Only grants that ALREADY EXISTED can be invalidated. A first deploy into a worktree
1798
+ // with no records has nothing to make stale, and warning there would train the
1799
+ // operator to scroll past the line that matters.
1800
+ const priorGrants = codexHome === null
1801
+ ? []
1802
+ : [...readCodexTrustState(codexHome).records]
1803
+ .filter(([key, record]) => key.startsWith(`${hooksPath}:`) && record.enabled && record.hash !== '')
1804
+ .map(([key]) => key);
1805
+ const hookTrustInvalidated = hooksBefore !== null && hooksBytesChanged && priorGrants.length > 0;
1806
+ // ── AN UNREADABLE "BEFORE" IS NOT A CLEAN BILL OF HEALTH (security review SF-B) ──
1807
+ // `priorGrants` was computed as `[]` whenever the hooks file could not be read before
1808
+ // the write, so a deploy into a worktree whose hooks.json was absent or unreadable — a
1809
+ // deleted file, a permission error, a half-finished checkout — reported
1810
+ // `hookTrustInvalidated = false` while live grants for that exact path sat in the Codex
1811
+ // config. The bytes just written may or may not match them; Codex says nothing either
1812
+ // way, and this path has no hashes to compare. Unknown is reported as unknown.
1813
+ const hookTrustUnverifiable = codexHome === null || (hooksBefore === null && priorGrants.length > 0);
1814
+ if (hooksBefore === null && priorGrants.length > 0) {
1815
+ warnings.push(`${CODEX_HOOKS_FILENAME} could NOT be read before this deploy (absent or unreadable), yet ` +
1816
+ `${priorGrants.length} hook-trust grant${priorGrants.length === 1 ? '' : 's'} already exist ` +
1817
+ `for its path (${priorGrants.join(', ')}). Whether those grants match the bytes just ` +
1818
+ 'written cannot be determined here — Codex binds each record to the entry content it was ' +
1819
+ 'granted for and SILENTLY declines to run an entry whose hash stopped matching. Treat them ' +
1820
+ 'as UNVERIFIED, not as current: `mx-agent codex trust-keys` compares them against Codex\'s ' +
1821
+ 'own hashes.');
1822
+ }
1823
+ if (hookTrustInvalidated) {
1824
+ warnings.push(`${CODEX_HOOKS_FILENAME} was REWRITTEN with different bytes, so every existing hook-trust ` +
1825
+ `grant for this file is now STALE (${priorGrants.length} record${priorGrants.length === 1 ? '' : 's'}: ` +
1826
+ `${priorGrants.join(', ')}). Codex binds each trust record to the entry content it was ` +
1827
+ 'granted for, and Codex silently does not run an entry whose hash stopped matching — ' +
1828
+ 'including in any session running right now, which will keep reporting nothing while its ' +
1829
+ 'guards do not fire. Re-grant before the next launch: `mx-agent codex trust-keys`.');
1253
1830
  }
1254
1831
  const overridePath = join(opts.worktreePath, AGENTS_OVERRIDE_FILENAME);
1255
1832
  const override = buildAgentsOverride({
@@ -1276,11 +1853,68 @@ export function deployCodexConfig(opts) {
1276
1853
  `markers but NO canonical instructions.`);
1277
1854
  }
1278
1855
  try {
1279
- writeFileEnsuringDir(overridePath, override.content);
1856
+ writeFileEnsuringDir(overridePath, override.content, opts.worktreePath);
1280
1857
  written.push(AGENTS_OVERRIDE_FILENAME);
1281
1858
  }
1282
- catch {
1283
- warnings.push(`Could not write ${AGENTS_OVERRIDE_FILENAME} — this Codex session has no local override context.`);
1859
+ catch (err) {
1860
+ noteWriteFailure(err, `Could not write ${AGENTS_OVERRIDE_FILENAME} — this Codex session has no local override context.`);
1861
+ }
1862
+ // ── A REFUSAL PART-WAY THROUGH LEAVES A MIXED WORKTREE (security review INFO) ──
1863
+ // Each artifact is written independently, so a refusal on the second one leaves the
1864
+ // first on disk: an instruction file with no hooks file, or a config with neither.
1865
+ // The artifacts are NOT rolled back — restoring the previous bytes would have to undo
1866
+ // a hooks-file overwrite whose trust consequences have already been measured and
1867
+ // reported above, and a restore that itself failed would leave a state nothing here
1868
+ // could describe. What the operator gets instead is the state named outright, so
1869
+ // "some files appeared" is never read as "most of the deploy worked".
1870
+ //
1871
+ // ── AND IT REPORTS WHAT IS ON DISK, NOT WHAT IT ASSUMES (security review SF-1) ──
1872
+ // The line used to say "the refused ones are whatever was there before". The reviewer
1873
+ // captured that sentence on a real refusal where the refused artifact DID NOT EXIST —
1874
+ // the same deploy had deleted it. The write is atomic now, so "unchanged" is true again
1875
+ // for the refusal case, but a warning about a mixed worktree is worth exactly what its
1876
+ // description of that worktree is worth, so nothing here is asserted: all three
1877
+ // artifacts are MEASURED after the writes and the measurement is what gets printed.
1878
+ // The gate is refusals OR failures: a non-containment failure produced a mixed worktree
1879
+ // with no partial-deploy line at all (executed: a directory at .codex/hooks.json →
1880
+ // ok=true, no warning).
1881
+ let incompleteDeployMessage = null;
1882
+ const notWritten = writeRefusals.length + writeFailures.length;
1883
+ if (notWritten > 0) {
1884
+ const measured = [CODEX_CONFIG_FILENAME, CODEX_HOOKS_FILENAME, AGENTS_OVERRIDE_FILENAME]
1885
+ .map((rel) => {
1886
+ const path = join(opts.worktreePath, rel);
1887
+ let st;
1888
+ try {
1889
+ st = lstatSync(path);
1890
+ }
1891
+ catch (err) {
1892
+ const code = err.code ?? 'unknown';
1893
+ return `${rel}: ${code === 'ENOENT' ? 'ABSENT' : `could not be examined (${code})`}`;
1894
+ }
1895
+ if (st.isSymbolicLink())
1896
+ return `${rel}: a SYMLINK, not a file`;
1897
+ if (st.isDirectory())
1898
+ return `${rel}: a DIRECTORY, not a file`;
1899
+ if (!st.isFile())
1900
+ return `${rel}: not a regular file`;
1901
+ // EMPTY IS NAMED SEPARATELY. A zero-byte AGENTS.override.md is the worst of these
1902
+ // states and the least visible: Codex reads that file INSTEAD of AGENTS.md, so the
1903
+ // session starts with no instructions rather than with an obvious error.
1904
+ return st.size === 0 ? `${rel}: present but EMPTY (0 bytes)` : `${rel}: present, ${st.size} bytes`;
1905
+ })
1906
+ .join('; ');
1907
+ const head = written.length > 0
1908
+ ? `PARTIAL DEPLOY: ${written.length} artifact${written.length === 1 ? ' was' : 's were'} ` +
1909
+ `written (${written.join(', ')}) and ${notWritten} was not`
1910
+ : `DEPLOY FAILED: no artifact was written; ${notWritten} write${notWritten === 1 ? '' : 's'} ` +
1911
+ 'did not complete';
1912
+ incompleteDeployMessage =
1913
+ `${head}. The worktree is in a MIXED state and it must not be launched. State measured on ` +
1914
+ 'disk at the end of this ' +
1915
+ `deploy: ${measured}. Fix the refusals and failures named above and redeploy; the deploy is ` +
1916
+ 'idempotent, so a clean rerun replaces all of them.';
1917
+ warnings.push(incompleteDeployMessage);
1284
1918
  }
1285
1919
  // Measured AFTER the override is written, since that file is the one Codex reads.
1286
1920
  const chain = measureInstructionChain(opts.worktreePath, PROJECT_DOC_MAX_BYTES);
@@ -1289,8 +1923,103 @@ export function deployCodexConfig(opts) {
1289
1923
  `project_doc_max_bytes — it will be TRUNCATED silently. Per-file sizes: ` +
1290
1924
  `${chain.files.map((f) => `${f.path} ${f.bytes}B${f.read ? ' (read)' : ' (ignored)'}`).join(', ')}.`);
1291
1925
  }
1292
- const trust = codexHookTrustPreconditions({ worktreePath: opts.worktreePath });
1293
- return { written, warnings, chain, trust };
1926
+ const trust = codexHookTrustPreconditions({
1927
+ worktreePath: opts.worktreePath,
1928
+ // An unlocatable config directory reads as no records at all, which fails closed:
1929
+ // every required key is reported ungranted rather than granted.
1930
+ codexHome: codexHome ?? '',
1931
+ // This call has NO observed hashes — reading them costs a `codex app-server`
1932
+ // invocation the deploy path cannot afford — so it cannot detect staleness on its
1933
+ // own. It does not have to: this function just changed the bytes and knows it.
1934
+ bytesChanged: hookTrustInvalidated,
1935
+ grantsUnverifiable: hookTrustUnverifiable,
1936
+ });
1937
+ return {
1938
+ written,
1939
+ warnings,
1940
+ chain,
1941
+ trust,
1942
+ hookTrustInvalidated,
1943
+ hookTrustUnverifiable,
1944
+ writeRefusals,
1945
+ writeFailures,
1946
+ hasBehavioralBlock: override.hasBehavioralBlock,
1947
+ incompleteDeployMessage,
1948
+ };
1949
+ }
1950
+ /**
1951
+ * The refusal a caller raises when a deploy did not write every artifact (Gap 2).
1952
+ *
1953
+ * ─── WHY THE LAUNCH PATH NEEDED ITS OWN REFUSAL ───────────────────────────────
1954
+ * `deployCodexConfig` already reported the mixed state, and `mx-agent codex deploy-config`
1955
+ * already exits non-zero on it. `CodexAdapter.deployConfig` only PRINTED it. Executed with
1956
+ * `MX_AGENT_CODEX_PHASE1_DEV=1` — the documented hatch, and the only way a Codex session
1957
+ * runs at all while G-7 is unpassed: a deploy in which ALL THREE artifacts failed printed
1958
+ * `DEPLOY FAILED … must not be launched`, and then `assertLaunchAllowed` returned ALLOWED.
1959
+ * The session would have started with no containment guards registered, no declared
1960
+ * sandbox_mode or approval_policy, and no MemNexus MCP server — the exact configuration
1961
+ * every guardrail in this module exists to put in place.
1962
+ *
1963
+ * `refreshGuardProof` re-hashes `.codex/hooks.json` after the deploy, so a failed hooks
1964
+ * write does lose the guard proof and the G-7 gate catches THAT artifact. It binds
1965
+ * nothing about `config.toml` or `AGENTS.override.md`, and the dev hatch returns before
1966
+ * the proof is consulted anyway.
1967
+ *
1968
+ * Same shape as `instructionChainOverBudgetMessage`: one text, both refusal sites, and the
1969
+ * state it quotes is the state that was MEASURED rather than a second description of it.
1970
+ */
1971
+ export function deployIncompleteMessage(result, refusalPrefix) {
1972
+ const detail = result.incompleteDeployMessage ??
1973
+ `${result.writeRefusals.length} artifact write(s) were refused and ` +
1974
+ `${result.writeFailures.length} failed.`;
1975
+ return `${refusalPrefix}: ${detail}`;
1976
+ }
1977
+ /** Render a deploy result as the lines both deploy callers print, in a fixed order. */
1978
+ export function codexDeployReportLines(result) {
1979
+ const lines = [];
1980
+ // The version every guardrail was verified against, named AT DEPLOY (security review
1981
+ // INFO). `prove-guards` already refuses on a mismatch, but that is one command later,
1982
+ // after the operator has hand-granted eight trust records; an operator on a different
1983
+ // codex build should learn it while the artifacts are being written, not afterwards.
1984
+ // This is a STATEMENT, not a probe — nothing here reads the installed version.
1985
+ lines.push({
1986
+ level: 'info',
1987
+ text: `Generated for codex-cli ${VERIFIED_CODEX_VERSION} — the one version these guardrails were ` +
1988
+ 'verified on. On any other version the hook, trust and sandbox behaviour they rest on is ' +
1989
+ 'unverified.',
1990
+ });
1991
+ for (const file of result.written)
1992
+ lines.push({ level: 'info', text: `Deployed ${file} (codex)` });
1993
+ for (const warning of result.warnings)
1994
+ lines.push({ level: 'warn', text: warning });
1995
+ for (const precondition of result.trust) {
1996
+ if (!precondition.satisfied) {
1997
+ lines.push({
1998
+ level: 'warn',
1999
+ text: `codex hook precondition unmet (${precondition.id}): ${precondition.detail}`,
2000
+ });
2001
+ }
2002
+ }
2003
+ return lines;
2004
+ }
2005
+ /**
2006
+ * The over-budget refusal, in ONE place (#4875).
2007
+ *
2008
+ * Codex truncates the instruction file silently at `project_doc_max_bytes`, so an
2009
+ * over-budget deploy produces a file whose tail nobody can see. Both callers REFUSE on
2010
+ * it rather than warning — the deploy-only path included, because the artifact it just
2011
+ * wrote is exactly the one that would be truncated, and a deploy that reports success
2012
+ * on it would send an operator on to grant trust for a configuration that cannot be
2013
+ * read in full.
2014
+ *
2015
+ * `refusalPrefix` differs only because the two callers are refusing different actions.
2016
+ */
2017
+ export function instructionChainOverBudgetMessage(chain, refusalPrefix) {
2018
+ return (`${refusalPrefix}: ${chain.readFile} is ${chain.bytes} bytes, over the ${chain.cap}-byte ` +
2019
+ 'project_doc_max_bytes. Codex truncates it SILENTLY, so the session would run on ' +
2020
+ 'instructions with an unknown tail missing. Shrink the instruction file (AGENTS.md and the ' +
2021
+ 'worktree-local override are folded into one file under codex), or run this team on Claude ' +
2022
+ 'with `mx-agent start <team> --runtime claude`.');
1294
2023
  }
1295
2024
  /** Does the worktree carry a generated Codex config tree? Used by tests and doctor-style checks. */
1296
2025
  export function hasCodexConfig(worktreePath) {