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

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 +1832 -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 +1098 -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,733 @@ 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
+ * ON THE WORD "PREDECESSOR" (#4897, label correction): the round-7 reviewer rebuilt both
1488
+ * comparison arms from source rather than trusting supplied build snapshots, and found the
1489
+ * arm the implementer had LABELLED as commit `85fe36faf` was a hand-made hybrid, not that
1490
+ * commit. Re-measured against the real commit, the conclusion was UNCHANGED — the numbers
1491
+ * above and the containment result they justify stand. The label was wrong; the finding
1492
+ * was not.
1493
+ *
1494
+ * Comparing `{dev, ino}` against the identity captured before the open answers the
1495
+ * question the name cannot: is this still the SAME directory, or a different one wearing
1496
+ * the same name. It is checked twice — once with the temp file open and not yet written,
1497
+ * so a swap turns a 4983-byte fleet-wide write into a zero-byte temp that is then
1498
+ * unlinked; and once immediately before `renameSync`, which narrows the residual window to
1499
+ * the rename call itself, at or below the width the predecessor had.
1500
+ *
1501
+ * THIS IS A NARROWING, NOT A CLOSURE, AND MUST NOT BE DESCRIBED AS ONE. The complete fix
1502
+ * is to hold a file descriptor on the directory and use `openat`/`renameat` against it, so
1503
+ * the kernel resolves against the directory OBJECT and no name is ever re-resolved. Node
1504
+ * exposes neither. That residual stays in known-issues; step 4 at the call site is what
1505
+ * keeps the REPORT honest when the residual is hit.
1506
+ *
1507
+ * THE RESIDUAL, IN THE CORRECTED WORDING (#4897 SF-K). It used to be stated as "no bytes
1508
+ * reach a path outside the worktree". One word short: no bytes reach a LIVE path outside
1509
+ * the worktree — one that something reads, loads or executes. Bytes CAN reach an INERT
1510
+ * one, when the directory is swapped before the `open` and RESTORED before the first
1511
+ * check: the temp file is then created in the other directory under a `.mx-tmp-*` name
1512
+ * nothing opens. The rate is of ORDER 1 in 10^3-10^4 deploys at a roughly 5-microsecond
1513
+ * swapper hold. That is an order-of-magnitude ESTIMATE, not a measured rate.
1514
+ *
1515
+ * ON THAT NUMBER'S PROVENANCE (#4897 round 12). It read "Measured 1 in 6,000 deploys"
1516
+ * until this commit. The round-12 security review could not establish which measurement
1517
+ * round produced that figure, and one candidate window (round 10) ran with two mutations
1518
+ * live in this file, one of which — a dropped `ino` comparison in `sameDirectoryStat` —
1519
+ * fails SILENTLY, so numbers from that window are not trustworthy. The residual measured
1520
+ * here is most likely unperturbed by that mutation, because this path is governed by
1521
+ * `renameSync` failing ENOENT and because `tempResidueNote` compares dev/ino/isDirectory
1522
+ * INLINE rather than through `sameDirectoryStat` — but "most likely unperturbed" does not
1523
+ * source a four-significant-figure claim, so the claim is downgraded to what it can carry.
1524
+ *
1525
+ * RE-MEASURING WAS CONSIDERED AND REJECTED, on evidence. A 1-in-6,000 event sits in the
1526
+ * p99.98 tail, and at a 5-microsecond hold this machine's scheduler overshoots that hold
1527
+ * 2.1x at p99, 12x at p99.9 and 54x at worst. The tail that sets the rate is therefore
1528
+ * dominated by preemption, not by the nominal hold: a fresh figure would measure the
1529
+ * machine's contention on the day, and would have exactly the unsourceable precision this
1530
+ * note exists to remove. The estimate's job is to ORDER the risk, and no handling decision
1531
+ * turns on the second digit — the window is real, rare, and fail-closed at any rate in
1532
+ * this range. The deploy still fails closed and reports nothing as written;
1533
+ * `tempResidueNote` names the path so the litter can be found.
1534
+ */
1535
+ function directoryIdentity(dir) {
1536
+ const st = lstatSync(dir, { bigint: true });
1537
+ if (!st.isDirectory() || st.isSymbolicLink()) {
1538
+ throw new ContainedWriteRefusal(`refusing to write into ${dir}: it is not a real directory. Nothing was written.`);
1539
+ }
1540
+ return { dev: st.dev, ino: st.ino };
1541
+ }
1542
+ /**
1543
+ * Refuse unless `dir` is still the very directory `expected` identifies.
1544
+ *
1545
+ * All three ways this can fail — the name now resolves to a different directory, to a
1546
+ * SYMLINK or other non-directory, or to nothing this process can examine — are ONE event
1547
+ * as far as the operator is concerned: the directory that passed containment is not the
1548
+ * directory about to be written into. They share a message for that reason, with the
1549
+ * measured difference appended, and every one of them is fail-closed.
1550
+ */
1551
+ function sameDirectoryStat(st, expected) {
1552
+ // ── ONE COMPARISON, TWO CALLERS (round 9 SF-A/SF-C) ────────────────────────
1553
+ // The identity test lives here rather than being written out at each call site so that
1554
+ // every clause of it has ONE set of pins. The `isDirectory()` clause is not redundant
1555
+ // beside `{dev, ino}`: an inode NUMBER is not a durable identity, so a directory that is
1556
+ // removed and replaced by a non-directory taking its number compares equal on both
1557
+ // numbers and differs only here.
1558
+ return st.dev === expected.dev && st.ino === expected.ino && st.isDirectory();
1559
+ }
1560
+ function assertSameDirectory(dir, expected, absPath, when) {
1561
+ let observed;
1562
+ try {
1563
+ const st = lstatSync(dir, { bigint: true });
1564
+ if (sameDirectoryStat(st, expected))
1565
+ return;
1566
+ observed = st.isSymbolicLink()
1567
+ ? 'a SYMLINK, which resolves wherever its target points'
1568
+ : !st.isDirectory()
1569
+ ? 'not a directory at all'
1570
+ : `device ${st.dev}/inode ${st.ino}`;
1571
+ }
1572
+ catch (err) {
1573
+ observed = `unexaminable (${err instanceof Error ? err.message : String(err)})`;
1574
+ }
1575
+ throw new ContainedWriteRefusal(`refusing to write ${absPath}: the directory ${dir} was REPLACED ${when} — it was ` +
1576
+ `device ${expected.dev}/inode ${expected.ino} when containment passed, and is now ` +
1577
+ `${observed}. The name still resolves, to something this deploy never checked, so the ` +
1578
+ 'bytes would land outside this worktree. Under OpenAI bug #27133 the main repo\'s ' +
1579
+ '.codex/hooks.json governs every Codex session in the fleet, and that is what a swapped ' +
1580
+ '.codex points at. Nothing was installed.');
1581
+ }
1582
+ /**
1583
+ * The same question `assertSameDirectory` asks, ANSWERED rather than thrown (round 9 MUST
1584
+ * FIX 2).
1585
+ *
1586
+ * `assertSameDirectory` is written for the two call sites that run BEFORE the artifact is
1587
+ * installed, and its message says so in two places — "the bytes would land outside this
1588
+ * worktree" and "Nothing was installed." The install acceptance called it too, from a point
1589
+ * where `renameSync` has already returned and `installed` is true, so a directory swapped
1590
+ * during verification produced a refusal that told the operator nothing was installed while
1591
+ * a 4983-byte artifact sat on disk, and filed it under `writeRefusals` (a containment
1592
+ * refusal) rather than `writeFailures` (what it is: a post-install directory swap). The
1593
+ * reviewer executed it.
1594
+ *
1595
+ * So the acceptance asks the question as a PREDICATE and returns false, which lets the
1596
+ * caller's own "NOT the file this deploy wrote" error fire — that message is written for a
1597
+ * state in which something IS at the path, and it is a plain `Error`, so it classifies as a
1598
+ * write FAILURE. Fail-closed is unchanged: every way of not being able to answer — the
1599
+ * directory moved, it is no longer a directory, it cannot be examined — returns false.
1600
+ *
1601
+ * The COMPARISON is shared with `assertSameDirectory` rather than restated (SF-C): the two
1602
+ * differ only in what they do with the answer, and a second copy of the clauses would be a
1603
+ * second set of mutants to pin.
1604
+ */
1605
+ function isStillSameDirectory(dir, expected) {
1606
+ try {
1607
+ return sameDirectoryStat(lstatSync(dir, { bigint: true }), expected);
1608
+ }
1609
+ catch {
1610
+ return false;
1611
+ }
1612
+ }
1613
+ /**
1614
+ * ── AN HONEST CONCURRENT REDEPLOY IS NOT A FAILED WRITE (security review SF-L) ─
1615
+ *
1616
+ * The install check below asks whether the entry at `absPath` is the very inode this call
1617
+ * renamed there. There is one way for that to be FALSE with nothing wrong: a second
1618
+ * legitimate deploy renames ITS artifact — byte-identical, since both deploys generate the
1619
+ * same content — into the same path between this deploy's `renameSync` and its `lstat`.
1620
+ * The file on disk is correct, and the deploy reported it as a failed write. Since #4896
1621
+ * made any write failure refuse the launch, that turned a benign race into `mx-agent start`
1622
+ * exiting 1, in exactly the scenario the rename design was introduced to make safe.
1623
+ * Measured 0 in 4,500 honest concurrent deploys, but deterministically reproducible.
1624
+ *
1625
+ * So a different inode is accepted only when what is at the path is INDISTINGUISHABLE from
1626
+ * this deploy's own output: a regular file, with exactly ONE name, whose bytes equal the
1627
+ * bytes this deploy wrote. That preserves SF-I unchanged — a substituted SYMLINK fails
1628
+ * `isFile()`, and a substituted HARDLINK to a main-repo file fails `nlink === 1` even if
1629
+ * an attacker arranges for its content to match. The re-open is `O_NOFOLLOW` and its
1630
+ * `fstat` is compared against the entry that was just `lstat`ed, so the acceptance is
1631
+ * decided on one object rather than on a name examined twice.
1632
+ *
1633
+ * ── THE RE-OPEN MUST NOT BE ABLE TO BLOCK (round 8 MUST FIX) ─────────────────
1634
+ * `O_RDONLY | O_NOFOLLOW` alone is not a safe way to open a name an attacker can control.
1635
+ * `open` on a FIFO for reading BLOCKS IN THE KERNEL until a writer arrives, and there is
1636
+ * never a writer here, so a FIFO substituted into the `lstat` → `open` window hangs
1637
+ * `openSync` — and `openSync` is synchronous, so it hangs `mx-agent start` forever: no
1638
+ * timeout fires, nothing is logged, nothing is written. The reviewer reproduced it; even
1639
+ * vitest's own 20-second test timeout never fired and the run had to be killed from
1640
+ * outside. That is a REGRESSION — before this acceptance existed the same substitution
1641
+ * produced a clean fail-closed refusal, because nothing re-opened the name at all.
1642
+ *
1643
+ * `O_NONBLOCK` makes the open return immediately whatever is behind the name; the
1644
+ * `!open.isFile()` check below then rejects the FIFO and the deploy falls through to the
1645
+ * normal "NOT the file this deploy wrote" refusal. It has no effect on the regular file
1646
+ * this path is actually for — `O_NONBLOCK` is meaningful only for FIFOs, devices and
1647
+ * sockets, and `read` on a regular fd ignores it.
1648
+ *
1649
+ * ── AND `!open.isFile()` IS LOAD-BEARING, NOT REDUNDANT (round 9 MUST FIX 1) ──
1650
+ * The round-8 commit claimed this check could never be the sole cause of a rejection once
1651
+ * the `{dev, ino}` binding was present, "because an identical inode has an identical type".
1652
+ * THAT CLAIM IS WITHDRAWN — it is false. An inode NUMBER is not a durable identity: unlink
1653
+ * the object it names and the number is free, and the next object created in that
1654
+ * filesystem can take it and be of ANY type. The reviewer built it with real syscalls only
1655
+ * (RP14, pinned in the race tests): at the verifying `lstat` the attacker unlinks the
1656
+ * artifact and creates a FIFO, retrying until the FIFO takes the same inode number — 322 of
1657
+ * 400 trials on this filesystem — and pre-buffers this deploy's exact bytes into it, so
1658
+ * `readFileSync` on the non-blocking fd drains the buffer and sees a clean EOF. Every other
1659
+ * check agrees: nlink 1, mode 0644, uid, size and `{dev, ino}` all match. With
1660
+ * `!open.isFile()` removed the deploy certifies a FIFO as `AGENTS.override.md`, `ok=true`,
1661
+ * artifact listed as written. The type check on the OPEN DESCRIPTOR is the only thing that
1662
+ * refuses it.
1663
+ *
1664
+ * ── THE ACCEPTANCE IS ANCHORED, NOT FREE-FLOATING (round 8 SF-1) ─────────────
1665
+ * As first written this predicate asked only "is this a lone regular file holding my
1666
+ * bytes" — a question a byte-identical file ANYWHERE ON THE FILESYSTEM answers yes to. The
1667
+ * reviewer executed it: a byte-identical copy placed in a stand-in main repo, then
1668
+ * `<worktree>/.codex` swapped for a symlink to that directory, and the deploy reported the
1669
+ * artifact as WRITTEN. The pre-SF-L code refused. Content equality was doing work it cannot
1670
+ * do: it says the bytes are right, not that the PATH is one this deploy is allowed to have
1671
+ * written.
1672
+ *
1673
+ * So the acceptance re-establishes both anchors before it will say yes:
1674
+ * 1. `isStillSameDirectory` — the parent is still the very directory whose `{dev, ino}`
1675
+ * was captured before the open. This is the check the symlinked-`.codex` probe
1676
+ * defeats. It RETURNS FALSE rather than throwing: by the time the acceptance runs the
1677
+ * rename has already happened, so this is not "nothing was installed, and the bytes
1678
+ * would land outside the worktree" — it is an installed artifact that is not this
1679
+ * deploy's, which is a write FAILURE and is reported as one (round 9 MUST FIX 2).
1680
+ * 2. `containedWriteRefusal` — the whole path from the worktree root down still resolves
1681
+ * inside this worktree, with no symlink and no second name anywhere along it.
1682
+ *
1683
+ * Both run BEFORE the open, so the name is judged before the object behind it is touched.
1684
+ * That leaves a window of its own — the walk resolves names, and the `open` resolves them
1685
+ * again — which is exactly what `O_NOFOLLOW` on the open is for, and what the round-8
1686
+ * substitution tests exercise: a symlink planted between the walk and the open is refused
1687
+ * by the open, not by the walk.
1688
+ *
1689
+ * ── WHAT MOVING THE WALK ABOVE THE OPEN COST (round 9 SF-D) ──────────────────
1690
+ * The round-8 commit said behaviour was "otherwise unchanged" by that reorder. The ORDER is
1691
+ * sound — the binding is not weakened, since `O_NOFOLLOW` and the `fstat`-vs-`lstat`
1692
+ * comparison both still judge the object the open returns — but the reorder is not free:
1693
+ * the window between the parent-identity check and the `open` is now a full path walk wide,
1694
+ * roughly 4–6 extra `lstat` syscalls, where before it was one `containedWriteRefusal` call
1695
+ * shorter. Nothing is WRITTEN in that window — the acceptance only reads — so widening it
1696
+ * has no write consequence, and everything the window admits is what `O_NOFOLLOW` and the
1697
+ * `{dev, ino}` binding exist to refuse. The window moved; it did not vanish.
1698
+ *
1699
+ * ── AND THE PERMISSIONS, WHICH ARE PART OF THE ARTIFACT (round 8 SF-2) ───────
1700
+ * `modeForInstalledArtifact` exists to guarantee that nothing this deploy installs is
1701
+ * group- or other-writable. The acceptance checked type, link count and bytes — not mode,
1702
+ * not owner — so it accepted a file that broke the very invariant the write path enforces.
1703
+ * The reviewer executed it (probe P2): a distinct regular file with identical bytes at mode
1704
+ * 0666 was accepted, `ok=true`, artifact reported as written, and `AGENTS.override.md` left
1705
+ * WORLD-WRITABLE on disk. Codex reads `AGENTS.override.md` as a REPLACEMENT for `AGENTS.md`,
1706
+ * so that is a locally rewritable instruction file for every session in the worktree.
1707
+ *
1708
+ * The mode is compared for EQUALITY with the mode this deploy computed, not merely for
1709
+ * "no wider than", because a genuine concurrent deploy runs the same deterministic
1710
+ * `modeForInstalledArtifact` over the same prior state and arrives at the same number — so
1711
+ * equality costs the benign race nothing, which is the whole point of SF-L. Owner is
1712
+ * checked for the same reason: a file this process did not create is not this deploy's
1713
+ * output however its bytes read.
1714
+ */
1715
+ function landedIsThisDeploysOwnContent(absPath, landed, content, worktreeRoot, parentDir, parentId, mode) {
1716
+ if (!isStillSameDirectory(parentDir, parentId))
1717
+ return false;
1718
+ if (!landed.isFile() || landed.nlink !== 1n)
1719
+ return false;
1720
+ // ── SIZE BEFORE BYTES (round 8 SF-4) ───────────────────────────────────────
1721
+ // `readFileSync(fd)` below reads and allocates the WHOLE landed file, and the landed
1722
+ // file is attacker-influenced — this path only runs because something other than this
1723
+ // deploy put an entry at the artifact path. The generated artifacts are 1.3–5 KB, so a
1724
+ // file of any other size cannot be this deploy's output and there is no reason to read
1725
+ // it. Exposure without this check was bounded but real: Node throws
1726
+ // ERR_FS_FILE_TOO_LARGE somewhere above 2 GB, so a file just under that was read and
1727
+ // allocated in full before the comparison rejected it.
1728
+ if (landed.size !== BigInt(Buffer.byteLength(content, 'utf-8')))
1729
+ return false;
1730
+ // The second anchor (SF-1): the path itself, walked afresh from the worktree root. A
1731
+ // regular file with the right bytes is not this deploy's artifact unless it is at a path
1732
+ // this deploy was allowed to write — inside this worktree, with no symlink and no second
1733
+ // name anywhere along the way.
1734
+ if (containedWriteRefusal(worktreeRoot, absPath) !== null)
1735
+ return false;
1736
+ let fd;
1737
+ try {
1738
+ fd = openSync(absPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
1739
+ }
1740
+ catch {
1741
+ return false;
1742
+ }
1743
+ try {
1744
+ const open = fstatSync(fd, { bigint: true });
1745
+ if (!open.isFile() ||
1746
+ open.nlink !== 1n ||
1747
+ open.dev !== landed.dev ||
1748
+ open.ino !== landed.ino ||
1749
+ (Number(open.mode) & 0o777) !== mode ||
1750
+ // ── THE EFFECTIVE uid, NOT THE REAL ONE (round 9 SF-B) ──────────────────
1751
+ // A file is created with the process's EFFECTIVE uid, so that is the uid this
1752
+ // deploy's own output carries. Comparing `getuid()` — the REAL uid — made the
1753
+ // acceptance reject the deploy's own honest artifact under any real/effective
1754
+ // split. Latent today (mx-agent is not setuid and is not run under one), which is
1755
+ // why no test caught it and why no test can: killing this mutant needs a second
1756
+ // uid the suite does not have. It is corrected rather than left because the
1757
+ // failure mode is a deploy that refuses itself, and #4896 makes that exit 1.
1758
+ open.uid !== BigInt(process.geteuid?.() ?? process.getuid?.() ?? 0)) {
1759
+ return false;
1760
+ }
1761
+ return readFileSync(fd).equals(Buffer.from(content, 'utf-8'));
1762
+ }
1763
+ catch {
1764
+ return false;
1765
+ }
1766
+ finally {
1767
+ closeSync(fd);
1768
+ }
1769
+ }
1770
+ /**
1771
+ * ── NAME THE TEMP FILE THAT MAY STILL BE OUT THERE (security review SF-K) ─────
1772
+ *
1773
+ * The residual this write path cannot close is a parent directory swapped between the
1774
+ * containment walk and the `open`, and RESTORED before the first identity check. Both
1775
+ * identity checks then pass, because every `lstat` of the name sees the original
1776
+ * directory — but the temp file was already created behind the swapped name, so its bytes
1777
+ * are in the OTHER directory, the `rename` resolves the temp name in the restored one and
1778
+ * fails ENOENT, and the cleanup `unlink` misses for the same reason. The rate is of ORDER
1779
+ * 1 in 10^3-10^4 deploys at a roughly 5-microsecond swapper hold — an order-of-magnitude
1780
+ * ESTIMATE, not a measured rate. It read "Measured 1 in 6,000" until #4897 round 12, when
1781
+ * the review found that figure's provenance could not be re-established; see the note on
1782
+ * `directoryIdentity` above for why it was downgraded rather than re-measured. Nothing
1783
+ * downstream turns on the second digit. The deploy reports `ok=false` and lists nothing
1784
+ * as written, so there is no false success, and the file sits at a `.mx-tmp-*` name that
1785
+ * Codex never reads — nothing is loaded or executed from it.
1786
+ *
1787
+ * What was missing was the PATH. The deploy knows the temp name and knows the cleanup
1788
+ * missed; the operator was told neither, and so had no way to find the litter. This adds
1789
+ * that sentence, and it is reporting only — a structural fix needs `openat`/`renameat`,
1790
+ * which Node does not expose.
1791
+ *
1792
+ * ── THE RESIDUAL, RESTATED PRECISELY ─────────────────────────────────────────
1793
+ * The earlier wording was "no bytes reach a path outside the worktree". That is one word
1794
+ * short: no bytes reach a LIVE path outside the worktree — a path something reads, loads,
1795
+ * or executes. Bytes CAN reach an INERT one: a `.mx-tmp-<pid>-<hex>` name nothing opens.
1796
+ * The exposure is worktree-path disclosure plus junk in a shared repo, not execution.
1797
+ *
1798
+ * ── AND IT IS NOT SAID WHEN THE FILE IS GONE (round 8 INFO-2) ────────────────
1799
+ * The note fired whenever the parent directory had moved, even when the cleanup `unlink`
1800
+ * had just SUCCEEDED — so a deploy that removed its own temp file still told the operator
1801
+ * a file "may have been LEFT BEHIND" at a path where nothing remains, and sent them
1802
+ * hunting for it. A successful unlink is proof the entry is gone, so it suppresses the
1803
+ * note outright; the residual this note exists for is the case where the unlink misses
1804
+ * with ENOENT, which is unaffected.
1805
+ */
1806
+ function tempResidueNote(tmpPath, parentDir, parentId, unlinkFailedENOENT, unlinkSucceeded) {
1807
+ if (unlinkSucceeded)
1808
+ return null;
1809
+ let parentMoved = null;
1810
+ try {
1811
+ const now = lstatSync(parentDir, { bigint: true });
1812
+ if (now.dev !== parentId.dev || now.ino !== parentId.ino || !now.isDirectory()) {
1813
+ parentMoved =
1814
+ `the directory ${parentDir} is no longer the one this deploy checked (it was device ` +
1815
+ `${parentId.dev}/inode ${parentId.ino})`;
1816
+ }
1817
+ }
1818
+ catch (err) {
1819
+ parentMoved =
1820
+ `the directory ${parentDir} can no longer be examined ` +
1821
+ `(${err instanceof Error ? err.message : String(err)})`;
1822
+ }
1823
+ if (!parentMoved && !unlinkFailedENOENT)
1824
+ return null;
1825
+ const because = [
1826
+ ...(parentMoved ? [parentMoved] : []),
1827
+ ...(unlinkFailedENOENT
1828
+ ? ['the cleanup unlink found NOTHING at that name, so the file is not where the name says']
1829
+ : []),
1830
+ ].join(', and ');
1831
+ return (` A temporary file may have been LEFT BEHIND at ${tmpPath} — ${because}. It holds this ` +
1832
+ `deploy's generated ${basename(absPathOf(tmpPath))} and its path names this worktree. ` +
1833
+ 'Nothing reads it (Codex loads no `.mx-tmp-*` name), so this is litter and a path ' +
1834
+ 'disclosure, not an execution path — but find it and delete it by hand. This is the ' +
1835
+ 'declared residual of a parent directory swapped and restored around the open: no bytes ' +
1836
+ 'reach a LIVE path outside the worktree, but bytes can reach an INERT one, and closing ' +
1837
+ 'it needs `openat`/`renameat`, which Node does not expose.');
1838
+ }
1839
+ /** `<artifact>.mx-tmp-<pid>-<hex>` back to `<artifact>` — for naming what the temp holds. */
1840
+ function absPathOf(tmpPath) {
1841
+ return tmpPath.replace(/\.mx-tmp-\d+-[0-9a-f]+$/, '');
1842
+ }
1843
+ function writeFileEnsuringDir(absPath, content, worktreeRoot) {
1844
+ const refusal = containedWriteRefusal(worktreeRoot, absPath);
1845
+ if (refusal)
1846
+ throw new ContainedWriteRefusal(refusal);
1186
1847
  mkdirSync(dirname(absPath), { recursive: true });
1187
- writeFileSync(absPath, content);
1848
+ const mode = modeForInstalledArtifact(absPath);
1849
+ // ── WRITE ASIDE, THEN RENAME (delta re-review MUST FIX) ──────────────────────
1850
+ // Two earlier forms of this write were wrong in opposite directions. `O_TRUNC` wrote
1851
+ // THROUGH the existing directory entry, into whatever inode the name pointed at — the
1852
+ // whole of the hardlink attack, and a race at the final hop besides. Replacing it with
1853
+ // `unlink` + `open(O_EXCL)` fixed that and broke something `O_TRUNC` had: the previous
1854
+ // artifact was destroyed BEFORE this code knew a replacement could be created, so any
1855
+ // failure of the open — EEXIST from a concurrent deploy, a raced symlink, ENOSPC,
1856
+ // EMFILE — left NO file at all. The reviewer executed it: two concurrent deploys
1857
+ // produced 74 failed writes, and with a racer 2466 of 2500 deploys left
1858
+ // AGENTS.override.md a ZERO-BYTE file, which Codex reads as a REPLACEMENT for
1859
+ // AGENTS.md — a worktree launching with no instructions.
1860
+ //
1861
+ // A temp file plus `rename` has both properties. `rename` is atomic and replaces the
1862
+ // DIRECTORY ENTRY rather than writing through it, so: nothing is destroyed until the
1863
+ // content exists in full; a reader sees the old file or the new one, never a truncated
1864
+ // one; and a second name for the old inode, from anywhere on the filesystem, keeps the
1865
+ // OLD inode and its old bytes.
1866
+ //
1867
+ // The `O_EXCL`/`O_NOFOLLOW`/`nlink` checks are all KEPT, on the destination and on the
1868
+ // temp path both. Rename makes some of them look redundant; the evidence three reviews
1869
+ // deep is against reasoning about what this path cannot be made to do, and the temp
1870
+ // path is a NEW path in the same directory, so it gets the same containment predicate
1871
+ // the destination gets.
1872
+ const tmpPath = `${absPath}.mx-tmp-${process.pid}-${randomBytes(6).toString('hex')}`;
1873
+ const tmpRefusal = containedWriteRefusal(worktreeRoot, tmpPath);
1874
+ if (tmpRefusal)
1875
+ throw new ContainedWriteRefusal(tmpRefusal);
1876
+ // Captured LAST, immediately after the walk that just proved every component of the temp
1877
+ // path, so the gap between "the name was checked" and "the object behind it was
1878
+ // identified" is as small as this code can make it. See `directoryIdentity`.
1879
+ const parentDir = dirname(absPath);
1880
+ const parentId = directoryIdentity(parentDir);
1881
+ let installed = false;
1882
+ let created = false;
1883
+ try {
1884
+ const fd = openSync(tmpPath, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW,
1885
+ // 0o600 until the content is written — the final mode is set with `fchmod` below,
1886
+ // so the bytes are never briefly readable more widely than they end up.
1887
+ 0o600);
1888
+ // From here a temp entry EXISTS somewhere — under this name in this directory if
1889
+ // nothing moved, and under this name in another directory if something did. The
1890
+ // difference is what `tempResidueNote` reports (SF-K).
1891
+ created = true;
1892
+ let opened;
1893
+ try {
1894
+ // ── CHECK 1 OF 3: BEFORE A SINGLE BYTE IS WRITTEN (MUST FIX) ─────────────
1895
+ // `openSync` resolved `.../.codex/<name>.mx-tmp-…` by NAME. If `.codex` became a
1896
+ // symlink to the main repo's `.codex` between the containment walk and this open,
1897
+ // the file that now exists is in the MAIN REPO. Refusing here is what makes the
1898
+ // measured worst case a zero-byte temp instead of a 4983-byte fleet-wide write —
1899
+ // the `finally` below unlinks it.
1900
+ assertSameDirectory(parentDir, parentId, absPath, 'while the temporary file was being created');
1901
+ // DEFENCE IN DEPTH. `O_EXCL` should already make this impossible, so a link count
1902
+ // other than 1 on a file this call just created means an assumption above is wrong.
1903
+ // Refuse rather than write — the destination of the extra name is unknown, and on
1904
+ // this path an unknown destination has been the main repo three reviews running.
1905
+ opened = fstatSync(fd, { bigint: true });
1906
+ if (opened.nlink !== 1n) {
1907
+ throw new ContainedWriteRefusal(`refusing to write ${absPath}: the temporary file this deploy just created ` +
1908
+ `(${tmpPath}) already has ${opened.nlink} names, so the bytes would also land outside ` +
1909
+ 'this worktree. This should be unreachable (the entry was created exclusively) — treat ' +
1910
+ 'it as a filesystem or race condition and inspect the path by hand. Nothing was ' +
1911
+ `written, and ${absPath} is untouched.`);
1912
+ }
1913
+ fchmodSync(fd, mode);
1914
+ writeFileSync(fd, content);
1915
+ }
1916
+ finally {
1917
+ closeSync(fd);
1918
+ }
1919
+ // ── CHECK 2 OF 3: THE LAST THING BEFORE THE INSTALL (MUST FIX) ─────────────
1920
+ // `renameSync` resolves BOTH names afresh. Re-identifying the directory here leaves a
1921
+ // residual window exactly one rename call wide — narrower than the two-syscall window
1922
+ // the destroy-first predecessor had, and the smallest this can be without
1923
+ // `renameat` against a directory fd, which Node does not expose.
1924
+ assertSameDirectory(parentDir, parentId, absPath, 'just before the artifact was installed');
1925
+ renameSync(tmpPath, absPath);
1926
+ installed = true;
1927
+ // ── CHECK 3 OF 3: WHAT ACTUALLY LANDED, NOT WHAT WAS INTENDED (SF-I) ───────
1928
+ // The residual window above is not zero, and there is a second way to lose this race
1929
+ // that has nothing to do with the parent directory: the TEMP PATH itself can be
1930
+ // unlinked and replaced — with a symlink, or with a hardlink to a main-repo file —
1931
+ // between the write and the rename, in which case `renameSync` installs the
1932
+ // attacker's entry at the artifact path. `rename` does not follow symlinks, so what
1933
+ // arrives is the substituted object. The reviewer executed exactly that: over 3000
1934
+ // deploys per mode, 29 installed an attacker symlink at AGENTS.override.md and 37
1935
+ // installed a hardlink to the main repo's file, and ALL 66 reported ok=true and
1936
+ // listed the artifact as written. No privilege boundary is crossed — the content went
1937
+ // to the fd's own inode, not through the link — but the deploy ASSERTED SUCCESS over
1938
+ // an artifact it did not install, and a false ok is the part this project keeps
1939
+ // paying for.
1940
+ //
1941
+ // So the install is verified rather than assumed: the entry now at `absPath` must be
1942
+ // the very inode this call wrote, and a regular file. Anything else is a FAILED write
1943
+ // (`writeFailures`, never `written`), and the mixed-state report enumerates what is
1944
+ // really on disk. The bad entry is deliberately LEFT in place: it is not this
1945
+ // function's to delete, and the next deploy's containment walk refuses a symlink or a
1946
+ // hardlink at an artifact path, so the failure stays visible and fails closed.
1947
+ let landed;
1948
+ try {
1949
+ landed = lstatSync(absPath, { bigint: true });
1950
+ }
1951
+ catch (err) {
1952
+ throw new Error(`${absPath} was renamed into place but could not then be examined ` +
1953
+ `(${err instanceof Error ? err.message : String(err)}), so this deploy cannot confirm ` +
1954
+ 'that what is at that path is the file it wrote. Treating the write as FAILED.');
1955
+ }
1956
+ if ((!landed.isFile() || landed.dev !== opened.dev || landed.ino !== opened.ino) &&
1957
+ // The one benign cause of a different inode: a concurrent legitimate deploy landed
1958
+ // its own byte-identical artifact here. See `landedIsThisDeploysOwnContent` (SF-L).
1959
+ !landedIsThisDeploysOwnContent(absPath, landed, content, worktreeRoot, parentDir, parentId, mode)) {
1960
+ throw new Error(`${absPath} is NOT the file this deploy wrote. It installed inode ${opened.ino} on ` +
1961
+ `device ${opened.dev}, and the path now holds ` +
1962
+ `${landed.isSymbolicLink() ? 'a SYMLINK' : landed.isDirectory() ? 'a DIRECTORY' : !landed.isFile() ? 'a non-regular file' : `inode ${landed.ino} on device ${landed.dev} with ${landed.nlink} name(s), holding content this deploy did not write`}` +
1963
+ '. The temporary file was substituted between the write and the rename, or the ' +
1964
+ 'directory was replaced under it. The bytes went to the file this deploy created, so ' +
1965
+ 'nothing outside the worktree was written through it — but the artifact at that path ' +
1966
+ 'is NOT this deploy\'s output and the deploy must not report it as written. Remove the ' +
1967
+ 'entry at that path by hand and redeploy.');
1968
+ }
1969
+ }
1970
+ catch (err) {
1971
+ // NO `.mx-tmp-*` LITTER, on any failure path — the refusal above, a write error, a
1972
+ // failed rename, or an open that never created the file at all (the unlink then
1973
+ // fails and is ignored, which is the correct outcome for a file that is not there).
1974
+ //
1975
+ // The cleanup runs HERE rather than in a `finally` because its outcome is part of the
1976
+ // report: an unlink that finds nothing at a name this call created is the signature of
1977
+ // the residual, and the operator needs the path (SF-K). The success path never reaches
1978
+ // this — `installed` is only false on a throw.
1979
+ let unlinkFailedENOENT = false;
1980
+ let unlinkSucceeded = false;
1981
+ if (!installed) {
1982
+ try {
1983
+ unlinkSync(tmpPath);
1984
+ unlinkSucceeded = true;
1985
+ }
1986
+ catch (cleanupErr) {
1987
+ unlinkFailedENOENT =
1988
+ created && cleanupErr.code === 'ENOENT';
1989
+ /* otherwise best effort — the error being propagated is the report that matters */
1990
+ }
1991
+ }
1992
+ if (created && !installed && err instanceof Error) {
1993
+ const note = tempResidueNote(tmpPath, parentDir, parentId, unlinkFailedENOENT, unlinkSucceeded);
1994
+ if (note)
1995
+ err.message += note;
1996
+ }
1997
+ throw err;
1998
+ }
1188
1999
  }
1189
2000
  /**
1190
2001
  * Deploy every Codex config artifact into the worktree. Idempotent — each file is
@@ -1193,6 +2004,30 @@ function writeFileEnsuringDir(absPath, content) {
1193
2004
  export function deployCodexConfig(opts) {
1194
2005
  const warnings = [];
1195
2006
  const written = [];
2007
+ const writeRefusals = [];
2008
+ const writeFailures = [];
2009
+ /**
2010
+ * Record a write failure. A CONTAINMENT refusal is not the same event as an I/O error
2011
+ * and must not be flattened into "could not write X": it means the bytes were aimed at
2012
+ * a destination outside this worktree, and the operator has to be told where.
2013
+ *
2014
+ * BOTH KINDS FAIL THE DEPLOY (delta re-review MUST FIX). The non-containment branch used
2015
+ * to push one warning line and nothing else, so a deploy that wrote no hooks file — or
2016
+ * left AGENTS.override.md, which Codex reads INSTEAD of AGENTS.md, absent — still
2017
+ * reported ok=true and exit 0. The error's own text is kept: "could not write X" without
2018
+ * the errno tells an operator nothing about whether to retry, free space, or fix a
2019
+ * permission.
2020
+ */
2021
+ const noteWriteFailure = (err, fallback) => {
2022
+ if (err instanceof ContainedWriteRefusal) {
2023
+ writeRefusals.push(err.message);
2024
+ warnings.push(err.message);
2025
+ return;
2026
+ }
2027
+ const detail = `${fallback} (${err instanceof Error ? err.message : String(err)})`;
2028
+ writeFailures.push(detail);
2029
+ warnings.push(detail);
2030
+ };
1196
2031
  const configPath = join(opts.worktreePath, CODEX_CONFIG_FILENAME);
1197
2032
  try {
1198
2033
  writeFileEnsuringDir(configPath, buildCodexConfigToml({
@@ -1205,11 +2040,11 @@ export function deployCodexConfig(opts) {
1205
2040
  if (d.level === 'warn')
1206
2041
  warnings.push(d.message);
1207
2042
  },
1208
- }));
2043
+ }), opts.worktreePath);
1209
2044
  written.push(CODEX_CONFIG_FILENAME);
1210
2045
  }
1211
- catch {
1212
- warnings.push(`Could not write ${CODEX_CONFIG_FILENAME} — Codex has no MemNexus MCP server configured.`);
2046
+ catch (err) {
2047
+ noteWriteFailure(err, `Could not write ${CODEX_CONFIG_FILENAME} — Codex has no MemNexus MCP server configured.`);
1213
2048
  }
1214
2049
  // Each ported guard's script must actually be on disk. Since the #4227 G-7 fix the
1215
2050
  // wrapper fails CLOSED when it is not, so an absent script no longer means a silently
@@ -1243,13 +2078,84 @@ export function deployCodexConfig(opts) {
1243
2078
  // It also restores the stated invariant that the generated file is byte-identical in
1244
2079
  // every worktree: a per-worktree proven list gives every worktree a distinct hash and
1245
2080
  // a separate human trust grant.
2081
+ // ── DEPLOYING IS NOT INERT (#4875 MF-2) ──────────────────────────────────────
2082
+ // The file was overwritten without ever being READ, and the header called the result
2083
+ // inert on the grounds that the artifacts do nothing until a human grants trust. That
2084
+ // is true of a FIRST deploy and false of a redeploy: Codex binds each trust record to
2085
+ // the entry's content, so a redeploy whose bytes differ makes every existing grant for
2086
+ // this file stale, and Codex says NOTHING when it declines to run an entry whose hash
2087
+ // stopped matching — including in a session that is running right now. So the bytes
2088
+ // are read first and compared after, and a change is reported.
1246
2089
  const hooksPath = join(opts.worktreePath, CODEX_HOOKS_FILENAME);
2090
+ // ONE resolver, honouring CODEX_HOME (SF-A). See `resolveCodexHome`.
2091
+ const homeResolution = opts.codexHome ? { home: opts.codexHome } : resolveCodexHome();
2092
+ let codexHome = null;
2093
+ if ('home' in homeResolution) {
2094
+ codexHome = homeResolution.home;
2095
+ }
2096
+ else {
2097
+ warnings.push(`The Codex config directory could not be located: ${homeResolution.error} No existing ` +
2098
+ 'hook-trust grant can be read, so this deploy cannot tell whether it just invalidated one. ' +
2099
+ 'Treat every grant for this worktree as UNVERIFIED: `mx-agent codex trust-keys`.');
2100
+ }
2101
+ let hooksBefore = null;
1247
2102
  try {
1248
- writeFileEnsuringDir(hooksPath, buildCodexHooksJson({ worktreePath: opts.worktreePath }));
1249
- written.push(CODEX_HOOKS_FILENAME);
2103
+ hooksBefore = readFileSync(hooksPath);
1250
2104
  }
1251
2105
  catch {
1252
- warnings.push(`Could not write ${CODEX_HOOKS_FILENAME} — no containment guards are registered.`);
2106
+ hooksBefore = null;
2107
+ }
2108
+ try {
2109
+ writeFileEnsuringDir(hooksPath, buildCodexHooksJson({ worktreePath: opts.worktreePath }), opts.worktreePath);
2110
+ written.push(CODEX_HOOKS_FILENAME);
2111
+ }
2112
+ catch (err) {
2113
+ noteWriteFailure(err, `Could not write ${CODEX_HOOKS_FILENAME} — no containment guards are registered.`);
2114
+ }
2115
+ let hooksBytesChanged = false;
2116
+ if (hooksBefore !== null) {
2117
+ try {
2118
+ hooksBytesChanged = !readFileSync(hooksPath).equals(hooksBefore);
2119
+ }
2120
+ catch {
2121
+ // Unreadable after a write we believed succeeded. Treat it as changed: the
2122
+ // conservative direction here is "your grants may be stale", never "they are fine".
2123
+ hooksBytesChanged = true;
2124
+ }
2125
+ }
2126
+ // Only grants that ALREADY EXISTED can be invalidated. A first deploy into a worktree
2127
+ // with no records has nothing to make stale, and warning there would train the
2128
+ // operator to scroll past the line that matters.
2129
+ const priorGrants = codexHome === null
2130
+ ? []
2131
+ : [...readCodexTrustState(codexHome).records]
2132
+ .filter(([key, record]) => key.startsWith(`${hooksPath}:`) && record.enabled && record.hash !== '')
2133
+ .map(([key]) => key);
2134
+ const hookTrustInvalidated = hooksBefore !== null && hooksBytesChanged && priorGrants.length > 0;
2135
+ // ── AN UNREADABLE "BEFORE" IS NOT A CLEAN BILL OF HEALTH (security review SF-B) ──
2136
+ // `priorGrants` was computed as `[]` whenever the hooks file could not be read before
2137
+ // the write, so a deploy into a worktree whose hooks.json was absent or unreadable — a
2138
+ // deleted file, a permission error, a half-finished checkout — reported
2139
+ // `hookTrustInvalidated = false` while live grants for that exact path sat in the Codex
2140
+ // config. The bytes just written may or may not match them; Codex says nothing either
2141
+ // way, and this path has no hashes to compare. Unknown is reported as unknown.
2142
+ const hookTrustUnverifiable = codexHome === null || (hooksBefore === null && priorGrants.length > 0);
2143
+ if (hooksBefore === null && priorGrants.length > 0) {
2144
+ warnings.push(`${CODEX_HOOKS_FILENAME} could NOT be read before this deploy (absent or unreadable), yet ` +
2145
+ `${priorGrants.length} hook-trust grant${priorGrants.length === 1 ? '' : 's'} already exist ` +
2146
+ `for its path (${priorGrants.join(', ')}). Whether those grants match the bytes just ` +
2147
+ 'written cannot be determined here — Codex binds each record to the entry content it was ' +
2148
+ 'granted for and SILENTLY declines to run an entry whose hash stopped matching. Treat them ' +
2149
+ 'as UNVERIFIED, not as current: `mx-agent codex trust-keys` compares them against Codex\'s ' +
2150
+ 'own hashes.');
2151
+ }
2152
+ if (hookTrustInvalidated) {
2153
+ warnings.push(`${CODEX_HOOKS_FILENAME} was REWRITTEN with different bytes, so every existing hook-trust ` +
2154
+ `grant for this file is now STALE (${priorGrants.length} record${priorGrants.length === 1 ? '' : 's'}: ` +
2155
+ `${priorGrants.join(', ')}). Codex binds each trust record to the entry content it was ` +
2156
+ 'granted for, and Codex silently does not run an entry whose hash stopped matching — ' +
2157
+ 'including in any session running right now, which will keep reporting nothing while its ' +
2158
+ 'guards do not fire. Re-grant before the next launch: `mx-agent codex trust-keys`.');
1253
2159
  }
1254
2160
  const overridePath = join(opts.worktreePath, AGENTS_OVERRIDE_FILENAME);
1255
2161
  const override = buildAgentsOverride({
@@ -1276,11 +2182,68 @@ export function deployCodexConfig(opts) {
1276
2182
  `markers but NO canonical instructions.`);
1277
2183
  }
1278
2184
  try {
1279
- writeFileEnsuringDir(overridePath, override.content);
2185
+ writeFileEnsuringDir(overridePath, override.content, opts.worktreePath);
1280
2186
  written.push(AGENTS_OVERRIDE_FILENAME);
1281
2187
  }
1282
- catch {
1283
- warnings.push(`Could not write ${AGENTS_OVERRIDE_FILENAME} — this Codex session has no local override context.`);
2188
+ catch (err) {
2189
+ noteWriteFailure(err, `Could not write ${AGENTS_OVERRIDE_FILENAME} — this Codex session has no local override context.`);
2190
+ }
2191
+ // ── A REFUSAL PART-WAY THROUGH LEAVES A MIXED WORKTREE (security review INFO) ──
2192
+ // Each artifact is written independently, so a refusal on the second one leaves the
2193
+ // first on disk: an instruction file with no hooks file, or a config with neither.
2194
+ // The artifacts are NOT rolled back — restoring the previous bytes would have to undo
2195
+ // a hooks-file overwrite whose trust consequences have already been measured and
2196
+ // reported above, and a restore that itself failed would leave a state nothing here
2197
+ // could describe. What the operator gets instead is the state named outright, so
2198
+ // "some files appeared" is never read as "most of the deploy worked".
2199
+ //
2200
+ // ── AND IT REPORTS WHAT IS ON DISK, NOT WHAT IT ASSUMES (security review SF-1) ──
2201
+ // The line used to say "the refused ones are whatever was there before". The reviewer
2202
+ // captured that sentence on a real refusal where the refused artifact DID NOT EXIST —
2203
+ // the same deploy had deleted it. The write is atomic now, so "unchanged" is true again
2204
+ // for the refusal case, but a warning about a mixed worktree is worth exactly what its
2205
+ // description of that worktree is worth, so nothing here is asserted: all three
2206
+ // artifacts are MEASURED after the writes and the measurement is what gets printed.
2207
+ // The gate is refusals OR failures: a non-containment failure produced a mixed worktree
2208
+ // with no partial-deploy line at all (executed: a directory at .codex/hooks.json →
2209
+ // ok=true, no warning).
2210
+ let incompleteDeployMessage = null;
2211
+ const notWritten = writeRefusals.length + writeFailures.length;
2212
+ if (notWritten > 0) {
2213
+ const measured = [CODEX_CONFIG_FILENAME, CODEX_HOOKS_FILENAME, AGENTS_OVERRIDE_FILENAME]
2214
+ .map((rel) => {
2215
+ const path = join(opts.worktreePath, rel);
2216
+ let st;
2217
+ try {
2218
+ st = lstatSync(path);
2219
+ }
2220
+ catch (err) {
2221
+ const code = err.code ?? 'unknown';
2222
+ return `${rel}: ${code === 'ENOENT' ? 'ABSENT' : `could not be examined (${code})`}`;
2223
+ }
2224
+ if (st.isSymbolicLink())
2225
+ return `${rel}: a SYMLINK, not a file`;
2226
+ if (st.isDirectory())
2227
+ return `${rel}: a DIRECTORY, not a file`;
2228
+ if (!st.isFile())
2229
+ return `${rel}: not a regular file`;
2230
+ // EMPTY IS NAMED SEPARATELY. A zero-byte AGENTS.override.md is the worst of these
2231
+ // states and the least visible: Codex reads that file INSTEAD of AGENTS.md, so the
2232
+ // session starts with no instructions rather than with an obvious error.
2233
+ return st.size === 0 ? `${rel}: present but EMPTY (0 bytes)` : `${rel}: present, ${st.size} bytes`;
2234
+ })
2235
+ .join('; ');
2236
+ const head = written.length > 0
2237
+ ? `PARTIAL DEPLOY: ${written.length} artifact${written.length === 1 ? ' was' : 's were'} ` +
2238
+ `written (${written.join(', ')}) and ${notWritten} was not`
2239
+ : `DEPLOY FAILED: no artifact was written; ${notWritten} write${notWritten === 1 ? '' : 's'} ` +
2240
+ 'did not complete';
2241
+ incompleteDeployMessage =
2242
+ `${head}. The worktree is in a MIXED state and it must not be launched. State measured on ` +
2243
+ 'disk at the end of this ' +
2244
+ `deploy: ${measured}. Fix the refusals and failures named above and redeploy; the deploy is ` +
2245
+ 'idempotent, so a clean rerun replaces all of them.';
2246
+ warnings.push(incompleteDeployMessage);
1284
2247
  }
1285
2248
  // Measured AFTER the override is written, since that file is the one Codex reads.
1286
2249
  const chain = measureInstructionChain(opts.worktreePath, PROJECT_DOC_MAX_BYTES);
@@ -1289,8 +2252,103 @@ export function deployCodexConfig(opts) {
1289
2252
  `project_doc_max_bytes — it will be TRUNCATED silently. Per-file sizes: ` +
1290
2253
  `${chain.files.map((f) => `${f.path} ${f.bytes}B${f.read ? ' (read)' : ' (ignored)'}`).join(', ')}.`);
1291
2254
  }
1292
- const trust = codexHookTrustPreconditions({ worktreePath: opts.worktreePath });
1293
- return { written, warnings, chain, trust };
2255
+ const trust = codexHookTrustPreconditions({
2256
+ worktreePath: opts.worktreePath,
2257
+ // An unlocatable config directory reads as no records at all, which fails closed:
2258
+ // every required key is reported ungranted rather than granted.
2259
+ codexHome: codexHome ?? '',
2260
+ // This call has NO observed hashes — reading them costs a `codex app-server`
2261
+ // invocation the deploy path cannot afford — so it cannot detect staleness on its
2262
+ // own. It does not have to: this function just changed the bytes and knows it.
2263
+ bytesChanged: hookTrustInvalidated,
2264
+ grantsUnverifiable: hookTrustUnverifiable,
2265
+ });
2266
+ return {
2267
+ written,
2268
+ warnings,
2269
+ chain,
2270
+ trust,
2271
+ hookTrustInvalidated,
2272
+ hookTrustUnverifiable,
2273
+ writeRefusals,
2274
+ writeFailures,
2275
+ hasBehavioralBlock: override.hasBehavioralBlock,
2276
+ incompleteDeployMessage,
2277
+ };
2278
+ }
2279
+ /**
2280
+ * The refusal a caller raises when a deploy did not write every artifact (Gap 2).
2281
+ *
2282
+ * ─── WHY THE LAUNCH PATH NEEDED ITS OWN REFUSAL ───────────────────────────────
2283
+ * `deployCodexConfig` already reported the mixed state, and `mx-agent codex deploy-config`
2284
+ * already exits non-zero on it. `CodexAdapter.deployConfig` only PRINTED it. Executed with
2285
+ * `MX_AGENT_CODEX_PHASE1_DEV=1` — the documented hatch, and the only way a Codex session
2286
+ * runs at all while G-7 is unpassed: a deploy in which ALL THREE artifacts failed printed
2287
+ * `DEPLOY FAILED … must not be launched`, and then `assertLaunchAllowed` returned ALLOWED.
2288
+ * The session would have started with no containment guards registered, no declared
2289
+ * sandbox_mode or approval_policy, and no MemNexus MCP server — the exact configuration
2290
+ * every guardrail in this module exists to put in place.
2291
+ *
2292
+ * `refreshGuardProof` re-hashes `.codex/hooks.json` after the deploy, so a failed hooks
2293
+ * write does lose the guard proof and the G-7 gate catches THAT artifact. It binds
2294
+ * nothing about `config.toml` or `AGENTS.override.md`, and the dev hatch returns before
2295
+ * the proof is consulted anyway.
2296
+ *
2297
+ * Same shape as `instructionChainOverBudgetMessage`: one text, both refusal sites, and the
2298
+ * state it quotes is the state that was MEASURED rather than a second description of it.
2299
+ */
2300
+ export function deployIncompleteMessage(result, refusalPrefix) {
2301
+ const detail = result.incompleteDeployMessage ??
2302
+ `${result.writeRefusals.length} artifact write(s) were refused and ` +
2303
+ `${result.writeFailures.length} failed.`;
2304
+ return `${refusalPrefix}: ${detail}`;
2305
+ }
2306
+ /** Render a deploy result as the lines both deploy callers print, in a fixed order. */
2307
+ export function codexDeployReportLines(result) {
2308
+ const lines = [];
2309
+ // The version every guardrail was verified against, named AT DEPLOY (security review
2310
+ // INFO). `prove-guards` already refuses on a mismatch, but that is one command later,
2311
+ // after the operator has hand-granted eight trust records; an operator on a different
2312
+ // codex build should learn it while the artifacts are being written, not afterwards.
2313
+ // This is a STATEMENT, not a probe — nothing here reads the installed version.
2314
+ lines.push({
2315
+ level: 'info',
2316
+ text: `Generated for codex-cli ${VERIFIED_CODEX_VERSION} — the one version these guardrails were ` +
2317
+ 'verified on. On any other version the hook, trust and sandbox behaviour they rest on is ' +
2318
+ 'unverified.',
2319
+ });
2320
+ for (const file of result.written)
2321
+ lines.push({ level: 'info', text: `Deployed ${file} (codex)` });
2322
+ for (const warning of result.warnings)
2323
+ lines.push({ level: 'warn', text: warning });
2324
+ for (const precondition of result.trust) {
2325
+ if (!precondition.satisfied) {
2326
+ lines.push({
2327
+ level: 'warn',
2328
+ text: `codex hook precondition unmet (${precondition.id}): ${precondition.detail}`,
2329
+ });
2330
+ }
2331
+ }
2332
+ return lines;
2333
+ }
2334
+ /**
2335
+ * The over-budget refusal, in ONE place (#4875).
2336
+ *
2337
+ * Codex truncates the instruction file silently at `project_doc_max_bytes`, so an
2338
+ * over-budget deploy produces a file whose tail nobody can see. Both callers REFUSE on
2339
+ * it rather than warning — the deploy-only path included, because the artifact it just
2340
+ * wrote is exactly the one that would be truncated, and a deploy that reports success
2341
+ * on it would send an operator on to grant trust for a configuration that cannot be
2342
+ * read in full.
2343
+ *
2344
+ * `refusalPrefix` differs only because the two callers are refusing different actions.
2345
+ */
2346
+ export function instructionChainOverBudgetMessage(chain, refusalPrefix) {
2347
+ return (`${refusalPrefix}: ${chain.readFile} is ${chain.bytes} bytes, over the ${chain.cap}-byte ` +
2348
+ 'project_doc_max_bytes. Codex truncates it SILENTLY, so the session would run on ' +
2349
+ 'instructions with an unknown tail missing. Shrink the instruction file (AGENTS.md and the ' +
2350
+ 'worktree-local override are folded into one file under codex), or run this team on Claude ' +
2351
+ 'with `mx-agent start <team> --runtime claude`.');
1294
2352
  }
1295
2353
  /** Does the worktree carry a generated Codex config tree? Used by tests and doctor-style checks. */
1296
2354
  export function hasCodexConfig(worktreePath) {