@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,333 @@
1
+ # Pinned Codex
2
+
3
+ Relay runs Codex only from a **qualified pin**: a copy of a Codex release that relay downloaded
4
+ and verified, whose run under relay passed the stage-2 qualification, kept in a store that
5
+ launched agents cannot write. The qualification is either your own (`relay qualify-codex`, a
6
+ **local** pin) or the maintainer's, shipped with the release (a **shipped** pin, below). Until
7
+ there is one, relay refuses every Codex job (`relay doctor` says so under "codex pin"). It never
8
+ falls back to the Codex on your PATH.
9
+
10
+ ## Qualifying once: `relay qualify-codex`
11
+
12
+ ```sh
13
+ relay qualify-codex # npm's latest Codex
14
+ relay qualify-codex --version 0.169.0 # a release of your choice
15
+ ```
16
+
17
+ Run it from a terminal in your own desktop login. It refuses to run inside an agent relay
18
+ launched, and the qualifier refuses outside a desktop (Aqua) session, such as over SSH.
19
+
20
+ It runs the same qualifier as the LaunchAgent below, with the same checks:
21
+
22
+ - It downloads the release and its source.
23
+ - It verifies npm's integrity, Apple's signature, OpenAI's Team ID and the exact version.
24
+ - It runs relay's model-free stage-2 qualification against the release. This step takes about an hour and a half.
25
+ - It promotes the release into the pin store only when every item passes.
26
+
27
+ The pin store is `targets.codex.pin_store`, by default `~/.local/share/relay-codex-pins`.
28
+
29
+ When it finishes, it prints what was checked and where the pin is. Then it asks relay which Codex
30
+ it would now run, and prints relay's answer. It exits 0 only when relay would run a qualified pin.
31
+
32
+ `--force` retries a release whose exact inputs failed before; every check still runs.
33
+
34
+ The command runs from the relay that `relay` runs from: an npm install, or a git checkout after
35
+ `npm run build`. The pin names relay's build identity (see below), not a git commit, so it needs no
36
+ `.git`, and a checkout with local changes is qualified as what it is. After you update or edit a
37
+ checkout, run `npm run build` before qualifying: the qualifier runs the build in `dist/`, never the
38
+ sources.
39
+
40
+ ### Relay's build identity
41
+
42
+ A pin records which relay it was qualified with as `relayBuild`: relay's version and one SHA-256
43
+ over the build a qualification exercises ([build-identity.ts](../src/core/build-identity.ts),
44
+ scheme `relay-build-v2`). The build is `dist/`, `npm-shrinkwrap.json`, `scripts/codex-qualify/`,
45
+ the stage-2 test files the qualification's cases run with the test modules, fixtures and stubs they
46
+ load, and the two red-team oracle modules one of them imports; `package.json` ships each of them in
47
+ its `files`. Every regular file under those paths is hashed in sorted path order, as
48
+ `<path>\0<sha256>\n` after the line `relay-build-v2\n`; names npm never packs (dotfiles,
49
+ `node_modules`, `*.orig`) are left out alike, and a symlink or special file is refused. A git
50
+ checkout and an npm install of the same build therefore name the same identity.
51
+
52
+ `npm-shrinkwrap.json` is relay's dependency lock: exact versions and sha512 integrities for relay's
53
+ whole dependency tree, so an identity, and a pin that names one, also names relay's dependencies.
54
+ `npm ci` in a checkout installs exactly what it names. An npm install reads a package's shrinkwrap
55
+ only when the registry marks the version as having one (`_hasShrinkwrap`, which it sets for a
56
+ published package that ships one, not for a local tarball), so `package.json` also names each of
57
+ relay's direct dependencies at exactly its locked version, which npm installs either way. Relay
58
+ then checks what it would actually load: it walks its runtime dependency graph, finds each package
59
+ as Node would (from the package that requires it) and its entry in the lock as npm lays it out, and
60
+ requires the same version for every one, transitive dependencies included (dev-only entries are
61
+ never reached). The qualifier refuses to run otherwise (run `npm ci`). Under a shipped pin, relay
62
+ refuses to run Codex otherwise (reinstall relay), both when the dependencies the process loaded at
63
+ start drifted and when the ones on disk now do. `dist/build-info.json` is part of `dist/`: it records the commit the build was
64
+ made from and when, so every build has an identity of its own, even of the same commit. Everything
65
+ else in the build is reproducible from its sources (the native helper is linked under a fixed name,
66
+ since its ad-hoc signature carries that name).
67
+
68
+ Builds before the lock was added wrote `relay-build-v1`, the same files without it. A local pin or failure record
69
+ that names a v1 identity is still read as a record of what it ran with, and a local pin keeps
70
+ working. A v1 identity never equals a v2 one, though: a recorded failure under v1 is qualified
71
+ again, and a shipped pin that names v1 is refused (a release must be qualified with the build it
72
+ ships). Node will not strip TypeScript types under
73
+ `node_modules`, so the qualifier copies the build to its scratch directory, checks the copy's
74
+ identity against the source's, and runs stage 2 from the copy; before promoting, it checks that
75
+ neither the source nor the copy changed during the run.
76
+
77
+ Pins written before build identities record the relay commit they ran from (`relayCommit`) and
78
+ keep working: a local pin was never bound to the relay running it, only to its own Codex binary
79
+ and the evidence of its qualification, and that is unchanged. `relay qualify-codex` describes
80
+ either kind.
81
+
82
+ After the first pin, sign in once with relay's own Codex home. `relay install codex --write` makes
83
+ that home first, with the `config.toml` relay writes there (Codex refuses a `CODEX_HOME` that does
84
+ not exist, and relay's file keeps the login in the file store its turns read):
85
+
86
+ ```sh
87
+ CODEX_HOME="$HOME/.local/share/relay-codex-home" ~/.local/share/relay-codex-pins/current/bin/codex login
88
+ ```
89
+
90
+ On a remote or headless Mac, add `--device-auth`, which needs device code sign-in switched on in
91
+ ChatGPT's Security settings.
92
+
93
+ `relay doctor`'s "codex login" line goes by the account Codex's app server reports for that home
94
+ (`account/read`), the check each turn makes before it starts, and not only by `codex login status`,
95
+ which finds a stored login whether or not Codex still accepts it. When a login is stored there but
96
+ Codex reports no account, the line fails and each Codex turn is refused, both saying that Codex no
97
+ longer accepts the stored login, most likely because it expired and Codex could not refresh it (on
98
+ 2026-11-18, a revoked refresh token), and giving the command above to sign in again. An expired
99
+ login whose refresh still works needs nothing: Codex refreshes it when its app server starts.
100
+ Under `child_auth: "any"` a turn does not check the login, and neither does the line.
101
+
102
+ ## A release's shipped pin
103
+
104
+ A release installed from npm carries `codex-pin.json`,
105
+ the maintainer's qualification of one Codex release with exactly that relay build
106
+ ([shipped-pin.ts](../src/core/shipped-pin.ts)):
107
+
108
+ ```json
109
+ {
110
+ "format": "relay-shipped-codex-pin-v1",
111
+ "codex": { "version": "0.169.0", "npmIntegrity": "sha512-…" },
112
+ "relay": { "scheme": "relay-build-v2", "version": "1.2.2", "sha256": "…" }
113
+ }
114
+ ```
115
+
116
+ That is all it can hold. npm's sha512 integrity fixes every byte of the Codex package, and relay's
117
+ build identity fixes every byte of the relay that ran the qualification, so nothing in it depends
118
+ on the maintainer's machine: no path, user, host or time. A manifest with any other field is
119
+ refused, not trimmed. What it does not carry is the maintainer's Mac itself, which is the trust a
120
+ shipped pin asks for (README, Security model, "Pinned Codex").
121
+
122
+ **Putting it in place.** `relay install codex --write` (and `relay qualify-codex --shipped`) run
123
+ [codex-shipped-pin.mjs](../scripts/codex-qualify/codex-shipped-pin.mjs) `installShippedPin`:
124
+
125
+ - it refuses a package whose build is not the one its pin names (a package changed after release);
126
+ - it refuses npm metadata naming another integrity, before downloading;
127
+ - it then downloads `@openai/codex@<version>-darwin-arm64` and checks its bytes against that
128
+ integrity, and Apple's signature, OpenAI's Team ID and the exact version as the qualifier does;
129
+ - it publishes the vendor tree under `shipped/<version>-<sha12>` (never `versions/`), and makes it
130
+ `current` through the same journalled promotion. Rollback works across both kinds.
131
+
132
+ **What relay checks on every turn.** A `shipped/` tree runs only if the package relay is running
133
+ from ships a pin naming exactly that tree's version and integrity, and that pin's relay build is
134
+ the build running now, both on disk and as the process loaded it when it started (a worker kept
135
+ running across an in-place upgrade still runs the old release's code, which the new release's pin
136
+ does not cover, so it refuses Codex until the session restarts).
137
+ Upgrading relay therefore refuses the old shipped pin until
138
+ `relay install codex --write` puts the new release's in place. That is immediate when the new
139
+ release ships the same Codex: the tree is shared. A `shipped/` manifest has no verdict, so it can
140
+ never pass as a local pin, and a local manifest under `shipped/` is refused too.
141
+
142
+ **Precedence.** Relay runs whatever `current` names, and:
143
+
144
+ - `relay install codex --write` makes the shipped pin current only when there is no pin or the
145
+ current one is shipped. It never replaces a pin qualified on this Mac.
146
+ - `relay qualify-codex --shipped` replaces a local pin with the shipped one, on request. `previous`
147
+ keeps the local one for rollback.
148
+ - `relay qualify-codex` (and the LaunchAgent) always qualify here, even the version the shipped pin
149
+ names, and the local pin then takes precedence.
150
+ - `relay doctor` reports which pin is in force. When a local pin is current and the release ships
151
+ another, doctor says so and how to switch.
152
+
153
+ ### Shipping a pin with a release (maintainer)
154
+
155
+ The manifest is written only by `writeShippedPin`, and only from a passing local qualification. It
156
+ holds the store's lock and refuses unless all of these hold:
157
+
158
+ - the store's `current` is a `versions/` tree;
159
+ - the tree's sealed manifest, binary digest and verdict re-judge as passing under the current
160
+ schema, with the verdict bound by its digest;
161
+ - it is not a stage-2 fixture;
162
+ - it records a `relayBuild` equal to the build being released.
163
+
164
+ `npm pack` refuses a `codex-pin.json` that names another build (`scripts/check-pack.mjs`). Because
165
+ the pin names `dist/` byte for byte, `dist/build-info.json` included, build once and pack that
166
+ build; never rebuild between qualifying and packing.
167
+
168
+ **Release order.** Development happens in a private repository; each release reaches the public
169
+ repository as one exported commit. The export leaves every file of the build identity, and the
170
+ sources they are built from (`src/`, `native/`, the build scripts), byte for byte as they are in
171
+ the private repository: it strips and rewrites only documentation and other files outside the
172
+ build. A release is then built, qualified and packed in the exported tree, never in the private
173
+ one, so `dist/build-info.json` records the public commit that anyone can check out:
174
+
175
+ 1. Export the release commit to a clean clone of the public repository, commit it there, and push.
176
+ 2. In that clone, at that commit, with a clean tree: `npm ci && npm run build`.
177
+ 3. Qualify that build into a fresh store and write the pin from it.
178
+ 4. Pack it, check the tarball, and publish that exact tarball.
179
+
180
+ ```sh
181
+ # in the public clone, at the release commit, with nothing uncommitted (git status --porcelain is empty)
182
+ npm ci && npm run build
183
+ # qualify into a fresh store (not your live one), with repo = this checkout
184
+ store=$(mktemp -d)/pins
185
+ printf '{"repo":"%s","store":"%s"}\n' "$PWD" "$store" > "$TMPDIR/release-qualifier.json"
186
+ node scripts/codex-qualify/codex-qualifier.mjs "$TMPDIR/release-qualifier.json" --run --version X.Y.Z # ~1.5 h, desktop login
187
+ node scripts/codex-qualify/codex-shipped-pin.mjs --write --store "$store" # writes ./codex-pin.json
188
+ npm pack # prepack checks the pin against the build
189
+ node scripts/codex-qualify/codex-shipped-pin.mjs --check-tarball jbkjr-relay-<version>.tgz # the packed release names its own build
190
+ npm publish jbkjr-relay-<version>.tgz # exactly the bytes just checked
191
+ ```
192
+
193
+ The identity in the published tarball then equals the identity in its pin by construction, and
194
+ both checks above refuse otherwise. A build of the same commit made elsewhere with `npm ci` and the
195
+ same developer tools differs only in `dist/build-info.json` (its time, and the commit when made in
196
+ another repository). Other tools can change more: the native helper (`dist/native/relay-sbcheck`) is
197
+ compiled with the Mac's own `cc`, and is left out of a build made without Apple's command line
198
+ tools.
199
+
200
+ `codex-pin.json` is ignored by git: it belongs to one build, not to a commit.
201
+
202
+ ## How the qualifier works
203
+
204
+ The independent [Codex qualifier](../scripts/codex-qualify/codex-qualifier.mjs) admits complete npm macOS ARM vendor trees into a Relay-owned store. Interactive Codex continues to update independently. Failed downloads, signatures, qualification, or missing GUI prerequisites leave the current qualified binary in service. There is no fallback to interactive Codex. Relay's separate Codex home defaults to `~/.local/share/relay-codex-home`, beside `~/.local/share/relay-codex-pins`; `targets.codex.home` and `targets.codex.pin_store` override those paths. Relay requires a pin by default, resolves `current` once per turn to its immutable executable, and uses its own `CODEX_HOME`. Its credential-home denials, whole-store write protection, explicit legacy opt-out and remaining person-run checks are documented in [the runtime qualification note](qualification/pinned-codex-runtime.md).
205
+
206
+ The default store is `~/.local/share/relay-codex-pins/`; `store` in the [example config](../scripts/codex-qualify/codex-qualifier.example.json) overrides it. Use a dedicated, trusted, built Relay checkout for `repo`, with no concurrent edits or builds. The runner never builds or updates that checkout and never reads your interactive Codex state. All child processes, including version probes, diagnostic tools, downloads and notifications, receive explicit scratch `HOME`, `CODEX_HOME` and `TMPDIR`. Stage 2 continues to use synthetic credentials and its own fake model; no signed-in turn runs.
207
+
208
+ ```text
209
+ relay-codex-pins/
210
+ versions/<version>-<binary-sha256-first-12>/ # qualified on this Mac
211
+ bin/codex
212
+ codex-package.json, codex-resources/, codex-path/, ... (complete vendor tree)
213
+ manifest.json
214
+ shipped/<version>-<binary-sha256-first-12>/ # a release's shipped pin, downloaded and verified here
215
+ bin/codex, ... , manifest.json # version, binary SHA-256, npm SRI, codesign, installedAt
216
+ current -> versions/... or shipped/...
217
+ previous -> versions/...
218
+ journal.jsonl
219
+ pending.json # only during a pointer transaction
220
+ lock/owner.json # one updater or rollback at a time
221
+ staging/ # publication and stale-lock tombstones
222
+ runs/<timestamp>-<random>/ # runner.log, stage2.log, verdict or failure
223
+ failed-qualifications/<key>.json # rejected verdicts, keyed by version, binary SHA and relay build
224
+ last-result.json
225
+ last-failure.json # last historical failure, retained after recovery
226
+ ```
227
+
228
+ The runner checks npm's stable `latest`, or an explicit `--version X.Y.Z`. It downloads `@openai/codex@<version>-darwin-arm64`, verifies npm's SHA-512 SRI before extraction, rejects archive traversal, links and special files, and runs no install scripts. It requires the exact `codex-cli <version>` output, `/usr/bin/codesign --verify --strict` with an Apple signature requirement for Team ID `2DC432GLL2`, and records the displayed signing identity and binary SHA-256. SRI authenticates bytes against npm metadata; it does not independently verify npm provenance. It resolves `rust-v<version>` (including annotated tags) to a Git commit and downloads the source at that commit.
229
+
230
+ After a verdict fails qualification, the runner atomically records the candidate version, binary SHA-256, relay build identity (`relayBuild`), timestamp (`at`) and retained `verdictPath` in `failed-qualifications/` inside the configured store. Each filename is the SHA-256 of the JSON array `[version, binarySha256, scheme, relay version, relay build sha256]`, so failures for different inputs remain remembered independently; a record from before build identities, keyed by a relay commit, matches no build, so those inputs are qualified again. After transaction recovery and the existing current-pin check, a later run acquires and verifies the candidate. If all three inputs match a recorded failure, it skips control/source acquisition and stage 2, writes `state: "skipped"` to `last-result.json`, and logs one skip line identifying the inputs and prior verdict. It sends no notification. Any changed version, binary SHA-256 or relay build runs qualification again. Runs without a parseable verdict (including crashes, kills and reboot interruptions), and errors after a passing verdict, are never added to this failure index. Promotion and recovery rules are unchanged.
231
+
232
+ Use `--force` to retry a recorded failure, with npm's latest or alongside `--version`:
233
+
234
+ ```sh
235
+ node scripts/codex-qualify/codex-qualifier.mjs ~/.local/share/relay-codex-qualifier/qualifier.json --run --force
236
+ node scripts/codex-qualify/codex-qualifier.mjs ~/.local/share/relay-codex-qualifier/qualifier.json --run --version 0.166.0 --force
237
+ ```
238
+
239
+ `--force` bypasses only the failed-qualification lookup; an already-current version still returns unchanged, and a candidate still needs every existing qualification and promotion check to pass. A passing verdict clears any prior failure record for those inputs, so a later driver, publication or promotion error cannot leave that old failure blocking retries.
240
+
241
+ The qualification invocation is exactly:
242
+
243
+ ```sh
244
+ node <copy>/scripts/codex-qualify/codex-stage2.mjs <copy> <out-dir> <version> <codex-bin> --source <codex-rs> --old-bin <bin>
245
+ ```
246
+
247
+ where `<copy>` is the verified copy of relay's build in the run's scratch directory.
248
+
249
+ `--old-bin` always means **0.163.0**: one check, a negative control, confirms that relay refuses stage 2 on a Codex older than stage 2 supports, and 0.163.0 is that Codex. By default the runner acquires and verifies that version into scratch too. An optional absolute `oldBin` config path may supply it; its signature and exact version are checked every time. It is never the previous pin. A zero exit status is insufficient: the verdict must be JSON with `ok === true`, `state === "passed"`, the requested version, `relayPath === "present"`, exactly the current schema's items (`stage2-v4`: items 1–33), all expected evidence parts from the reviewed driver, and every recorded part passed. Missing controls or Relay parts, missing verdicts, skipped parts, pending integration and unavailable GUI probes fail qualification.
250
+
251
+ Evidence requirements are versioned in the fixed, frozen `VERDICT_SCHEMAS` list in [codex-pin-store.mjs](../scripts/codex-qualify/codex-pin-store.mjs). `stage2-v1` is the exact Relay 1.1.0 set at `237bd74`; `stage2-v2` (Relay 1.1.1) adds item 10's `effort` evidence; `stage2-v3` adds item 12's `prefetch` positive control; `stage2-v4` (Relay 1.1.4) adds item 33, the decoy keychain under the never floor, and is the current schema. Pins already qualified under `stage2-v3` (items 1–32) stay valid. New driver verdicts record `verdictSchema`. Every new qualification is judged explicitly against `CURRENT_VERDICT_SCHEMA`, regardless of any older schema claimed in its verdict; after a pass, the runner records the schema it actually enforced. Unknown ids and custom requirement sets are invalid. When adding a requirement, add a new fixed schema entry and advance `CURRENT_VERDICT_SCHEMA`; preserve every historical entry, including its escalation parts, independently of the live driver.
252
+
253
+ On a pass, the complete vendor tree and `manifest.json` are staged on the store filesystem and renamed into `versions/`. The manifest records version, npm SRI, binary SHA-256, codesign identity/Team ID, qualification time, absolute verdict path, `verdictSchema`, `verdictSha256`, source commit/archive digest, relay build identity (`relayBuild`; earlier pins: the Relay commit), driver digest and Node version. New publications require the current schema. Published trees are never rewritten; old trees and their evidence remain available. Read-only file modes prevent accidental edits; Relay's separate whole-store sandbox protection is still required against agents running as you.
254
+
255
+ Stored receipts, including `current`, `previous`, promotion recovery and rollback targets, are checked against their publication's schema. A manifest without schema/digest fields always selects the fixed `stage2-v1` baseline, and a verdict without a schema id means `stage2-v1`. Its evidence must still contain every required item and part, with every recorded part passing. This keeps pre-schema 1.1.0 receipts usable after requirements grow; an unchanged check or rollback does not requalify them against today's requirements.
256
+
257
+ The verdict file lives outside the sealed vendor tree, in the run directory, and was neither sealed nor hashed by 1.1.0. For new receipts, the sealed manifest binds both its schema id and the SHA-256 of the verdict's exact bytes. Validation hashes and parses the same bytes, requires the verdict's schema to match the manifest, and rejects any content change, including removal or downgrading of the schema id. Legacy evidence retains its original trust model: its content is not hash-bound, but the sealed manifest's absent schema fixes the oldest allowed baseline, so changing that external verdict cannot choose a weaker or different schema. No receipt can supply its own requirements. The manifest is protected by read-only publication modes and the trusted store, rather than a cryptographic signature; an owner who can rewrite the store can defeat those protections.
258
+
259
+ Promotion first makes a temporary `previous` symlink and renames it over `previous`, then does the same for `current`. The `current` rename is the visibility commit point. The first successful run bootstraps `current` with no `previous`. `pending.json` records the transaction before the swaps; the next locked operation restores the old `previous` if `current` never switched, or finishes the journal append if it did. A torn/corrupt journal fails closed and requires inspection rather than silently discarding history. Each committed promotion/rollback appends a synced JSONL record. A qualified tree can remain unreferenced if publication is interrupted; the runner never promotes an incomplete tree.
260
+
261
+ Rollback takes the same lock and verifies that `previous` matches the journal's last recorded `from`, then swaps `previous` and `current` by the same temporary-link/rename procedure:
262
+
263
+ ```sh
264
+ node scripts/codex-qualify/codex-qualifier.mjs ~/.local/share/relay-codex-qualifier/qualifier.json --rollback
265
+ ```
266
+
267
+ **Rollback changes the binary only.** It does not undo `targets.codex.home` configuration, sessions, credential refreshes or database migrations. It does not establish home downgrade compatibility. Keep version/state compatibility and consistent database backup policy in the runtime rollout plan. The next scheduled check may qualify and promote npm's latest again; stop the agent first if a rollback must stay in place.
268
+
269
+ The lock is an exclusive directory with a PID and random owner token. A live PID is never evicted (including permission-denied liveness checks); a recent incomplete lock is busy. After 30 seconds a dead owner's lock or an abandoned partial lock can be recovered. Nonempty stale-lock tombstones are retained so concurrent recoverers cannot rename a new lock over an already claimed stale lock. A reused living PID conservatively keeps the lock busy. Do not remove a live lock by hand.
270
+
271
+ Stage 2 has a two-hour watchdog (`timeoutMs`, the most it can be set to): a full qualification includes one probe that runs for just over an hour (3601 seconds) and takes about 85 minutes. The runner sets `RELAY_TEST_PUBLIC_NET=1` and `RELAY_TEST_ESCALATION_LONG=1` for the driver, since a part left "not run" fails the verdict. Its driver starts in its own process group. The watchdog inventories descendants using macOS `ps -E` (uppercase: include environments), tracks PID/start identities and groups whose leaders have exited, and finds detached/reparented processes by the unique scratch paths in their environments. On timeout or SIGTERM/SIGINT it repeatedly freezes newly found identities until discovery converges, then kills the frozen processes and their groups. It preserves the parent chain until discovery finishes and never resumes frozen children before killing them. It looks again after the kill, stops any newly discovered survivors, and requires a final empty look; zombies have already exited. Inspection failure, nonconvergent discovery or surviving processes fail cleanup and prevent promotion. This is for this trusted model-free harness, not a general hostile-process containment boundary. Real macOS process-tree cleanup and logout behavior require the host checks below; fixture tests alone do not establish them.
272
+
273
+ Failure text goes to `runs/.../runner.log`, `failure.json`, `last-failure.json`, and launchd's stderr/stdout logs. Notifications use `/usr/bin/osascript` with a constant `display notification` script and the message as an argument, never interpolated AppleScript. Notification failure is logged too. Evidence and scratch directories are retained deliberately; monitor disk use and prune only inactive scratch/evidence that no manifest or transaction references. No automatic version eviction runs.
274
+
275
+ **Release gates run the suite's real-Codex tests on the pin too.** The sandbox tests that run a real Codex (`codex sandbox (installed Codex)` in `test/codex-permissions.test.ts`, and C1 in `test/security-boundary.test.ts`) take the absolute path in `RELAY_TEST_CODEX`, as the red team does. A gate sets it to the pinned executable (`versions/<version>-<sha>/bin/codex`, the one it qualifies and red-teams with) and sets `RELAY_REQUIRE_REAL_CODEX=1`, under which a missing `RELAY_TEST_CODEX` fails those tests: they neither skip nor fall back to PATH's or Homebrew's Codex, which update by themselves. Outside gates, with neither set, they use the first `codex` on PATH (Homebrew's for C1) and skip, saying so, when there is none.
276
+
277
+ ## Keeping up with Codex releases: the LaunchAgent
278
+
279
+ `relay qualify-codex` pins one release; relay keeps running it until you qualify another. The optional LaunchAgent runs the same qualifier six times a day, so each new Codex release is qualified and pinned without you. It is for a Mac that stays logged in to its desktop: each run takes about an hour and a half, needs the network and a desktop (Aqua) session, and spends no model usage. Nothing installs or loads the agent for you; these are the steps.
280
+
281
+ 1. **Set up a dedicated relay checkout and the qualifier's config.** The agent runs the qualifier from a checkout of its own, which nothing else edits or builds, so that a qualification never runs against a half-updated build:
282
+
283
+ ```sh
284
+ mkdir -p ~/.local/share/relay-codex-qualifier
285
+ git clone https://github.com/jbkjr/relay-mcp.git ~/.local/share/relay-codex-qualifier/relay
286
+ cd ~/.local/share/relay-codex-qualifier/relay
287
+ npm ci --ignore-scripts
288
+ npm run build
289
+ printf '{"repo":"%s","store":"%s","timeoutMs":7200000}\n' \
290
+ "$HOME/.local/share/relay-codex-qualifier/relay" "$HOME/.local/share/relay-codex-pins" \
291
+ > ~/.local/share/relay-codex-qualifier/qualifier.json
292
+ ```
293
+
294
+ `store` must be the pin store relay reads (`targets.codex.pin_store`, by default the one above), and both paths must be absolute; [codex-qualifier.example.json](../scripts/codex-qualify/codex-qualifier.example.json) shows the same shape. After you update this checkout later, run `npm run build` again before the next scheduled run: the agent's process supervisor imports the checkout's `dist/`, and scripts newer than the build can be incompatible with it.
295
+
296
+ 2. **Check that this Mac can run the qualifier**, from a terminal in your desktop login. The first command runs the qualifier's fixture tests, which need no network, Codex or launchd. The second runs its host checks, which start only synthetic Node processes (detached groups and an orphaned grandchild among them), check that a timeout and a cancellation stop all of them, and clean up even on failure:
297
+
298
+ ```sh
299
+ node --test --test-timeout=60000 test/codex-qualifier.test.ts test/qualify-codex.test.ts test/build-identity.test.ts test/codex-shipped-pin.test.ts
300
+ RELAY_QUALIFIER_HOST_CHECKS=1 node --test --test-timeout=60000 test/codex-qualifier-host.test.ts
301
+ ```
302
+
303
+ 3. **Run a first qualification by hand**, still in your desktop login. Without `--version` it takes npm's latest Codex; with `--version`, the release you name (the one `relay doctor` shows under "codex pin", say):
304
+
305
+ ```sh
306
+ node scripts/codex-qualify/codex-qualifier.mjs ~/.local/share/relay-codex-qualifier/qualifier.json --run
307
+ ```
308
+
309
+ It pins the release only when every item passes (33 today). Its run directory, under the store's `runs/`, holds the verdict and logs; `relay doctor` then shows the new pin.
310
+
311
+ 4. **Sign in once** with relay's Codex home, if you have not already (`relay install codex --write` makes the home first). With the default `targets.codex.home`:
312
+
313
+ ```sh
314
+ CODEX_HOME="$HOME/.local/share/relay-codex-home" ~/.local/share/relay-codex-pins/current/bin/codex login
315
+ ```
316
+
317
+ If `targets.codex.home` is set to another path, use that. On a remote or headless Mac, add `--device-auth`, which needs device code sign-in switched on in ChatGPT's Security settings. The scheduled qualification never uses this login: it runs Codex with scratch homes and its own fake model.
318
+
319
+ 5. **Install the agent, check notifications, and load it.** The installer prints the plist it would write; `--install` writes it, with the validated config and log directories and restrictive permissions, but does not load it:
320
+
321
+ ```sh
322
+ node scripts/codex-qualify/install-codex-qualifier.mjs --config ~/.local/share/relay-codex-qualifier/qualifier.json
323
+ node scripts/codex-qualify/install-codex-qualifier.mjs --config ~/.local/share/relay-codex-qualifier/qualifier.json --install
324
+ /usr/bin/osascript -e 'on run argv' -e 'display notification (item 1 of argv) with title "Relay Codex qualification"' -e 'end run' 'Relay qualifier notification check'
325
+ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/local.$(id -un).relay-codex-qualifier.plist
326
+ launchctl print gui/$(id -u)/local.$(id -un).relay-codex-qualifier
327
+ ```
328
+
329
+ The agent's launchd label is `local.<your login name>.relay-codex-qualifier`, with the name lowercased and any character other than a letter, digit or hyphen turned into a hyphen; `--label` sets another. The installer prints the two `launchctl` lines with the label it used: run those if your login name has other characters. An existing plist of that name is replaced only when it is itself a qualifier agent. The installer resolves Node to an absolute installed version, never a shell's temporary link; `--node /absolute/node` and `--logs /absolute/logs` override its choices, and you rerun it if that Node version is removed. The notification check is there because the qualifier reports failures as macOS notifications: allow them for Script Editor, and check Focus and lock-screen settings.
330
+
331
+ The [plist template](../scripts/codex-qualify/relay-codex-qualifier.plist) requires `Aqua`, runs at load and at 02:15, 06:15, 10:15, 14:15, 18:15 and 22:15, has no KeepAlive, uses umask 077 and a 120-second shutdown allowance, and writes its output under `~/Library/Logs/relay-codex-qualifier/`. It waits for a desktop login after logout or reboot, and sleep can merge missed runs into one. Stop it with `launchctl bootout gui/$(id -u)/<label>`, which sends the runner SIGTERM; the watchdog then stops what it started.
332
+
333
+ Each run leaves `current` alone unless a new release passes in full: a failed download, signature, qualification, a network outage or a missing desktop session keeps the pin you have. Look at `last-result.json` and `last-failure.json` in the store, or the logs above, to see what the last run did.
@@ -0,0 +1,214 @@
1
+ // Oracles the probes share: process-tree walks (survivor checks), a passive look at relay's reserved
2
+ // range, and best-effort scans for the executor token and for marker files outside the roots.
3
+ import { execFileSync, spawnSync } from "node:child_process";
4
+ import { DatabaseSync } from "node:sqlite";
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import crypto from "node:crypto";
8
+
9
+ export const RELAY_RANGE = [47200, 47263];
10
+
11
+ /** Read a node row from MY scratch registry: its params_json (codex_confinement) and worktree. */
12
+ export function readNode(relayHome, nodeId) {
13
+ const d = new DatabaseSync(path.join(relayHome, "relay.db"));
14
+ try {
15
+ const row = d.prepare("SELECT id, cwd, worktree, params_json, status FROM nodes WHERE id = ?").get(nodeId);
16
+ if (!row) return null;
17
+ let params = {};
18
+ try { params = JSON.parse(row.params_json ?? "{}"); } catch { /* keep {} */ }
19
+ return { ...row, params };
20
+ } finally {
21
+ d.close();
22
+ }
23
+ }
24
+
25
+ /** True if dir is the top of a git worktree right now. */
26
+ export function isGitWorktree(dir) {
27
+ if (!dir) return false;
28
+ const r = spawnSync("git", ["-C", dir, "rev-parse", "--is-inside-work-tree"], { encoding: "utf8" });
29
+ return r.status === 0 && /true/.test(r.stdout);
30
+ }
31
+
32
+ /** A file's size, or null when it is not there. */
33
+ export const fileSize = (file) => { try { return file ? fs.statSync(file).size : null; } catch { return null; } };
34
+
35
+ /**
36
+ * Whether a file a probe's process kept writing stopped growing after teardown, from two sizes read
37
+ * apart. Only a file that was written counts (the writer ran: the positive control); a missing or
38
+ * empty one, 0 = 0, shows nothing and does not pass.
39
+ */
40
+ export const frozenAfter = (size1, size2) => Number.isInteger(size1) && size1 > 0 && size1 === size2;
41
+
42
+ /**
43
+ * The positive control for a turn's refused nc connects, reach-denied-port's: the job binds its own
44
+ * block port ($PORT, which it may use) and connects to it with the same nc, printing self_block=<rc>.
45
+ * Run it in the same command as the connects it vouches for. The listener lives until the turn
46
+ * ends; its stdio goes to /dev/null so the exec does not wait on its open output until Codex yields.
47
+ */
48
+ export const NC_SELF_CONTROL = [
49
+ `/usr/bin/perl -MIO::Socket::INET -e 'my $s=IO::Socket::INET->new(LocalAddr=>"127.0.0.1",LocalPort=>$ENV{PORT},Listen=>5,ReuseAddr=>1) or exit 9; fork and exit 0; while(my $c=$s->accept){close $c}' >/dev/null 2>&1 </dev/null &`,
50
+ "sleep 0.4",
51
+ `/usr/bin/nc -z -G1 -w1 127.0.0.1 $PORT >/dev/null 2>&1; echo "self_block=$?"`,
52
+ ];
53
+
54
+ /**
55
+ * Whether `out` shows the nc connect it printed as `<tag>=<rc>` refused (rc not 0) beside a working
56
+ * control (self_block=0, NC_SELF_CONTROL): without the control, a non-zero code may only mean that
57
+ * nc never ran.
58
+ */
59
+ export function refusedBesideControl(out, tag) {
60
+ const rc = (t) => new RegExp(`\\b${t}=(\\d+)`).exec(out ?? "")?.[1];
61
+ return rc("self_block") === "0" && rc(tag) !== undefined && rc(tag) !== "0";
62
+ }
63
+
64
+ /** True once pid is gone. */
65
+ export const gone = (pid) => {
66
+ try { process.kill(pid, 0); return false; } catch (e) { return e.code === "ESRCH"; }
67
+ };
68
+
69
+ /**
70
+ * The whole process table as {pid, ppid, command}. Throws when ps fails or lists nothing: an empty
71
+ * table would pass every survivor check that reads it.
72
+ */
73
+ export function psTable() {
74
+ const r = spawnSync("/bin/ps", ["-axww", "-o", "pid=,ppid=,command="], { encoding: "utf8", maxBuffer: 64 << 20 });
75
+ if (r.error || r.status !== 0) throw new Error(`ps failed (${r.error?.message ?? `exit ${r.status}`}): the process table cannot be read, so no survivor check can pass`);
76
+ const table = (r.stdout || "").split("\n").map((l) => /^\s*(\d+)\s+(\d+)\s+([\s\S]*)$/.exec(l)).filter(Boolean)
77
+ .map((m) => ({ pid: Number(m[1]), ppid: Number(m[2]), command: m[3] }));
78
+ if (!table.length) throw new Error("ps listed no processes: the process table cannot be read, so no survivor check can pass");
79
+ return table;
80
+ }
81
+
82
+ /** Every descendant pid of root (inclusive), by the current process table. */
83
+ export function descendants(rootPid) {
84
+ const table = psTable();
85
+ const byParent = new Map();
86
+ for (const p of table) { if (!byParent.has(p.ppid)) byParent.set(p.ppid, []); byParent.get(p.ppid).push(p); }
87
+ const seen = [];
88
+ const stack = [rootPid];
89
+ while (stack.length) {
90
+ const pid = stack.pop();
91
+ for (const c of byParent.get(pid) ?? []) { seen.push(c); stack.push(c.pid); }
92
+ }
93
+ return seen;
94
+ }
95
+
96
+ /** Processes anywhere that look like a Codex control plane (exec-server / app-server / code-mode). */
97
+ export function codexProcesses() {
98
+ return psTable().filter((p) => /\bcodex\b/i.test(p.command) && /(exec-server|app-server|--listen ws:\/\/127\.0\.0\.1:|code-mode-host)/.test(p.command));
99
+ }
100
+
101
+ /**
102
+ * The Codex control-plane processes that are MY run's, discriminated by MY unique scratch root path
103
+ * appearing in the process's argv+environment (ps eww). The executor's CODEX_HOME/TMPDIR and the app
104
+ * server's CODEX_HOME both live under the scratch root, so this reliably includes mine (even when the
105
+ * executor is spawned detached) and reliably excludes sibling stage-2 agents and the user's own
106
+ * ChatGPT.app Codex (different roots) — which are therefore never flagged as survivors or touched.
107
+ */
108
+ export function myCodexProcesses(scratchRoot) {
109
+ return codexProcesses().filter((p) => psEnv(p.pid).includes(scratchRoot));
110
+ }
111
+
112
+ /** My run's executor (exec-server), scoped by scratch root. */
113
+ export function findExecutorByScratch(scratchRoot) {
114
+ const p = myCodexProcesses(scratchRoot).find((q) => /exec-server --listen ws:\/\/127\.0\.0\.1:\d+/.test(q.command));
115
+ if (!p) return null;
116
+ const e = psEnv(p.pid);
117
+ return {
118
+ pid: p.pid,
119
+ sha: /--ws-token-sha256 ([0-9a-f]{64})/.exec(e)?.[1] ?? null,
120
+ port: Number(/--listen ws:\/\/127\.0\.0\.1:(\d+)/.exec(e)?.[1] ?? 0),
121
+ command: p.command,
122
+ };
123
+ }
124
+
125
+ /** My run's app server pid, scoped by scratch root. */
126
+ export function findAppServerByScratch(scratchRoot) {
127
+ return myCodexProcesses(scratchRoot).find((q) => /app-server/.test(q.command))?.pid ?? 0;
128
+ }
129
+
130
+ /** The executor pid and the sha256 in its argv, or null. */
131
+ export function findExecutor() {
132
+ const p = psTable().find((q) => /exec-server --listen ws:\/\/127\.0\.0\.1:\d+/.test(q.command));
133
+ if (!p) return null;
134
+ const sha = /--ws-token-sha256 ([0-9a-f]{64})/.exec(p.command)?.[1] ?? null;
135
+ const port = Number(/--listen ws:\/\/127\.0\.0\.1:(\d+)/.exec(p.command)?.[1] ?? 0);
136
+ return { pid: p.pid, sha, port, command: p.command };
137
+ }
138
+
139
+ /** Passive look (lsof, no connect) at what is listening in relay's reserved range. Never a scan/probe. */
140
+ export function listeningInRelayRange() {
141
+ const r = spawnSync("/usr/bin/lsof", ["-nP", `-iTCP:${RELAY_RANGE[0]}-${RELAY_RANGE[1]}`, "-sTCP:LISTEN"], { encoding: "utf8" });
142
+ return (r.stdout || "").trim();
143
+ }
144
+
145
+ /** `ps eww` for a pid (argv + environment), for token/leak inspection. */
146
+ export const psEnv = (pid) => spawnSync("/bin/ps", ["eww", "-o", "command=", "-p", String(pid)], { encoding: "utf8" }).stdout || "";
147
+
148
+ /**
149
+ * Best-effort scan for executor-token leakage across a set of directories, plus given argv/env
150
+ * strings. We do not hold relay's in-memory raw token, so we flag: any `authBearerToken`, any
151
+ * `Bearer <long>`, and any 64-hex string that is NOT the known executor sha (the sha legitimately
152
+ * appears in the executor's own argv). Hits are returned for manual review; [] is clean.
153
+ * The strong, token-aware oracle lives in WP-C's in-process live test (redaction knows the token).
154
+ */
155
+ // Trusted fixture assets now include a staged native binary and the copied distribution. Their
156
+ // source contains protocol names and public digests, not a turn's future memory-only token.
157
+ // Ignore only bytes snapshotted BEFORE launch; changed/missing assets remain a failing oracle.
158
+ export function snapshotFixtureAssets(roots) {
159
+ const baseline = new Map();
160
+ const walk = dir => {
161
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
162
+ const file = path.join(dir, e.name);
163
+ if (e.isDirectory()) walk(file);
164
+ else if (e.isFile()) baseline.set(file, crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"));
165
+ }
166
+ };
167
+ for (const root of roots) walk(root);
168
+ return baseline;
169
+ }
170
+
171
+ export function tokenLeakHits({ dirs = [], extraText = [], knownSha = null, baseline = new Map() }) {
172
+ const hits = [];
173
+ const bearer = /Bearer\s+[A-Za-z0-9+/=_-]{16,}/g;
174
+ const hex64 = /\b[0-9a-f]{64}\b/g;
175
+ const scan = (label, text) => {
176
+ if (!text) return;
177
+ if (/authBearerToken/.test(text)) hits.push({ label, why: "authBearerToken literal" });
178
+ for (const m of text.match(bearer) ?? []) hits.push({ label, why: `bearer-like: ${m.slice(0, 24)}…` });
179
+ // A person-path heartbeat is named by the one-way root-token identity it also contains. Exempt
180
+ // only that self-identifying value: a JSON file directly in person-paths whose 64-hex stem is
181
+ // the matched value. Other digests in the same file, nested files and bearer-like strings still
182
+ // hit the oracle.
183
+ const ownPersonPathIdentity = path.basename(path.dirname(label)) === "person-paths"
184
+ && /^[0-9a-f]{64}\.json$/.test(path.basename(label)) ? path.basename(label, ".json") : null;
185
+ // relay.db's session params record the policy's public digest under exactly this key.
186
+ const neverPolicyHash = (m) => path.basename(label) === "relay.db" && text.includes(`"never_policy":{"hash":"${m}"`);
187
+ for (const m of text.match(hex64) ?? []) if (m !== knownSha && m !== ownPersonPathIdentity && !neverPolicyHash(m)) hits.push({ label, why: `64-hex (not the known sha): ${m.slice(0, 12)}…` });
188
+ };
189
+ for (const t of extraText) scan("argv/env", t);
190
+ const walk = (d) => {
191
+ let ents;
192
+ try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
193
+ for (const e of ents) {
194
+ const p = path.join(d, e.name);
195
+ if (e.isDirectory()) walk(p);
196
+ else if (e.isFile()) { try {
197
+ const bytes = fs.readFileSync(p);
198
+ if (baseline.has(p)) {
199
+ if (crypto.createHash("sha256").update(bytes).digest("hex") === baseline.get(p)) continue;
200
+ hits.push({ label: p, why: "trusted fixture asset changed after launch" });
201
+ }
202
+ scan(p, bytes.toString("latin1"));
203
+ } catch { /* raced/gone */ } }
204
+ }
205
+ };
206
+ for (const d of dirs) walk(d);
207
+ for (const file of baseline.keys()) if (!fs.existsSync(file)) hits.push({ label: file, why: "trusted fixture asset removed after launch" });
208
+ return hits;
209
+ }
210
+
211
+ /** Kill a pid, waiting briefly. Only used to clean up a survivor a probe detects. */
212
+ export function killNow(pid) {
213
+ try { execFileSync("/bin/kill", ["-9", String(pid)]); } catch { /* already gone */ }
214
+ }
@@ -0,0 +1,35 @@
1
+ // Tiny check/report helpers shared by the e2e runner and the probes.
2
+
3
+ /** One named oracle: pass is a boolean; detail is shown either way. */
4
+ export function check(name, pass, detail) {
5
+ return { name, pass: Boolean(pass), detail };
6
+ }
7
+
8
+ /**
9
+ * Print a scenario's checks and a short diagnostic tail. Returns true iff every check passed.
10
+ * `bundle` is the runScenario result (for stderr / status on failure).
11
+ */
12
+ export function report(title, checks, bundle) {
13
+ if (bundle?.modelRequests) {
14
+ const exercised = bundle.modelRequests.length > 0 && bundle.outputs?.length > 0 && !bundle.modelErrors?.length;
15
+ checks = [
16
+ check("scripted model reached and tool output returned (no setup-refusal pass)",
17
+ exercised,
18
+ { requests: bundle.modelRequests.length, outputs: bundle.outputs?.length, status: bundle.result?.status }),
19
+ check("scripted probe hooks succeeded", !bundle.modelErrors?.length, bundle.modelErrors),
20
+ ...checks.map(c => exercised ? c : { ...c, pass: false, detail: "probe did not execute successfully; no containment claim" }),
21
+ ];
22
+ }
23
+ const ok = checks.every((c) => c.pass);
24
+ console.log(`\n=== ${title}: ${ok ? "PASS" : "FAIL"} ===`);
25
+ for (const c of checks) {
26
+ console.log(` [${c.pass ? "ok" : "XX"}] ${c.name}` + (c.pass ? "" : ` -> ${JSON.stringify(c.detail)}`));
27
+ }
28
+ if (!ok && bundle) {
29
+ console.log(` status: ${JSON.stringify(bundle.result)?.slice(0, 400)}`);
30
+ const err = (bundle.stderr ?? []).join("");
31
+ if (err) console.log(` relay stderr (tail):\n${err.slice(-1600)}`);
32
+ }
33
+ if (bundle?.cleanup?.length) console.log(` cleanup: ${bundle.cleanup.join(" ; ")}`);
34
+ return ok;
35
+ }