@jbkjr/relay 0.0.0-stage → 1.2.2

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 (296) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSES/Apache-2.0.txt +201 -0
  3. package/LICENSES/README.md +19 -0
  4. package/LICENSES/codex-NOTICE.txt +6 -0
  5. package/README.md +393 -2
  6. package/SECURITY.md +145 -0
  7. package/adapters/briefs/claude.md +43 -0
  8. package/adapters/briefs/codex.md +56 -0
  9. package/adapters/briefs/models.json +33 -0
  10. package/adapters/build.mjs +8 -0
  11. package/adapters/claude/.claude-plugin/marketplace.json +13 -0
  12. package/adapters/claude/relay/.claude-plugin/plugin.json +5 -0
  13. package/adapters/claude/relay/agents/codex.md +21 -0
  14. package/adapters/claude/relay/agents/operator.md +21 -0
  15. package/adapters/claude/relay/skills/ask/SKILL.md +20 -0
  16. package/adapters/claude/relay/skills/chat/SKILL.md +13 -0
  17. package/adapters/claude/relay/skills/delegate/SKILL.md +21 -0
  18. package/adapters/claude/relay/skills/discuss/SKILL.md +19 -0
  19. package/adapters/claude/relay/skills/review/SKILL.md +21 -0
  20. package/adapters/claude/relay/skills/tree/SKILL.md +10 -0
  21. package/adapters/claude/relay/skills/write-for-codex/SKILL.md +78 -0
  22. package/adapters/codex/.agents/plugins/marketplace.json +20 -0
  23. package/adapters/codex/AGENTS.snippet.md +5 -0
  24. package/adapters/codex/relay/.codex-plugin/plugin.json +6 -0
  25. package/adapters/codex/relay/skills/relay-ask/SKILL.md +20 -0
  26. package/adapters/codex/relay/skills/relay-chat/SKILL.md +13 -0
  27. package/adapters/codex/relay/skills/relay-delegate/SKILL.md +21 -0
  28. package/adapters/codex/relay/skills/relay-discuss/SKILL.md +19 -0
  29. package/adapters/codex/relay/skills/relay-review/SKILL.md +21 -0
  30. package/adapters/codex/relay/skills/relay-tree/SKILL.md +10 -0
  31. package/adapters/codex/relay/skills/relay-write-for-claude/SKILL.md +66 -0
  32. package/adapters/generate.mjs +124 -0
  33. package/bin/relay +59 -0
  34. package/codex-pin.json +12 -0
  35. package/dist/backends/acp.js +1424 -0
  36. package/dist/backends/claude.js +890 -0
  37. package/dist/backends/cli-version.js +112 -0
  38. package/dist/backends/codex-app.js +1539 -0
  39. package/dist/backends/codex-daybreak.js +75 -0
  40. package/dist/backends/codex-env.js +656 -0
  41. package/dist/backends/codex-network.js +304 -0
  42. package/dist/backends/codex-pin.js +345 -0
  43. package/dist/backends/codex-shell-policy.js +182 -0
  44. package/dist/backends/codex-stage2.js +998 -0
  45. package/dist/backends/codex-subagents.js +47 -0
  46. package/dist/backends/codex.js +641 -0
  47. package/dist/backends/copilot.js +246 -0
  48. package/dist/backends/env.js +147 -0
  49. package/dist/backends/gemini.js +607 -0
  50. package/dist/backends/grok.js +337 -0
  51. package/dist/backends/index.js +8 -0
  52. package/dist/backends/native-temp.js +187 -0
  53. package/dist/backends/never-admission.js +90 -0
  54. package/dist/backends/run.js +67 -0
  55. package/dist/backends/stream.js +230 -0
  56. package/dist/backends/tool-discovery.js +15 -0
  57. package/dist/backends/types.js +264 -0
  58. package/dist/build-info.json +5 -0
  59. package/dist/cli.js +344 -0
  60. package/dist/confine/bridge.js +113 -0
  61. package/dist/confine/broker-core.js +76 -0
  62. package/dist/confine/broker-http.js +650 -0
  63. package/dist/confine/broker-names.js +9 -0
  64. package/dist/confine/broker.js +258 -0
  65. package/dist/confine/canary.js +380 -0
  66. package/dist/confine/diagnostics.js +122 -0
  67. package/dist/confine/gemini-tools-main.js +8 -0
  68. package/dist/confine/gemini-tools.js +181 -0
  69. package/dist/confine/hardlinks.js +58 -0
  70. package/dist/confine/harness-config.js +16 -0
  71. package/dist/confine/index.js +117 -0
  72. package/dist/confine/leases.js +217 -0
  73. package/dist/confine/paths.js +6 -0
  74. package/dist/confine/peer.js +115 -0
  75. package/dist/confine/port-policy.js +8 -0
  76. package/dist/confine/ports.js +365 -0
  77. package/dist/confine/private-root.js +208 -0
  78. package/dist/confine/probe-stage2.js +501 -0
  79. package/dist/confine/probe.js +1109 -0
  80. package/dist/confine/proxy.js +783 -0
  81. package/dist/confine/sbcheck.js +208 -0
  82. package/dist/confine/seatbelt-never.js +41 -0
  83. package/dist/confine/seatbelt-stage2.js +139 -0
  84. package/dist/confine/seatbelt.js +1129 -0
  85. package/dist/confine/sockets.js +36 -0
  86. package/dist/confine/turn-probe.js +19 -0
  87. package/dist/confine/turn.js +86 -0
  88. package/dist/core/adoption.js +124 -0
  89. package/dist/core/api-keys.js +423 -0
  90. package/dist/core/approvals.js +740 -0
  91. package/dist/core/build-identity.js +248 -0
  92. package/dist/core/caller.js +749 -0
  93. package/dist/core/calls.js +102 -0
  94. package/dist/core/claude-settings.js +1045 -0
  95. package/dist/core/config.js +453 -0
  96. package/dist/core/context.js +186 -0
  97. package/dist/core/db.js +753 -0
  98. package/dist/core/dispatch.js +110 -0
  99. package/dist/core/env-broker.js +505 -0
  100. package/dist/core/env-policy.js +182 -0
  101. package/dist/core/escalation-authority.js +76 -0
  102. package/dist/core/escalation-contract.js +13 -0
  103. package/dist/core/escalation-person-path.js +131 -0
  104. package/dist/core/escalation-policy.js +79 -0
  105. package/dist/core/escalation-runtime.js +135 -0
  106. package/dist/core/escalation-state.js +42 -0
  107. package/dist/core/escalations.js +191 -0
  108. package/dist/core/events.js +235 -0
  109. package/dist/core/executables.js +147 -0
  110. package/dist/core/extensions.js +645 -0
  111. package/dist/core/families.js +204 -0
  112. package/dist/core/git.js +657 -0
  113. package/dist/core/identity.js +113 -0
  114. package/dist/core/liveness.js +68 -0
  115. package/dist/core/mediated-network-provider.js +81 -0
  116. package/dist/core/never-checkpoint.js +76 -0
  117. package/dist/core/never-coverage.js +97 -0
  118. package/dist/core/never-network.js +49 -0
  119. package/dist/core/never-policy.js +302 -0
  120. package/dist/core/never-proxy-policy.js +109 -0
  121. package/dist/core/never-schema.js +61 -0
  122. package/dist/core/never-tools.js +56 -0
  123. package/dist/core/notices.js +48 -0
  124. package/dist/core/ops.js +959 -0
  125. package/dist/core/outcome.js +224 -0
  126. package/dist/core/params.js +32 -0
  127. package/dist/core/presence.js +174 -0
  128. package/dist/core/procs.js +546 -0
  129. package/dist/core/prompts.js +363 -0
  130. package/dist/core/protected-config.js +238 -0
  131. package/dist/core/raw-network.js +192 -0
  132. package/dist/core/redact.js +152 -0
  133. package/dist/core/refusal.js +33 -0
  134. package/dist/core/relay-command.js +310 -0
  135. package/dist/core/reported.js +3 -0
  136. package/dist/core/restart-overlay.js +651 -0
  137. package/dist/core/retention.js +1135 -0
  138. package/dist/core/secrets.js +329 -0
  139. package/dist/core/session-token.js +175 -0
  140. package/dist/core/session.js +744 -0
  141. package/dist/core/shell.js +2 -0
  142. package/dist/core/shipped-pin.js +47 -0
  143. package/dist/core/shown.js +42 -0
  144. package/dist/core/slots.js +67 -0
  145. package/dist/core/stage2-executors.js +453 -0
  146. package/dist/core/stage2-switch.js +5 -0
  147. package/dist/core/steering.js +149 -0
  148. package/dist/core/storage.js +358 -0
  149. package/dist/core/toml.js +175 -0
  150. package/dist/core/views.js +324 -0
  151. package/dist/core/wait.js +114 -0
  152. package/dist/core/wake.js +207 -0
  153. package/dist/core/watch.js +247 -0
  154. package/dist/core/worktree.js +213 -0
  155. package/dist/hosts/claude-desktop.js +274 -0
  156. package/dist/hosts/claude.js +249 -0
  157. package/dist/hosts/codex.js +345 -0
  158. package/dist/hosts/desktop-shared.js +20 -0
  159. package/dist/hosts/index.js +11 -0
  160. package/dist/hosts/types.js +4 -0
  161. package/dist/install/basics.js +18 -0
  162. package/dist/install/claude-init.js +133 -0
  163. package/dist/install/common.js +655 -0
  164. package/dist/install/doctor.js +635 -0
  165. package/dist/install/qualify-codex.js +205 -0
  166. package/dist/install.js +524 -0
  167. package/dist/mcp/elicit.js +209 -0
  168. package/dist/mcp/gateway.js +218 -0
  169. package/dist/mcp/host.js +253 -0
  170. package/dist/mcp/server.js +1124 -0
  171. package/dist/mcp/stdio.js +37 -0
  172. package/dist/modes/discussion.js +393 -0
  173. package/dist/modes/review.js +722 -0
  174. package/dist/native/relay-sbcheck +0 -0
  175. package/dist/targets/briefs.js +86 -0
  176. package/dist/targets/claude.js +94 -0
  177. package/dist/targets/codex.js +66 -0
  178. package/dist/targets/copilot.js +93 -0
  179. package/dist/targets/gemini.js +119 -0
  180. package/dist/targets/grok.js +126 -0
  181. package/dist/targets/index.js +192 -0
  182. package/dist/targets/types.js +18 -0
  183. package/dist/targets/verified.js +35 -0
  184. package/dist/worker.js +113 -0
  185. package/docs/UPGRADING.md +1518 -0
  186. package/docs/pinned-codex.md +333 -0
  187. package/experiments/stage2-redteam/lib/oracles.mjs +214 -0
  188. package/experiments/stage2-redteam/lib/report.mjs +35 -0
  189. package/npm-shrinkwrap.json +1632 -0
  190. package/package.json +82 -4
  191. package/scripts/codex-qualify/codex-pin-store.mjs +353 -0
  192. package/scripts/codex-qualify/codex-qualifier-process.mjs +265 -0
  193. package/scripts/codex-qualify/codex-qualifier.example.json +5 -0
  194. package/scripts/codex-qualify/codex-qualifier.mjs +281 -0
  195. package/scripts/codex-qualify/codex-shipped-pin.mjs +158 -0
  196. package/scripts/codex-qualify/codex-stage2-pin.mjs +48 -0
  197. package/scripts/codex-qualify/codex-stage2.mjs +2381 -0
  198. package/scripts/codex-qualify/install-codex-qualifier.mjs +98 -0
  199. package/scripts/codex-qualify/main-module.mjs +14 -0
  200. package/scripts/codex-qualify/relay-codex-qualifier.plist +37 -0
  201. package/scripts/codex-qualify/scratch-env.mjs +31 -0
  202. package/scripts/codex-qualify/session.mjs +96 -0
  203. package/scripts/codex-qualify/stage2-escalation-cases.mjs +125 -0
  204. package/test/codex-permissions.test.ts +875 -0
  205. package/test/fixtures/boundary-probes.mjs +17 -0
  206. package/test/fixtures/denial-stream-host.mjs +7 -0
  207. package/test/fixtures/families.json +246 -0
  208. package/test/fixtures/install-snapshots/claude-desktop-foreign.txt +158 -0
  209. package/test/fixtures/install-snapshots/claude-desktop-fresh.txt +101 -0
  210. package/test/fixtures/install-snapshots/claude-desktop-installed.txt +161 -0
  211. package/test/fixtures/install-snapshots/claude-foreign.txt +133 -0
  212. package/test/fixtures/install-snapshots/claude-fresh.txt +77 -0
  213. package/test/fixtures/install-snapshots/claude-installed.txt +133 -0
  214. package/test/fixtures/install-snapshots/codex-foreign.txt +159 -0
  215. package/test/fixtures/install-snapshots/codex-fresh.txt +107 -0
  216. package/test/fixtures/install-snapshots/codex-installed.txt +161 -0
  217. package/test/fixtures/link-parent.mjs +6 -0
  218. package/test/fixtures/mediated-command.cjs +72 -0
  219. package/test/fixtures/native-skill-isolation.json +280 -0
  220. package/test/fixtures/pinned-codex-app-server.mjs +25 -0
  221. package/test/fixtures/qualified-ext-adapters.mjs +36 -0
  222. package/test/fixtures/refusals/README.md +52 -0
  223. package/test/fixtures/refusals/claude-source-result.json +7 -0
  224. package/test/fixtures/refusals/openai-app-capacity.json +24 -0
  225. package/test/fixtures/refusals/openai-app-cyberPolicy.json +24 -0
  226. package/test/fixtures/refusals/openai-gpt-6-astra-max.json +12 -0
  227. package/test/fixtures/refusals/openai-gpt-6.1-sol-xhigh.json +12 -0
  228. package/test/fixtures/refusals/openai-review-capacity.json +24 -0
  229. package/test/fixtures/relay-0.2.0.sql +57 -0
  230. package/test/fixtures/relay-0.9.1.gen.mjs +212 -0
  231. package/test/fixtures/relay-0.9.1.sql +340 -0
  232. package/test/fixtures/slow-boundary-probes.mjs +37 -0
  233. package/test/fixtures/stable-surfaces/config.json +1122 -0
  234. package/test/fixtures/stable-surfaces/escalation.json +128 -0
  235. package/test/fixtures/stable-surfaces/events.json +37 -0
  236. package/test/fixtures/stable-surfaces/gemini-native-resume.json +4 -0
  237. package/test/fixtures/stable-surfaces/inbox.jsonl +2 -0
  238. package/test/fixtures/stable-surfaces/notice.txt +1 -0
  239. package/test/fixtures/stable-surfaces/refusal-item.json +28 -0
  240. package/test/fixtures/stable-surfaces/refusal-review.json +23 -0
  241. package/test/fixtures/stable-surfaces/registry.json +49 -0
  242. package/test/fixtures/stable-surfaces/tools-desktop.json +575 -0
  243. package/test/fixtures/stable-surfaces/tools.json +716 -0
  244. package/test/fixtures/stable-surfaces/usage.txt +46 -0
  245. package/test/fixtures/stage2-acp-native.mjs +138 -0
  246. package/test/fixtures/stage2-app-server.mjs +23 -0
  247. package/test/fixtures/stage2-catalog.json +91 -0
  248. package/test/fixtures/stage2-hostile-web.mjs +35 -0
  249. package/test/fixtures/stage2-native-network.mjs +62 -0
  250. package/test/fixtures/stage2-worker.ts +87 -0
  251. package/test/fixtures/status-views/expected.json +7825 -0
  252. package/test/fixtures/status-views/registries.json +1 -0
  253. package/test/fixtures/steering.json +209 -0
  254. package/test/helpers.ts +740 -0
  255. package/test/host-env.ts +7 -0
  256. package/test/keychain-decoy.ts +197 -0
  257. package/test/live-scope.ts +44 -0
  258. package/test/mediated-network.test.ts +192 -0
  259. package/test/mediated-proxy.test.ts +264 -0
  260. package/test/native-temp-alias.ts +10 -0
  261. package/test/never-policy.test.ts +629 -0
  262. package/test/never-tools.test.ts +136 -0
  263. package/test/process-home.ts +18 -0
  264. package/test/proxy.test.ts +531 -0
  265. package/test/restart-overlay-live.test.ts +85 -0
  266. package/test/restart-overlay-profile.test.ts +66 -0
  267. package/test/restart-overlay.test.ts +416 -0
  268. package/test/stable-surfaces.test.ts +249 -0
  269. package/test/stage2-escalation-live.test.ts +544 -0
  270. package/test/stage2-escalation-qualification.test.ts +170 -0
  271. package/test/stage2-escalation.test.ts +747 -0
  272. package/test/stage2-executor.test.ts +849 -0
  273. package/test/stage2-grant.test.ts +603 -0
  274. package/test/stage2-native-live.test.ts +647 -0
  275. package/test/stage2-network-decisions.test.ts +70 -0
  276. package/test/stage2-probe.test.ts +845 -0
  277. package/test/stage2-standing-live.test.ts +203 -0
  278. package/test/stubs/broker-host.mjs +59 -0
  279. package/test/stubs/broker-peer.mjs +20 -0
  280. package/test/stubs/confined-harness.mjs +91 -0
  281. package/test/stubs/ext-broken-server.mjs +2 -0
  282. package/test/stubs/ext-odd-server.mjs +21 -0
  283. package/test/stubs/ext-server.mjs +31 -0
  284. package/test/stubs/fake-host-cli.mjs +218 -0
  285. package/test/stubs/procargs.mjs +30 -0
  286. package/test/stubs/stub-acp +4 -0
  287. package/test/stubs/stub-agent.mjs +322 -0
  288. package/test/stubs/stub-claude +4 -0
  289. package/test/stubs/stub-codex +4 -0
  290. package/test/stubs/targets/acp.mjs +307 -0
  291. package/test/stubs/targets/claude.mjs +149 -0
  292. package/test/stubs/targets/codex.mjs +479 -0
  293. package/test/stubs/targets/gemini.mjs +604 -0
  294. package/test/temp-root.ts +11 -0
  295. package/test/wp4-adapters.test.ts +353 -0
  296. package/test/wp4-interlock.test.ts +136 -0
@@ -0,0 +1,265 @@
1
+ // Process containment for the qualifier, including stage2's detached executors and app servers.
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ import { scratchEnv } from "./scratch-env.mjs";
6
+ import { assertGroupSignalAllowed, isGroupSignalRefusal } from "../../dist/core/procs.js";
7
+
8
+ export const SWEEP_CAP = 64;
9
+
10
+ /** How long one process inventory may take before the watchdog gives up and fails the run, and
11
+ * from how long on it is reported as slow. On a laptop (macOS 27.0.1 and 27.2) `ps -axEww`
12
+ * timed out at the earlier 5 s in six qualifications while it took 0.06 s outside them, idle or
13
+ * at load 36; the slow reports say how long those stalls really last. */
14
+ export const INVENTORY_TIMEOUT_MS = 30_000;
15
+ export const SLOW_INVENTORY_MS = 5_000;
16
+
17
+ const reportSlowInventory = (ms) => process.stderr.write(`${new Date().toISOString()} watchdog: process inventory took ${ms} ms\n`);
18
+
19
+ /** macOS ps includes the environment, so reparented/setsid children retain the scratch marker. */
20
+ export function processTable(root, inspect = spawnSync, { onSlow = reportSlowInventory, now = () => performance.now() } = {}) {
21
+ // On macOS -e means all processes; only uppercase -E includes their environments. Orphaned
22
+ // setsid children may name the scratch root nowhere else after their parent exits.
23
+ const started = now();
24
+ const r = inspect("/bin/ps", ["-axEww", "-o", "pid=,ppid=,pgid=,stat=,lstart=,command="], {
25
+ env: scratchEnv(root, { LC_ALL: "C" }), encoding: "utf8", timeout: INVENTORY_TIMEOUT_MS, maxBuffer: 64 << 20,
26
+ });
27
+ const ms = Math.round(now() - started);
28
+ // Reporting a slow inventory is diagnostic: a logger that throws (runner.log not writable) must
29
+ // neither replace the inventory's own error nor fail a good inventory. Its failure is reported
30
+ // with that error, or else on stderr.
31
+ let logFailure = null;
32
+ if (ms >= SLOW_INVENTORY_MS) { try { onSlow(ms); } catch (e) { logFailure = e; } }
33
+ const why = (e) => e?.message ?? String(e);
34
+ const fail = (message, cause) => {
35
+ const err = new Error(`${message}${logFailure ? `; reporting the slow inventory also failed: ${why(logFailure)}` : ""}`, cause ? { cause } : undefined);
36
+ if (logFailure) err.loggingError = logFailure;
37
+ return err;
38
+ };
39
+ if (r.error || r.status !== 0) throw fail(`watchdog cannot inspect processes after ${ms} ms: ${r.error?.message ?? r.stderr}`, r.error);
40
+ const rows = parseProcessTable(r.stdout, r.pid);
41
+ if (!rows.length) throw fail("watchdog process inventory was empty or unparseable");
42
+ if (logFailure) {
43
+ try { process.stderr.write(`${new Date().toISOString()} watchdog: process inventory took ${ms} ms (could not log it: ${why(logFailure)})\n`); } catch { /* nowhere left to report it */ }
44
+ }
45
+ return rows;
46
+ }
47
+
48
+ export function parseProcessTable(text, inventoryPid) {
49
+ return text.split("\n").flatMap((line) => {
50
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+\s+\S+\s+\d+\s+[\d:]+\s+\d+)\s+(.*)$/.exec(line);
51
+ // ps inherits our scratch marker too; its own already-exited PID is not a survivor.
52
+ return m && +m[1] !== inventoryPid ? [{ pid: +m[1], ppid: +m[2], pgid: +m[3], stat: m[4], start: m[5].replace(/\s+/g, " "), command: m[6] }] : [];
53
+ });
54
+ }
55
+
56
+ export class ProcessSupervisor {
57
+ constructor(root, { onSlowInventory, table = () => processTable(root, spawnSync, onSlowInventory ? { onSlow: onSlowInventory } : {}), kill = process.kill.bind(process), graceMs = 2000, pollMs = 100, sweepCap = SWEEP_CAP } = {}) {
58
+ this.root = fs.realpathSync(root); this.table = table; this.kill = kill; this.graceMs = graceMs; this.pollMs = pollMs; this.sweepCap = sweepCap;
59
+ this.known = new Map(); this.leaders = new Set(); this.groups = new Map(); this.cancelled = null; this.active = false;
60
+ this.refusedGroups = new Map(); this.sources = new Map();
61
+ }
62
+ check() {
63
+ if (this.cancelled) throw new Error(this.cancelled);
64
+ if (this.refusedGroups.size) throw this.refusedGroups.values().next().value;
65
+ }
66
+ guardGroup(pgid) {
67
+ if (this.refusedGroups.has(pgid)) throw this.refusedGroups.get(pgid);
68
+ try { assertGroupSignalAllowed(pgid); }
69
+ catch (e) { if (isGroupSignalRefusal(e)) this.refusedGroups.set(pgid, e); throw e; }
70
+ }
71
+ signal(pid, signal) {
72
+ if (pid < 0) this.guardGroup(-pid);
73
+ try { this.kill(pid, signal); }
74
+ catch (e) {
75
+ if (e.code === "ESRCH") return;
76
+ // macOS answers killpg with EPERM, not ESRCH, when every member left in the group is a
77
+ // zombie awaiting its reaper. Treat that group as gone only when a fresh look finds no
78
+ // live member; a real refusal, or a look that fails, keeps the EPERM.
79
+ if (e.code === "EPERM" && pid < 0 && this.groupOnlyZombies(-pid)) return;
80
+ throw e;
81
+ }
82
+ }
83
+ groupOnlyZombies(pgid) {
84
+ try { return !this.table().some((row) => row.pgid === pgid && !row.stat?.startsWith("Z")); }
85
+ catch { return false; }
86
+ }
87
+ scan() {
88
+ const all = this.table(), byPid = new Map(all.map((row) => [row.pid, row]));
89
+ const rows = all.filter((row) => !row.stat?.startsWith("Z"));
90
+ // Remember selection by a group separately from membership in a group. A scratch-marked
91
+ // process may share our group and still be safe to stop by its pinned pid.
92
+ const owned = new Map();
93
+ const own = (pid, sources = []) => {
94
+ const prior = owned.get(pid);
95
+ const next = new Set([...(prior ?? []), ...sources]);
96
+ owned.set(pid, next);
97
+ return !prior || next.size !== prior.size;
98
+ };
99
+ for (const pid of this.leaders) {
100
+ const leader = byPid.get(pid), known = this.known.get(pid);
101
+ if (leader && (!known || known.start === leader.start)) own(pid, [pid]);
102
+ // The leader may exit before the first look. A live group retains its ID until its last
103
+ // member exits; remember its members even without a leader or scratch environment.
104
+ if (!leader) for (const row of rows) if (row.pgid === pid) own(row.pid, [pid]);
105
+ }
106
+ for (const [pgid, start] of this.groups) {
107
+ const leader = byPid.get(pgid);
108
+ if (leader && leader.start !== start) continue; // Reused group/leader number.
109
+ for (const row of rows) if (row.pgid === pgid) own(row.pid, [pgid]);
110
+ }
111
+ for (const row of rows) {
112
+ const prior = this.known.get(row.pid);
113
+ if (prior?.start === row.start) own(row.pid, this.sources.get(`${row.pid} ${row.start}`));
114
+ if (row.command.includes(this.root)) own(row.pid);
115
+ }
116
+ let changed = true;
117
+ while (changed) {
118
+ changed = false;
119
+ for (const row of rows) {
120
+ if (owned.has(row.pid) && row.pid === row.pgid) changed = own(row.pid, [row.pgid]) || changed;
121
+ if (owned.has(row.ppid)) changed = own(row.pid, owned.get(row.ppid)) || changed;
122
+ }
123
+ }
124
+ const found = rows.filter((row) => row.pid !== process.pid && owned.has(row.pid));
125
+ // Check group-derived selections before pid cleanup, including detached descendants. Merely
126
+ // sitting in an ancestor's group introduces no group selection and needs no exception.
127
+ for (const pgid of new Set(found.flatMap(row => [...owned.get(row.pid)]))) {
128
+ try { this.guardGroup(pgid); } catch (e) { if (!isGroupSignalRefusal(e)) throw e; }
129
+ }
130
+ for (const row of found) {
131
+ this.known.set(row.pid, row);
132
+ this.sources.set(`${row.pid} ${row.start}`, owned.get(row.pid));
133
+ if (row.pid === row.pgid) this.groups.set(row.pgid, row.start);
134
+ }
135
+ return found.filter(row => ![...owned.get(row.pid)].some(g => this.refusedGroups.has(g)));
136
+ }
137
+ signalSame(row, signal) {
138
+ const now = this.table().find((p) => p.pid === row.pid);
139
+ if (!now || now.start !== row.start || now.stat?.startsWith("Z")) return false;
140
+ for (const pgid of this.sources.get(`${now.pid} ${now.start}`) ?? []) {
141
+ try { this.guardGroup(pgid); } catch (e) { if (isGroupSignalRefusal(e)) return false; throw e; }
142
+ }
143
+ this.signal(row.pid, signal);
144
+ return true;
145
+ }
146
+ killGroups() {
147
+ const rows = this.table(), byPid = new Map(rows.map((row) => [row.pid, row]));
148
+ let refusal;
149
+ for (const pgid of new Set([...this.leaders, ...this.groups.keys()])) {
150
+ const leader = byPid.get(pgid), start = this.groups.get(pgid) ?? this.known.get(pgid)?.start;
151
+ if (leader && start && leader.start !== start) continue;
152
+ const blocked = [...(this.sources.get(`${pgid} ${leader?.start ?? start}`) ?? [])].find(g => this.refusedGroups.has(g));
153
+ if (blocked !== undefined) { refusal ??= this.refusedGroups.get(blocked); continue; }
154
+ try { this.guardGroup(pgid); }
155
+ catch (e) { if (!isGroupSignalRefusal(e)) throw e; refusal ??= e; continue; }
156
+ if (rows.some((row) => row.pgid === pgid && !row.stat?.startsWith("Z"))) this.signal(-pgid, "SIGKILL");
157
+ }
158
+ if (refusal) throw refusal;
159
+ }
160
+ async terminate() {
161
+ // Same convergence rule as stage2-executors.sweepSurvivorsNow: freeze each newly found
162
+ // identity before another look. Do not thaw them between discovery and SIGKILL: a TERM
163
+ // handler could fork a new setsid child after the two fixed looks used by the old watchdog.
164
+ const frozen = new Map(), problems = [];
165
+ const key = (row) => `${row.pid} ${row.start}`;
166
+ const attempt = (fn) => { try { return fn(); } catch (e) { problems.push(e.message); } };
167
+ let quiet = false;
168
+ try {
169
+ for (let round = 0; round < this.sweepCap; round++) {
170
+ const fresh = this.scan().filter((row) => !frozen.has(key(row)));
171
+ if (!fresh.length) { quiet = true; break; }
172
+ for (const row of fresh) if (this.signalSame(row, "SIGSTOP")) frozen.set(key(row), row);
173
+ }
174
+ if (!quiet) problems.push(`watchdog discovery did not converge after ${this.sweepCap} looks`);
175
+ } catch (e) { problems.push(e.message); }
176
+ // Even a failed/nonconvergent discovery must kill what it already froze.
177
+ for (const row of frozen.values()) attempt(() => this.signalSame(row, "SIGKILL"));
178
+ attempt(() => this.killGroups());
179
+ // Look again after killing, including processes not seen before the kill. Group death is
180
+ // never accepted as proof that detached descendants died. Recheck identity before signaling.
181
+ const deadline = Date.now() + this.graceMs;
182
+ let remaining;
183
+ for (let round = 0; round < this.sweepCap; round++) {
184
+ try { remaining = this.scan(); } catch (e) { problems.push(e.message); break; }
185
+ if (!remaining.length) break;
186
+ for (const row of remaining) {
187
+ attempt(() => this.signalSame(row, "SIGSTOP"));
188
+ attempt(() => this.signalSame(row, "SIGKILL"));
189
+ }
190
+ attempt(() => this.killGroups());
191
+ if (Date.now() >= deadline) break;
192
+ await delay(Math.min(50, Math.max(0, deadline - Date.now())));
193
+ }
194
+ try { remaining = this.scan(); } catch (e) { problems.push(e.message); }
195
+ if (remaining?.length) problems.push(`watchdog survivors: ${remaining.map((r) => r.pid).join(",")}`);
196
+ problems.push(...[...this.refusedGroups.values()].map(e => e.message));
197
+ if (problems.length) throw new Error([...new Set(problems)].join("; "));
198
+ }
199
+ cancel(reason) {
200
+ this.cancelled ??= reason;
201
+ // An active run observes cancellation at its next bounded poll; acquisition has the same path.
202
+ }
203
+ async run(command, args, { env = {}, cwd, timeoutMs = 300_000, logFd, inspect = false, combineOutput = false } = {}) {
204
+ this.check();
205
+ if (this.active) throw new Error("supervisor runs one command at a time");
206
+ this.active = true;
207
+ let child, closed, settled = false, result, failure, stdout = "", stderr = "";
208
+ try {
209
+ // Fail before spawning if process inspection is unavailable for the qualification watchdog.
210
+ if (inspect) { this.scan(); this.check(); }
211
+ child = spawn(command, args, {
212
+ cwd, env: scratchEnv(this.root, env), detached: true,
213
+ stdio: ["ignore", logFd === undefined ? "pipe" : logFd, logFd === undefined ? "pipe" : logFd],
214
+ });
215
+ if (child.pid) this.leaders.add(child.pid);
216
+ child.stdout?.on("data", (d) => { stdout = (stdout + d).slice(-16 * 1024 * 1024); });
217
+ child.stderr?.on("data", (d) => { stderr = (stderr + d).slice(-1024 * 1024); });
218
+ closed = new Promise((resolve) => {
219
+ child.once("error", (e) => { failure = e; });
220
+ child.once("close", (code, signal) => { result = { code, signal, stdout, stderr }; settled = true; resolve(); });
221
+ });
222
+ const deadline = Date.now() + timeoutMs;
223
+ while (!settled) {
224
+ if (Date.now() >= deadline) this.cancel(`timeout after ${timeoutMs}ms: ${command}`);
225
+ this.check();
226
+ if (inspect) { this.scan(); this.check(); }
227
+ await Promise.race([closed, delay(this.pollMs)]);
228
+ }
229
+ this.check();
230
+ if (failure) throw failure;
231
+ if (inspect) {
232
+ const left = this.scan();
233
+ this.check();
234
+ if (left.length) throw new Error(`qualification left descendants: ${left.map((r) => r.pid).join(",")}`);
235
+ }
236
+ if (result.code !== 0 || result.signal) throw new Error(`${command} exited ${result.code ?? result.signal}: ${stderr.slice(-2000)}`);
237
+ return combineOutput ? result.stdout + result.stderr : result.stdout;
238
+ } catch (e) {
239
+ if (child?.pid) {
240
+ // A failed group kill must not replace the error that started cleanup, or the run log
241
+ // would show only the kill error. The run still fails; every error is kept. (A group
242
+ // holding only zombies is not a failure; see signal().)
243
+ const killGroup = () => { try { this.signal(-child.pid, "SIGKILL"); return null; } catch (k) { return k; } };
244
+ const why = `qualification failed (${e?.message ?? e})`;
245
+ if (inspect) {
246
+ // Preserve the parent chain until discovery has frozen the descendants. Killing the
247
+ // driver group first loses short-lived ancestry to children which changed sessions.
248
+ try { await this.terminate(); }
249
+ catch (cleanup) {
250
+ const k = killGroup();
251
+ throw new AggregateError([e, cleanup, ...(k ? [k] : [])], `${why} and watchdog cleanup failed: ${cleanup.message}${k ? `; group kill: ${k.message}` : ""}`);
252
+ }
253
+ } else {
254
+ const k = killGroup();
255
+ if (k) throw new AggregateError([e, k], `${why} and the group kill failed: ${k.message}`);
256
+ }
257
+ if (closed) await Promise.race([closed, delay(5000, null, { ref: false }).then(() => { throw new Error("killed child did not close its pipes"); })]);
258
+ }
259
+ throw e;
260
+ } finally {
261
+ if (child?.pid) this.leaders.delete(child.pid);
262
+ this.active = false;
263
+ }
264
+ }
265
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "repo": "/Users/you/.local/share/relay-codex-qualifier/relay",
3
+ "store": "/Users/you/.local/share/relay-codex-pins",
4
+ "timeoutMs": 7200000
5
+ }
@@ -0,0 +1,281 @@
1
+ #!/usr/bin/env node
2
+ // Based on docs/research/pinned-codex-probes/qualifier.draft.mjs (feasibility job).
3
+ // No login or model traffic: only the existing model-free stage2 driver is invoked.
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import os from "node:os";
7
+ import crypto from "node:crypto";
8
+ import { pathToFileURL } from "node:url";
9
+ import { parseArgs } from "node:util";
10
+ import { scratchEnv } from "./scratch-env.mjs";
11
+ import { ProcessSupervisor } from "./codex-qualifier-process.mjs";
12
+ import {
13
+ CURRENT_VERDICT_SCHEMA, OLD_VERSION, TEAM_ID, acquireLock, atomicJson, initStore, isShippedTarget, judgeVerdict, pointer,
14
+ promote, publishTree, recoverTransaction, rollback, sha256, validateTarget,
15
+ } from "./codex-pin-store.mjs";
16
+ import { isMain } from "./main-module.mjs";
17
+ import { buildIdentity, copyBuild, describeBuild, sameBuild } from "../../dist/core/build-identity.js";
18
+
19
+ export const NOTIFICATION_SCRIPT = 'on run argv\ndisplay notification (item 1 of argv) with title "Relay Codex qualification"\nend run';
20
+
21
+ // The longest socket path the driver's relay turns make, below a scratch root. macOS allows 103 bytes.
22
+ const LONGEST_SOCKET = "/run-XXXXXX/stage2/home/.relay-t/s/relay-probe-XXXXXX/relay.sock";
23
+
24
+ export function validateConfig(input) {
25
+ const cfg = { store: path.join(os.homedir(), ".local/share/relay-codex-pins"), scratchRoot: path.join(os.homedir(), ".rsm/q"), timeoutMs: 2 * 60 * 60_000, ...input };
26
+ for (const key of ["repo", "store", "scratchRoot"]) if (!path.isAbsolute(cfg[key] ?? "")) throw new Error(`${key} must be absolute`);
27
+ if (Buffer.byteLength(cfg.scratchRoot + LONGEST_SOCKET) > 103) throw new Error(`scratchRoot ${cfg.scratchRoot} is too long: relay's unix sockets below it would pass macOS's 103-byte limit`);
28
+ if (cfg.oldBin !== undefined && !path.isAbsolute(cfg.oldBin)) throw new Error("oldBin must be absolute");
29
+ if (!Number.isSafeInteger(cfg.timeoutMs) || cfg.timeoutMs < 1000 || cfg.timeoutMs > 2 * 60 * 60_000) throw new Error("timeoutMs must be 1000..7200000");
30
+ return cfg;
31
+ }
32
+
33
+ export function verifyIntegrity(bytes, integrity) {
34
+ if (!/^sha512-[A-Za-z0-9+/]{86}==$/.test(integrity ?? "")) throw new Error("npm must supply a single sha512 SRI");
35
+ const actual = "sha512-" + crypto.createHash("sha512").update(bytes).digest("base64");
36
+ if (actual !== integrity) throw new Error("npm SRI mismatch");
37
+ }
38
+
39
+ /** Acquisition and child execution seams allow the whole orchestration to run on local fixtures. */
40
+ export function liveServices(root, supervisor) {
41
+ const command = (bin, args, options = {}) => supervisor.run(bin, args, { env: scratchEnv(root), ...options });
42
+ const get = async (url, file) => {
43
+ const args = ["--fail", "--silent", "--show-error", "--location", "--proto", "=https", "--proto-redir", "=https", "--retry", "2", "--max-time", "300", url];
44
+ if (file) args.push("--output", file);
45
+ return command("/usr/bin/curl", args, { timeoutMs: 330_000 });
46
+ };
47
+ return {
48
+ command,
49
+ json: async (url) => JSON.parse(await get(url)),
50
+ download: async (url, file) => { await get(url, file); },
51
+ // `members`: only these, so links elsewhere in the archive are never written. Paths are checked for the whole archive.
52
+ unpack: async (archive, dest, members = []) => {
53
+ const names = await command("/usr/bin/tar", ["-tzf", archive]);
54
+ if (!names.trim() || names.split("\n").some((n) => n.startsWith("/") || n.split("/").includes(".."))) throw new Error("unsafe archive member path");
55
+ const types = await command("/usr/bin/tar", ["-tvzf", archive, ...members]);
56
+ if (types.trimEnd().split("\n").some((line) => !/^[d-]/.test(line))) throw new Error("archive links and special files are forbidden");
57
+ fs.mkdirSync(dest, { mode: 0o700 });
58
+ await command("/usr/bin/tar", ["-xzf", archive, "--no-same-owner", "--no-same-permissions", "-C", dest, ...members]);
59
+ },
60
+ notify: async (text) => { await command("/usr/bin/osascript", ["-e", NOTIFICATION_SCRIPT, text], { timeoutMs: 10_000 }); },
61
+ };
62
+ }
63
+
64
+ export async function verifyBinary(bin, version, services) {
65
+ await services.command("/usr/bin/codesign", ["--verify", "--strict", "-R=anchor apple generic and certificate leaf[subject.OU] = \"2DC432GLL2\"", bin]);
66
+ const identityText = await services.command("/usr/bin/codesign", ["-dv", "--verbose=4", bin], { combineOutput: true });
67
+ const team = /^TeamIdentifier=(.+)$/m.exec(identityText)?.[1]?.trim();
68
+ const identity = /^Authority=(.+)$/m.exec(identityText)?.[1]?.trim();
69
+ if (team !== TEAM_ID || !identity) throw new Error("unexpected codesign identity");
70
+ const said = (await services.command(bin, ["--version"], { timeoutMs: 30_000 })).trim();
71
+ if (said !== `codex-cli ${version}`) throw new Error(`binary version mismatch: expected ${version}, got ${said}`);
72
+ return { teamId: team, identity };
73
+ }
74
+
75
+ /** `integrity`: the sha512 SRI the package must have (a release's shipped pin); npm's metadata is refused before any download when it names another. */
76
+ export async function acquire(version, root, services, { integrity } = {}) {
77
+ if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error("candidate must be stable semver");
78
+ const meta = await services.json(`https://registry.npmjs.org/@openai/codex/${version}-darwin-arm64`);
79
+ if (meta.version !== `${version}-darwin-arm64`) throw new Error("npm metadata version mismatch");
80
+ if (integrity !== undefined && meta.dist?.integrity !== integrity) throw new Error(`npm's integrity for @openai/codex@${version}-darwin-arm64 is not the one relay's shipped pin names`);
81
+ const url = new URL(meta.dist.tarball);
82
+ if (url.protocol !== "https:" || url.hostname !== "registry.npmjs.org") throw new Error("unexpected npm tarball origin");
83
+ const archive = path.join(root, `codex-${version}.tgz`);
84
+ await services.download(url.href, archive);
85
+ verifyIntegrity(fs.readFileSync(archive), meta.dist.integrity);
86
+ const extracted = path.join(root, `package-${version}`);
87
+ await services.unpack(archive, extracted);
88
+ const vendor = path.join(extracted, "package/vendor/aarch64-apple-darwin");
89
+ const pkg = JSON.parse(fs.readFileSync(path.join(vendor, "codex-package.json"), "utf8"));
90
+ if (pkg.version !== version || pkg.entrypoint !== "bin/codex") throw new Error("unreviewed Codex vendor layout");
91
+ const bin = path.join(vendor, "bin/codex");
92
+ const codesign = await verifyBinary(bin, version, services);
93
+ return { vendor, bin, npmIntegrity: meta.dist.integrity, binarySha256: sha256(bin), codesign };
94
+ }
95
+
96
+ async function sourceFor(version, root, services) {
97
+ let ref = (await services.json(`https://api.github.com/repos/openai/codex/git/ref/tags/rust-v${version}`)).object;
98
+ for (let n = 0; ref?.type === "tag" && n < 5; n++) {
99
+ if (!/^[a-f0-9]{40}$/.test(ref.sha)) throw new Error("invalid annotated tag");
100
+ ref = (await services.json(`https://api.github.com/repos/openai/codex/git/tags/${ref.sha}`)).object;
101
+ }
102
+ if (ref?.type !== "commit" || !/^[a-f0-9]{40}$/.test(ref.sha)) throw new Error("cannot resolve source tag to commit");
103
+ const archive = path.join(root, "source.tar.gz");
104
+ await services.download(`https://codeload.github.com/openai/codex/tar.gz/${ref.sha}`, archive);
105
+ const extracted = path.join(root, "source");
106
+ // The driver reads only the model catalog. The tree holds links (rust-v0.164.0: vendor/bubblewrap/LICENSE), which unpack refuses.
107
+ await services.unpack(archive, extracted, [`codex-${ref.sha}/codex-rs/models-manager/models.json`]);
108
+ const source = path.join(extracted, `codex-${ref.sha}`, "codex-rs");
109
+ if (!fs.statSync(source).isDirectory()) throw new Error("source archive lacks codex-rs");
110
+ return { source, sourceCommit: ref.sha, sourceArchiveSha256: sha256(archive) };
111
+ }
112
+
113
+ function failedQualificationPath(store, attempt) {
114
+ // Keyed by relay's build identity, scheme included (relay-build-v2). Records keyed by a relay
115
+ // commit, or by a relay-build-v1 identity, match nothing now, so those inputs are qualified again.
116
+ const key = crypto.createHash("sha256").update(JSON.stringify([attempt.version, attempt.binarySha256, attempt.relayBuild.scheme, attempt.relayBuild.version, attempt.relayBuild.sha256])).digest("hex");
117
+ return path.join(store, "failed-qualifications", `${key}.json`);
118
+ }
119
+
120
+ /** Holds one updater/rollback lock. Durable evidence is retained on every failure. */
121
+ export async function runQualifier(input, { services: supplied, supervisor: suppliedSupervisor, version: requested, force = false, signals = true, aqua = true } = {}) {
122
+ const cfg = validateConfig(input);
123
+ initStore(cfg.store);
124
+ const release = acquireLock(cfg.store);
125
+ if (!release) return { state: "busy" };
126
+ let runDir, scratch;
127
+ try {
128
+ runDir = fs.mkdtempSync(path.join(cfg.store, "runs", `${new Date().toISOString().replaceAll(":", "-")}-`));
129
+ fs.mkdirSync(cfg.scratchRoot, { recursive: true, mode: 0o700 });
130
+ scratch = fs.mkdtempSync(path.join(cfg.scratchRoot, "run-"));
131
+ } catch (e) { release(); throw e; }
132
+ const supervisor = suppliedSupervisor ?? new ProcessSupervisor(scratch, {
133
+ onSlowInventory: (ms) => fs.appendFileSync(path.join(runDir, "runner.log"), `${new Date().toISOString()} watchdog: process inventory took ${ms} ms\n`, { mode: 0o600 }),
134
+ });
135
+ const services = supplied ?? liveServices(scratch, supervisor);
136
+ let version = requested ?? "unknown";
137
+ const onTerm = () => supervisor.cancel("interrupted by SIGTERM/logout");
138
+ const onInt = () => supervisor.cancel("interrupted by SIGINT");
139
+ if (signals) { process.on("SIGTERM", onTerm); process.on("SIGINT", onInt); }
140
+ const log = (message) => { fs.appendFileSync(path.join(runDir, "runner.log"), `${new Date().toISOString()} ${message}\n`, { mode: 0o600 }); console.log(message); };
141
+ try {
142
+ recoverTransaction(cfg.store);
143
+ if (aqua && (await services.command("/bin/launchctl", ["managername"])).trim() !== "Aqua") throw new Error("qualification requires the Aqua (desktop) login session: run it from a terminal in your own desktop login, or from its LaunchAgent");
144
+ if (!fs.existsSync(path.join(cfg.repo, "dist/backends/codex.js"))) throw new Error("repo must be a trusted, built relay: a git checkout after npm run build, or an npm install");
145
+ // What the pin will say was qualified (src/core/build-identity.ts). Computed before anything is
146
+ // downloaded, so an incomplete build fails here and not an hour into stage 2.
147
+ const relayBuild = buildIdentity(cfg.repo);
148
+ if (!requested) version = (await services.json("https://registry.npmjs.org/@openai/codex/latest")).version;
149
+ if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error("latest must be a stable semver");
150
+ const current = pointer(cfg.store, "current");
151
+ // A release's shipped pin is the maintainer's qualification, not this Mac's: running the
152
+ // qualifier qualifies the version here even when the shipped pin already names it.
153
+ if (current && !isShippedTarget(current) && validateTarget(cfg.store, current).version === version) {
154
+ const result = { state: "unchanged", version, runDir, target: current };
155
+ atomicJson(path.join(cfg.store, "last-result.json"), result);
156
+ log(`Codex ${version} already qualified`);
157
+ return result;
158
+ }
159
+ log(`Acquiring Codex ${version}`);
160
+ const candidate = await acquire(version, scratch, services);
161
+ const attempt = { version, binarySha256: candidate.binarySha256, relayBuild };
162
+ const failedPath = failedQualificationPath(cfg.store, attempt);
163
+ if (!force) {
164
+ let failed;
165
+ try { failed = JSON.parse(fs.readFileSync(failedPath, "utf8")); }
166
+ catch (e) { if (e.code !== "ENOENT") throw e; }
167
+ if (failed?.version === version && failed.binarySha256 === attempt.binarySha256 && failed.relayBuild && sameBuild(failed.relayBuild, relayBuild)) {
168
+ const result = { state: "skipped", ...attempt, runDir, failedAt: failed.at, verdictPath: failed.verdictPath };
169
+ atomicJson(path.join(cfg.store, "last-result.json"), result);
170
+ log(`Skipped Codex ${version}: binary SHA-256 ${attempt.binarySha256} already failed with ${describeBuild(relayBuild)} on ${failed.at}; verdict: ${failed.verdictPath}`);
171
+ return result;
172
+ }
173
+ }
174
+ let oldBin = cfg.oldBin;
175
+ if (oldBin) await verifyBinary(oldBin, OLD_VERSION, services);
176
+ else oldBin = (await acquire(OLD_VERSION, scratch, services)).bin;
177
+ const source = await sourceFor(version, scratch, services);
178
+ // Stage 2 runs from a verified copy of the build in scratch: Node strips TypeScript types only
179
+ // outside node_modules, where an npm install lives, and the source cannot change under the run.
180
+ const tree = path.join(scratch, "relay");
181
+ copyBuild(cfg.repo, tree);
182
+ const driver = path.join(tree, "scripts/codex-qualify/codex-stage2.mjs");
183
+ const stage2Sha256 = sha256(driver);
184
+ const out = path.join(scratch, "stage2");
185
+ const logFd = fs.openSync(path.join(runDir, "stage2.log"), "wx", 0o600);
186
+ let driverError;
187
+ try {
188
+ await services.command(process.execPath, [driver, tree, out, version, candidate.bin, "--source", source.source, "--old-bin", oldBin], {
189
+ cwd: tree, timeoutMs: cfg.timeoutMs, logFd, inspect: true,
190
+ // Items 28 and 30 stay "not run" without these, and judgeVerdict refuses a verdict with any part not run.
191
+ env: { RELAY_TEST_PUBLIC_NET: "1", RELAY_TEST_ESCALATION_LONG: "1" },
192
+ });
193
+ } catch (e) { driverError = e; }
194
+ finally { fs.closeSync(logFd); }
195
+ const scratchVerdict = path.join(out, "stage2-verdict.json");
196
+ if (driverError && !fs.existsSync(scratchVerdict)) throw driverError;
197
+ const verdict = JSON.parse(fs.readFileSync(scratchVerdict, "utf8"));
198
+ const verdictPath = path.join(runDir, "stage2-verdict.json");
199
+ atomicJson(verdictPath, verdict);
200
+ // A candidate cannot opt into a historical schema: judge against the current one.
201
+ const judged = judgeVerdict(verdict, version, CURRENT_VERDICT_SCHEMA);
202
+ if (!judged.ok) {
203
+ // Only a completed, rejected verdict is reusable. Acquisition/driver crashes without
204
+ // a verdict and failures after a passing verdict must remain retryable.
205
+ fs.mkdirSync(path.dirname(failedPath), { recursive: true, mode: 0o700 });
206
+ atomicJson(failedPath, { ...attempt, at: new Date().toISOString(), verdictPath });
207
+ throw driverError ?? new Error(judged.why.join("; "));
208
+ }
209
+ // Stamp the schema actually enforced.
210
+ verdict.verdictSchema = CURRENT_VERDICT_SCHEMA;
211
+ atomicJson(verdictPath, verdict);
212
+ // A forced retry can overturn a prior failure. Do not let that old record suppress
213
+ // retries if this passing qualification encounters a driver/publication/promotion error.
214
+ fs.rmSync(failedPath, { force: true });
215
+ if (driverError) throw driverError;
216
+ supervisor.check();
217
+ // Refuse a build (the source or the copy that ran) or a binary changed while qualification was running.
218
+ if (sha256(candidate.bin) !== candidate.binarySha256 || !sameBuild(buildIdentity(tree), relayBuild) ||
219
+ !sameBuild(buildIdentity(cfg.repo), relayBuild)) throw new Error("qualification inputs changed during run");
220
+ const manifest = {
221
+ version, npmIntegrity: candidate.npmIntegrity, binarySha256: candidate.binarySha256, codesign: candidate.codesign,
222
+ qualifiedAt: new Date().toISOString(), verdictPath, verdictSchema: CURRENT_VERDICT_SCHEMA,
223
+ verdictSha256: sha256(verdictPath), sourceCommit: source.sourceCommit,
224
+ sourceArchiveSha256: source.sourceArchiveSha256, relayBuild, stage2Sha256, nodeVersion: process.version,
225
+ };
226
+ const target = publishTree(cfg.store, candidate.vendor, manifest);
227
+ const transaction = promote(cfg.store, target, "promote", () => supervisor.check());
228
+ atomicJson(path.join(cfg.store, "last-result.json"), { state: "promoted", version, runDir, target, transaction });
229
+ log(`Promoted Codex ${version} to ${target}`);
230
+ return { state: "promoted", version, target, runDir };
231
+ } catch (err) {
232
+ // Restore previous on an aborted pre-commit swap, or finish the journal after the current
233
+ // commit point. A recovery error remains visible alongside the original failure.
234
+ let recoveryError;
235
+ try { recoverTransaction(cfg.store); } catch (e) { recoveryError = e.stack ?? String(e); }
236
+ const failure = { state: "failed", version, at: new Date().toISOString(), runDir, scratch, error: err.stack ?? String(err) };
237
+ if (recoveryError) failure.recoveryError = recoveryError;
238
+ atomicJson(path.join(runDir, "failure.json"), failure);
239
+ atomicJson(path.join(cfg.store, "last-failure.json"), failure);
240
+ atomicJson(path.join(cfg.store, "last-result.json"), failure);
241
+ log(`FAILED Codex ${version}: ${err.stack ?? err}`);
242
+ // A cancelled supervisor refuses new work. Use a fresh bounded supervisor for notification.
243
+ try { await (supplied?.notify ?? liveServices(scratch, new ProcessSupervisor(scratch)).notify)(`Codex ${version}: qualification/update failed. See ${runDir} and current pin/journal.`); }
244
+ catch (notifyError) { log(`Notification failed: ${notifyError.message}`); }
245
+ return failure;
246
+ } finally {
247
+ if (signals) { process.off("SIGTERM", onTerm); process.off("SIGINT", onInt); }
248
+ // Scratch is deliberately retained: diagnosis and watchdog reproduction use the exact tree.
249
+ release();
250
+ }
251
+ }
252
+
253
+ export function runRollback(input) {
254
+ const cfg = validateConfig(input);
255
+ initStore(cfg.store);
256
+ const release = acquireLock(cfg.store);
257
+ if (!release) throw new Error("qualifier is running; rollback did not run");
258
+ try { return rollback(cfg.store); } finally { release(); }
259
+ }
260
+
261
+ if (isMain(import.meta.url)) {
262
+ process.umask(0o077);
263
+ const [configFile, action, ...rest] = process.argv.slice(2);
264
+ let options;
265
+ try {
266
+ const { values } = parseArgs({ args: rest, options: { version: { type: "string" }, force: { type: "boolean", default: false } } });
267
+ if (!configFile || !["--run", "--rollback"].includes(action) || (action === "--rollback" && rest.length) ||
268
+ (values.version !== undefined && !/^\d+\.\d+\.\d+$/.test(values.version))) throw new Error("invalid arguments");
269
+ options = values;
270
+ } catch {
271
+ console.error("Usage: node codex-qualifier.mjs /absolute/qualifier.json --run [--version X.Y.Z] [--force] | --rollback"); process.exitCode = 2;
272
+ }
273
+ if (options) {
274
+ try {
275
+ const cfg = JSON.parse(fs.readFileSync(configFile, "utf8"));
276
+ const result = action === "--rollback" ? runRollback(cfg) : await runQualifier(cfg, options);
277
+ console.log(JSON.stringify(result, null, 2));
278
+ if (result?.state === "failed") process.exitCode = 1;
279
+ } catch (e) { console.error(e.stack); process.exitCode = 1; }
280
+ }
281
+ }