@jbkjr/relay 0.0.0-stage → 1.2.1

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 +386 -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 +1525 -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 +320 -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 +637 -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 +329 -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 +629 -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 +1502 -0
  186. package/docs/pinned-codex.md +321 -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
package/package.json CHANGED
@@ -1,6 +1,84 @@
1
1
  {
2
2
  "name": "@jbkjr/relay",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.1",
4
+ "description": "Lets coding agents of different model families (Claude Code, OpenAI Codex CLI) call each other: delegate, consult, discuss and review across families, over one MCP server",
5
+ "license": "MIT",
6
+ "author": "Jack Koch",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/jbkjr/relay-mcp.git"
10
+ },
11
+ "homepage": "https://github.com/jbkjr/relay-mcp#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/jbkjr/relay-mcp/issues"
14
+ },
15
+ "type": "module",
16
+ "bin": {
17
+ "relay": "dist/cli.js"
18
+ },
19
+ "files": [
20
+ "dist/",
21
+ "npm-shrinkwrap.json",
22
+ "codex-pin.json",
23
+ "bin/",
24
+ "adapters/",
25
+ "scripts/codex-qualify/",
26
+ "test/codex-permissions.test.ts",
27
+ "test/mediated-network.test.ts",
28
+ "test/mediated-proxy.test.ts",
29
+ "test/never-policy.test.ts",
30
+ "test/never-tools.test.ts",
31
+ "test/proxy.test.ts",
32
+ "test/restart-overlay.test.ts",
33
+ "test/restart-overlay-live.test.ts",
34
+ "test/restart-overlay-profile.test.ts",
35
+ "test/stable-surfaces.test.ts",
36
+ "test/stage2-escalation.test.ts",
37
+ "test/stage2-escalation-live.test.ts",
38
+ "test/stage2-escalation-qualification.test.ts",
39
+ "test/stage2-executor.test.ts",
40
+ "test/stage2-grant.test.ts",
41
+ "test/stage2-native-live.test.ts",
42
+ "test/stage2-network-decisions.test.ts",
43
+ "test/stage2-probe.test.ts",
44
+ "test/stage2-standing-live.test.ts",
45
+ "test/wp4-adapters.test.ts",
46
+ "test/wp4-interlock.test.ts",
47
+ "test/helpers.ts",
48
+ "test/host-env.ts",
49
+ "test/keychain-decoy.ts",
50
+ "test/live-scope.ts",
51
+ "test/native-temp-alias.ts",
52
+ "test/process-home.ts",
53
+ "test/temp-root.ts",
54
+ "test/fixtures/",
55
+ "test/stubs/",
56
+ "experiments/stage2-redteam/lib/oracles.mjs",
57
+ "experiments/stage2-redteam/lib/report.mjs",
58
+ "docs/pinned-codex.md",
59
+ "docs/UPGRADING.md",
60
+ "LICENSES/",
61
+ "SECURITY.md"
62
+ ],
63
+ "engines": {
64
+ "node": ">=24.15"
65
+ },
66
+ "scripts": {
67
+ "build": "tsc -p tsconfig.json && chmod +x dist/cli.js && node scripts/build-sbcheck.mjs && node scripts/stamp-build.mjs",
68
+ "test": "npm run build && node --test --test-timeout=600000 --test-concurrency=8 test/*.test.ts",
69
+ "typecheck": "tsc -p tsconfig.json --noEmit",
70
+ "prepack": "node scripts/check-pack.mjs"
71
+ },
72
+ "dependencies": {
73
+ "@modelcontextprotocol/sdk": "1.32.1",
74
+ "smol-toml": "1.9.1",
75
+ "zod": "4.6.6"
76
+ },
77
+ "devDependencies": {
78
+ "@types/node": "^26.6.5",
79
+ "typescript": "^7.0.2"
80
+ },
81
+ "publishConfig": {
82
+ "access": "public"
83
+ }
84
+ }
@@ -0,0 +1,353 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import crypto from "node:crypto";
4
+
5
+ export const OLD_VERSION = "0.163.0";
6
+ export const TEAM_ID = "2DC432GLL2";
7
+ const stable = /^\d+\.\d+\.\d+$/;
8
+ const digest = /^[a-f0-9]{64}$/;
9
+ // versions/: qualified on this Mac (manifest with its stage-2 verdict). shipped/: a release's
10
+ // shipped pin (decision 18), downloaded and verified against it (manifest with `shipped`, no verdict).
11
+ // The two never share a tree: a kind is fixed by the directory and checked against the manifest.
12
+ const targetPattern = /^(versions|shipped)\/(\d+\.\d+\.\d+)-([a-f0-9]{12})$/;
13
+ export const SHIPPED_PIN_FORMAT = "relay-shipped-codex-pin-v1";
14
+ export const LEGACY_VERDICT_SCHEMA = "stage2-v1";
15
+ export const CURRENT_VERDICT_SCHEMA = "stage2-v4";
16
+ const freezeParts = (parts) => Object.freeze(Object.fromEntries(Object.entries(parts).map(([id, names]) => [id, Object.freeze([...names])])));
17
+ // Fixed snapshot of EXPECTED_PARTS at 237bd74 (Relay 1.1.0), including escalation parts.
18
+ // Never derive a historical schema from the live driver or edit it when requirements grow.
19
+ const schemaV1 = freezeParts({
20
+ 1: ["codex", "control", "relay"], 2: ["codex"], 3: ["outside", "settings", "relay"],
21
+ 4: ["codex", "relay"], 5: ["codex"], 6: ["codex", "relay"], 7: ["codex", "relay"],
22
+ 8: ["relay"], 9: ["relay"], 10: ["tools", "isolate", "relay"],
23
+ 11: ["subagent", "resume", "unbound", "control", "selfStart", "noLocal", "goalControl", "relay"],
24
+ 12: ["control", "codex"], 13: ["codex", "relay"],
25
+ 14: ["direct", "code_mode_only", "long", "relay"], 15: ["startup", "credentials", "midTurn"],
26
+ 16: ["coexist", "admission"], 17: ["codex", "control"], 18: ["reconnect", "eof"],
27
+ 19: ["sessions", "retry"], 20: ["relay"], 21: ["disarmed"], 22: ["v1", "v2"],
28
+ 23: ["unit", "surfaces", "freshResume", "overlay"],
29
+ 24: ["unit", "worker", "cancel", "http", "code", "mismatch"],
30
+ 25: ["unit"], 26: ["unit", "hostRoots", "crash"],
31
+ 27: ["unit", "planner", "kernel", "profiles"],
32
+ 28: ["unit", "addresses", "worker", "public", "crossJobCrash"],
33
+ 29: ["unit", "decisions", "local", "nativeProfiles"], 30: ["long"],
34
+ 31: ["unit", "executor", "live"], 32: ["unit", "accounting", "planner", "kernel", "worker"],
35
+ });
36
+ // Item 10 gains the effort evidence (Relay 1.1.1).
37
+ const schemaV2 = freezeParts({ ...schemaV1, 10: [...schemaV1[10], "effort"] });
38
+ // New requirements get a new fixed entry and advance CURRENT_VERDICT_SCHEMA; retain old entries.
39
+ export const VERDICT_SCHEMAS = Object.freeze({
40
+ [LEGACY_VERDICT_SCHEMA]: schemaV1,
41
+ "stage2-v2": schemaV2,
42
+ // Item 12 gains the discovery-prefetch positive control.
43
+ "stage2-v3": freezeParts({ ...schemaV2, 12: [...schemaV2[12], "prefetch"] }),
44
+ // Item 33: the keychain under the never floor from native Codex turns (a floored decoy keychain and its control).
45
+ "stage2-v4": freezeParts({ ...schemaV2, 12: [...schemaV2[12], "prefetch"], 33: ["codex"] }),
46
+ });
47
+ export const EXPECTED_PARTS = VERDICT_SCHEMAS[CURRENT_VERDICT_SCHEMA];
48
+ const knownSchema = (id) => typeof id === "string" && Object.hasOwn(VERDICT_SCHEMAS, id);
49
+ export const sha256 = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
50
+ const json = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
51
+
52
+ /** Exit status alone is never a qualification verdict. Unknown/empty parts fail closed too. */
53
+ export function judgeVerdict(v, version, schemaId = CURRENT_VERDICT_SCHEMA) {
54
+ const why = [];
55
+ if (!knownSchema(schemaId)) return { ok: false, why: [`unknown verdict schema: ${schemaId}`] };
56
+ if (v?.verdictSchema !== undefined && !knownSchema(v.verdictSchema)) why.push(`unknown verdict schema: ${v.verdictSchema}`);
57
+ const expected = VERDICT_SCHEMAS[schemaId];
58
+ if (v?.ok !== true || v?.state !== "passed") why.push("verdict did not pass");
59
+ if (v?.version !== version) why.push("verdict version mismatch");
60
+ if (v?.relayPath !== "present") why.push("relay path missing");
61
+ const items = v?.items;
62
+ const object = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
63
+ if (!object(items) || Object.keys(items).sort((a, b) => +a - +b).join(",") !== Object.keys(expected).join(",")) why.push(`expected exactly items ${Object.keys(expected).join(",")}`);
64
+ for (const [id, item] of Object.entries(object(items) ? items : {})) {
65
+ if (item?.state !== "passed" || !object(item.parts) || !Object.keys(item.parts).length) { why.push(`item ${id} lacks passed evidence`); continue; }
66
+ for (const name of expected[id] ?? []) if (!Object.hasOwn(item.parts, name)) why.push(`item ${id}.${name} evidence missing`);
67
+ for (const [name, part] of Object.entries(item.parts)) if (part?.state !== "passed") why.push(`item ${id}.${name} did not pass`);
68
+ }
69
+ return { ok: why.length === 0, why };
70
+ }
71
+
72
+ export function atomicJson(file, value) {
73
+ const tmp = `${file}.${crypto.randomUUID()}.tmp`;
74
+ const fd = fs.openSync(tmp, "wx", 0o600);
75
+ try { fs.writeFileSync(fd, JSON.stringify(value, null, 2) + "\n"); fs.fsyncSync(fd); }
76
+ finally { fs.closeSync(fd); }
77
+ try { fs.renameSync(tmp, file); } finally { fs.rmSync(tmp, { force: true }); }
78
+ }
79
+
80
+ export function validateManifest(m) {
81
+ if (!m || !stable.test(m.version) || !digest.test(m.binarySha256) ||
82
+ !/^sha512-[A-Za-z0-9+/]{86}==$/.test(m.npmIntegrity ?? "") ||
83
+ m.codesign?.teamId !== TEAM_ID || typeof m.codesign?.identity !== "string" || !m.codesign.identity ||
84
+ !Number.isFinite(Date.parse(m.qualifiedAt)) || !path.isAbsolute(m.verdictPath ?? "") ||
85
+ !/^[a-f0-9]{40}$/.test(m.sourceCommit ?? "")) throw new Error("invalid pin manifest");
86
+ const hasSchema = Object.hasOwn(m, "verdictSchema"), hasDigest = Object.hasOwn(m, "verdictSha256");
87
+ if (hasSchema && !knownSchema(m.verdictSchema)) throw new Error(`unknown verdict schema: ${m.verdictSchema}`);
88
+ if (hasSchema !== hasDigest || (hasDigest && !digest.test(m.verdictSha256))) throw new Error("invalid pin manifest verdict schema/digest");
89
+ // New pins name relay's build (relay-build-v2, src/core/build-identity.ts; earlier builds wrote
90
+ // relay-build-v1, without the dependency lock); earlier ones name a relay commit (relayCommit).
91
+ // Each is a record of what ran, and none binds a local pin to the relay running now.
92
+ // The shape of src/core/build-identity.ts isBuildIdentity, kept here because release-watch's
93
+ // detect job imports this module (through codex-stage2.mjs) before anything is built.
94
+ const b = m.relayBuild;
95
+ if (Object.hasOwn(m, "relayBuild") && !isBuild(b, BUILD_RECORD_SCHEMES)) throw new Error("invalid pin manifest relay build");
96
+ // A shipped tree's manifest (validateShippedTreeManifest) has no verdict, source commit or
97
+ // qualification time, so it can never pass here, and a local one has keys a shipped one refuses.
98
+ return m;
99
+ }
100
+
101
+ // src/core/build-identity.ts BUILD_SCHEME, and the schemes it reads as records (LEGACY_BUILD_SCHEMES);
102
+ // test/codex-shipped-pin.test.ts holds these to that module.
103
+ export const BUILD_SCHEME = "relay-build-v2";
104
+ export const BUILD_RECORD_SCHEMES = Object.freeze([BUILD_SCHEME, "relay-build-v1"]);
105
+ const isBuild = (b, schemes = [BUILD_SCHEME]) => !!b && typeof b === "object" && !Array.isArray(b) && Object.keys(b).sort().join(",") === "scheme,sha256,version" &&
106
+ schemes.includes(b.scheme) && typeof b.version === "string" && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(b.version) &&
107
+ typeof b.sha256 === "string" && /^[a-f0-9]{64}$/.test(b.sha256);
108
+ const keysAre = (v, keys) => !!v && typeof v === "object" && !Array.isArray(v) && Object.keys(v).sort().join(",") === [...keys].sort().join(",");
109
+
110
+ /**
111
+ * A release's shipped pin, exactly as src/core/shipped-pin.ts parseShippedPin takes it (kept here
112
+ * because this module loads before any build; test/codex-shipped-pin.test.ts holds the two to the
113
+ * same answers). Only format, codex {version, npmIntegrity} and relay's build identity: any other
114
+ * field, machine-specific or not, is refused.
115
+ */
116
+ export function validateShippedPin(v) {
117
+ if (!keysAre(v, ["format", "codex", "relay"]) || v.format !== SHIPPED_PIN_FORMAT) throw new Error("invalid shipped Codex pin: exactly format, codex and relay, in the known format");
118
+ if (!keysAre(v.codex, ["version", "npmIntegrity"]) || !stable.test(v.codex.version ?? "") || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(v.codex.npmIntegrity ?? "")) throw new Error("invalid shipped Codex pin: codex is exactly a stable version and npm's sha512 integrity");
119
+ if (isBuild(v.relay, BUILD_RECORD_SCHEMES) && v.relay.scheme !== BUILD_SCHEME) throw new Error(`invalid shipped Codex pin: relay's build is named under ${v.relay.scheme}, which does not cover the dependency lock; a shipped pin needs ${BUILD_SCHEME}`);
120
+ if (!isBuild(v.relay)) throw new Error("invalid shipped Codex pin: relay is exactly relay's build identity");
121
+ return v;
122
+ }
123
+
124
+ /**
125
+ * The manifest of a shipped/ tree: a Codex release as relay downloaded and verified it here against
126
+ * a release's shipped pin (npm's sha512 integrity, Apple's signature and OpenAI's Team ID, the exact
127
+ * version). No verdict: that evidence is the maintainer's. The tree is not bound to one relay
128
+ * build, so releases that ship the same Codex share it; relay binds it at every turn instead, to
129
+ * the shipped pin in the package it runs from (src/backends/codex-pin.ts).
130
+ */
131
+ export function validateShippedTreeManifest(m) {
132
+ if (!keysAre(m, ["version", "binarySha256", "npmIntegrity", "codesign", "installedAt"]) || !stable.test(m.version ?? "") ||
133
+ !digest.test(m.binarySha256 ?? "") || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(m.npmIntegrity ?? "") ||
134
+ m.codesign?.teamId !== TEAM_ID || typeof m.codesign?.identity !== "string" || !m.codesign.identity ||
135
+ !Number.isFinite(Date.parse(m.installedAt))) throw new Error("invalid shipped pin tree manifest");
136
+ return m;
137
+ }
138
+
139
+ export function readManifest(dir) {
140
+ const m = validateManifest(json(path.join(dir, "manifest.json")));
141
+ if (sha256(path.join(dir, "bin/codex")) !== m.binarySha256) throw new Error("pin binary digest mismatch");
142
+ // The external run file stays available for diagnosis. Bind new receipts to its exact bytes
143
+ // and schema in the sealed manifest; unversioned manifests always mean the fixed v1 baseline.
144
+ const bytes = fs.readFileSync(m.verdictPath);
145
+ if (m.verdictSha256 && crypto.createHash("sha256").update(bytes).digest("hex") !== m.verdictSha256) throw new Error("pin verdict digest mismatch");
146
+ const v = JSON.parse(bytes.toString("utf8"));
147
+ const schemaId = m.verdictSchema ?? LEGACY_VERDICT_SCHEMA;
148
+ const verdict = judgeVerdict(v, m.version, schemaId);
149
+ if (!verdict.ok) throw new Error(`pin verdict invalid: ${verdict.why.join("; ")}`);
150
+ if ((v.verdictSchema ?? LEGACY_VERDICT_SCHEMA) !== schemaId) throw new Error("pin verdict schema disagrees with manifest");
151
+ return m;
152
+ }
153
+
154
+ export function initStore(store) {
155
+ for (const d of [store, path.join(store, "versions"), path.join(store, "shipped"), path.join(store, "staging"), path.join(store, "runs")]) fs.mkdirSync(d, { recursive: true, mode: 0o700 });
156
+ }
157
+
158
+ /** The store is trusted, but reject accidental external pointers and mutable directory aliases. */
159
+ export function validateTarget(store, target) {
160
+ const match = targetPattern.exec(target ?? "");
161
+ if (!match) throw new Error("pin target must be a relative versions/ or shipped/<version>-<digest12> path");
162
+ const dir = path.join(store, target);
163
+ if (fs.realpathSync(dir) !== path.join(fs.realpathSync(store), target)) throw new Error("pin target traverses a symlink");
164
+ if (fs.statSync(dir).mode & 0o222) throw new Error("pin publication was not sealed; inspect the unreferenced tree");
165
+ const m = match[1] === "shipped" ? readShippedTree(dir) : readManifest(dir);
166
+ if (m.version !== match[2] || m.binarySha256.slice(0, 12) !== match[3]) throw new Error("pin target disagrees with manifest");
167
+ return m;
168
+ }
169
+
170
+ export function readShippedTree(dir) {
171
+ const m = validateShippedTreeManifest(json(path.join(dir, "manifest.json")));
172
+ if (sha256(path.join(dir, "bin/codex")) !== m.binarySha256) throw new Error("pin binary digest mismatch");
173
+ return m;
174
+ }
175
+
176
+ /** Whether a target names a shipped pin's tree (shipped/) rather than a local qualification's (versions/). */
177
+ export const isShippedTarget = (target) => targetPattern.exec(target ?? "")?.[1] === "shipped";
178
+
179
+ export function pointer(store, name) {
180
+ const file = path.join(store, name);
181
+ let st;
182
+ try { st = fs.lstatSync(file); } catch (e) { if (e.code === "ENOENT") return null; throw e; }
183
+ if (!st.isSymbolicLink()) throw new Error(`${name} must be a symlink`);
184
+ const target = fs.readlinkSync(file);
185
+ validateTarget(store, target);
186
+ return target;
187
+ }
188
+
189
+ export function swapPointer(store, name, target) {
190
+ validateTarget(store, target);
191
+ const tmp = path.join(store, `.${name}-${crypto.randomUUID()}`);
192
+ try { fs.symlinkSync(target, tmp); fs.renameSync(tmp, path.join(store, name)); }
193
+ finally { fs.rmSync(tmp, { force: true }); }
194
+ }
195
+
196
+ export function readJournal(store) {
197
+ let text;
198
+ try { text = fs.readFileSync(path.join(store, "journal.jsonl"), "utf8"); }
199
+ catch (e) { if (e.code === "ENOENT") return []; throw e; }
200
+ // A torn write is not silently ignored: recover the pending transaction before editing history.
201
+ if (text && !text.endsWith("\n")) throw new Error("truncated promotion journal");
202
+ return text.trim() ? text.trimEnd().split("\n").map((line) => {
203
+ return validateJournalRecord(JSON.parse(line));
204
+ }) : [];
205
+ }
206
+
207
+ function validateJournalRecord(r) {
208
+ if (!["promote", "rollback"].includes(r?.action) || typeof r.id !== "string" || !r.id || !Number.isFinite(Date.parse(r.at)) ||
209
+ (r.from !== null && !targetPattern.test(r.from)) || !targetPattern.test(r.to)) throw new Error("invalid promotion journal entry");
210
+ return r;
211
+ }
212
+
213
+ function appendJournal(store, record) {
214
+ validateJournalRecord(record);
215
+ const records = readJournal(store);
216
+ if (records.some((r) => r.id === record.id)) return;
217
+ const fd = fs.openSync(path.join(store, "journal.jsonl"), "a", 0o600);
218
+ try { fs.writeFileSync(fd, JSON.stringify(record) + "\n"); fs.fsyncSync(fd); }
219
+ finally { fs.closeSync(fd); }
220
+ }
221
+
222
+ /** Repair an interruption between pointer swaps and journal append. Never guess after corruption. */
223
+ export function recoverTransaction(store) {
224
+ const file = path.join(store, "pending.json");
225
+ if (!fs.existsSync(file)) { readJournal(store); return; }
226
+ const tx = validateJournalRecord(json(file));
227
+ validateTarget(store, tx.to);
228
+ if (tx.from !== null) validateTarget(store, tx.from);
229
+ if (tx.previousBefore !== null) validateTarget(store, tx.previousBefore);
230
+ const current = pointer(store, "current");
231
+ if (current === tx.to) appendJournal(store, tx);
232
+ else if (current === tx.from) {
233
+ if (tx.previousBefore !== null) swapPointer(store, "previous", tx.previousBefore);
234
+ else fs.rmSync(path.join(store, "previous"), { force: true });
235
+ } else throw new Error("pending promotion disagrees with current; manual recovery required");
236
+ fs.rmSync(file);
237
+ }
238
+
239
+ /** Caller holds the store lock. Each symlink replacement is atomic; current is the commit point. */
240
+ export function promote(store, target, action = "promote", beforeCurrent = () => {}) {
241
+ recoverTransaction(store);
242
+ validateTarget(store, target);
243
+ const from = pointer(store, "current"), previousBefore = pointer(store, "previous");
244
+ if (from === target) return null;
245
+ const tx = { id: crypto.randomUUID(), action, at: new Date().toISOString(), from, to: target, previousBefore };
246
+ atomicJson(path.join(store, "pending.json"), tx);
247
+ // Bootstrap has no old binary: previous is absent until the second successful promotion.
248
+ if (from !== null) swapPointer(store, "previous", from);
249
+ beforeCurrent();
250
+ swapPointer(store, "current", target);
251
+ appendJournal(store, tx);
252
+ fs.rmSync(path.join(store, "pending.json"));
253
+ return tx;
254
+ }
255
+
256
+ export function rollback(store) {
257
+ recoverTransaction(store);
258
+ const target = pointer(store, "previous");
259
+ if (!target) throw new Error("no previous qualified pin to roll back to");
260
+ const history = readJournal(store);
261
+ const last = history.at(-1);
262
+ if (!last || last.to !== pointer(store, "current") || last.from !== target) throw new Error("previous does not match the recorded promotion journal");
263
+ return promote(store, target, "rollback");
264
+ }
265
+
266
+ /** Complete tree staged on the store filesystem, never rewritten after publication. */
267
+ export function publishTree(store, vendor, manifest) {
268
+ validateManifest(manifest);
269
+ if (manifest.verdictSchema !== CURRENT_VERDICT_SCHEMA) throw new Error("new pin publication requires the current verdict schema");
270
+ return publishSealed(store, `versions/${manifest.version}-${manifest.binarySha256.slice(0, 12)}`, vendor, manifest, readManifest);
271
+ }
272
+
273
+ /**
274
+ * A release's shipped pin, as relay downloaded and verified it here (codex-shipped-pin.mjs
275
+ * installShippedPin is the only caller). Its tree goes under shipped/, never versions/, so it can
276
+ * never be taken for a local qualification, nor a local qualification of the same binary for it.
277
+ */
278
+ export function publishShippedTree(store, vendor, manifest) {
279
+ validateShippedTreeManifest(manifest);
280
+ return publishSealed(store, `shipped/${manifest.version}-${manifest.binarySha256.slice(0, 12)}`, vendor, manifest, readShippedTree);
281
+ }
282
+
283
+ function publishSealed(store, target, vendor, manifest, read) {
284
+ const dest = path.join(store, target);
285
+ if (fs.existsSync(dest)) {
286
+ validateTarget(store, target);
287
+ if (read(dest).binarySha256 !== manifest.binarySha256) throw new Error("pin digest prefix collision");
288
+ return target;
289
+ }
290
+ const staging = fs.mkdtempSync(path.join(store, "staging", "publish-"));
291
+ try {
292
+ for (const name of fs.readdirSync(vendor)) fs.cpSync(path.join(vendor, name), path.join(staging, name), { recursive: true, force: false, errorOnExist: true });
293
+ atomicJson(path.join(staging, "manifest.json"), manifest);
294
+ read(staging);
295
+ const seal = (dir, top = false) => {
296
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
297
+ const file = path.join(dir, entry.name);
298
+ if (entry.isSymbolicLink()) throw new Error("vendor symlinks are not allowed");
299
+ if (entry.isDirectory()) seal(file);
300
+ else if (entry.isFile()) fs.chmodSync(file, fs.statSync(file).mode & 0o111 ? 0o555 : 0o444);
301
+ else throw new Error("special vendor file is not allowed");
302
+ }
303
+ // macOS requires write permission on a directory moved between parents (its '..' changes).
304
+ // Seal the root immediately after the rename, before any current/previous pointer exists.
305
+ if (!top) fs.chmodSync(dir, 0o555);
306
+ };
307
+ seal(staging, true);
308
+ fs.renameSync(staging, dest);
309
+ fs.chmodSync(dest, 0o555);
310
+ } catch (e) {
311
+ // Preserve a failed, possibly sealed staging tree for diagnosis.
312
+ throw new Error(`publishing ${staging}: ${e.message}`, { cause: e });
313
+ }
314
+ return target;
315
+ }
316
+
317
+ /** Empty/recent locks are busy until staleMs. Never take a lock held by a living PID. */
318
+ export function acquireLock(store, { pid = process.pid, alive = pidAlive, staleMs = 30_000, now = Date.now() } = {}) {
319
+ const file = path.join(store, "lock");
320
+ const ownerFile = path.join(file, "owner.json");
321
+ const owner = { pid, token: crypto.randomUUID(), createdAt: now };
322
+ for (let attempt = 0; attempt < 3; attempt++) {
323
+ try {
324
+ fs.mkdirSync(file, { mode: 0o700 });
325
+ atomicJson(ownerFile, owner);
326
+ return () => {
327
+ if (json(ownerFile).token === owner.token) fs.rmSync(file, { recursive: true });
328
+ };
329
+ } catch (e) {
330
+ if (e.code !== "EEXIST") throw e;
331
+ let stat;
332
+ try { stat = fs.statSync(file); } catch (statError) { if (statError.code === "ENOENT") continue; throw statError; }
333
+ let old;
334
+ try { old = json(ownerFile); } catch { /* a writer may still be publishing its owner */ }
335
+ if (old && Number.isInteger(old.pid) && old.pid > 0 && alive(old.pid)) return null;
336
+ if (now - stat.mtimeMs < staleMs) return null;
337
+ // Keep the nonempty tombstone: two stale-lock reclaimers cannot rename a new owner's lock
338
+ // over the same nonempty directory. This closes the stat/unlink ABA race across processes.
339
+ try {
340
+ const next = fs.statSync(file);
341
+ if (stat.ino !== next.ino || stat.mtimeMs !== next.mtimeMs) continue;
342
+ fs.writeFileSync(path.join(file, "stale"), "reclaimed\n", { flag: "a", mode: 0o600 });
343
+ const tombstone = path.join(store, "staging", `stale-lock-${stat.dev}-${stat.ino}`);
344
+ fs.renameSync(file, tombstone);
345
+ } catch (renameError) { if (!["EEXIST", "ENOTEMPTY", "ENOENT"].includes(renameError.code)) throw renameError; }
346
+ }
347
+ }
348
+ return null; // Another updater won recovery; leave it to finish.
349
+ }
350
+
351
+ function pidAlive(pid) {
352
+ try { process.kill(pid, 0); return true; } catch (e) { if (e.code === "EPERM") return true; if (e.code === "ESRCH") return false; throw e; }
353
+ }