@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,353 @@
1
+ import "./helpers.ts";
2
+ import assert from "node:assert/strict";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import net from "node:net";
6
+ import { EventEmitter } from "node:events";
7
+ import path from "node:path";
8
+ import { test } from "node:test";
9
+ import { nativeCodexNeverNetworkEntry, nativeCodexShellRoute, neverAdapterProblem } from "../dist/backends/never-admission.js";
10
+ import { launchTurn } from "../dist/backends/run.js";
11
+ import { codexPermissions } from "../dist/backends/codex.js";
12
+ import { configProblem } from "../dist/backends/codex-app.js";
13
+ import { NETWORK_MODE_TEXT } from "../dist/backends/codex-network.js";
14
+ import { applyClaudeNeverPolicy } from "../dist/backends/claude.js";
15
+ import { neverEndpointProblem, neverProfileInputs, resolveNeverPolicy } from "../dist/core/never-policy.js";
16
+ import { neverSeatbeltRules } from "../dist/confine/seatbelt-never.js";
17
+ import { STAGE2_FLAG_ENV } from "../dist/core/stage2-switch.js";
18
+ import { localModeRetired, rawNetworkGrantProblem } from "../dist/core/raw-network.js";
19
+ import { withDefaults } from "../dist/core/config.js";
20
+ import { targetDef } from "../dist/targets/index.js";
21
+ import { turnPolicy } from "../dist/confine/turn.js";
22
+ import { seatbeltProfile } from "../dist/confine/seatbelt.js";
23
+ import { openProxy } from "../dist/confine/proxy.js";
24
+ import { closeDbForTests, createRun, insertNode, insertTurn } from "../dist/core/db.js";
25
+ import { requestApproval } from "../dist/core/approvals.js";
26
+ import { admitWork } from "../dist/core/caller.js";
27
+ import { checkpointNever } from "../dist/core/never-checkpoint.js";
28
+ import type { TurnSpec } from "../dist/backends/types.js";
29
+
30
+ test("WP4: stage 2 keeps known credential/settings bypass refusals and admits native Codex", () => {
31
+ const policy = resolveNeverPolicy({ builtins: false });
32
+ const spec = (id: "codex" | "claude" | "copilot" | "grok" | "gemini", extra = {}) => ({ target: targetDef(id), config: withDefaults({ targets: { codex: { stage2: true } } }), access: "write", neverPolicy: policy, ...extra }) as TurnSpec;
33
+ // Test native admission too: escalation:false keeps network-off turns on native Codex.
34
+ assert.equal(neverAdapterProblem(spec("codex")), null);
35
+ for (const codex_backend of ["app-server", "exec"] as const) for (const grant of [undefined, { network: true }]) {
36
+ assert.equal(neverAdapterProblem(spec("codex", { config: withDefaults({ targets: { codex: { stage2: true } }, escalation: false, codex_backend }), grant })), null);
37
+ }
38
+ assert.match(NETWORK_MODE_TEXT.strict, /trustd.*bypass/);
39
+ assert.equal(neverAdapterProblem(spec("codex", { grant: { network: true, raw_network: true } })), null);
40
+ // Exec's raw-network rejection remains at the grant gate, rather than refusing all exec jobs.
41
+ assert.match(rawNetworkGrantProblem({ network: true, raw_network: true }, "write", "codex", withDefaults({ targets: { codex: { stage2: true } }, codex_backend: "exec" }))!, /needs codex_backend "app-server"/);
42
+ assert.match(neverAdapterProblem(spec("copilot"))!, /KEYCHAIN\/TRUST.*qualified/);
43
+ assert.match(neverAdapterProblem(spec("grok"))!, /token-store\/TRUST.*qualified/);
44
+ assert.equal(neverAdapterProblem(spec("gemini")), null);
45
+ assert.equal(neverAdapterProblem(spec("claude")), null);
46
+ for (const config of [{ allow_dangerous: true }, { child_hooks: true }, { child_settings: "inherit" }, { child_mcp: "inherit" }]) assert.match(neverAdapterProblem(spec("claude", { config: withDefaults({ ...config, targets: { codex: { stage2: true } } } as any) }))!, /never:.*bypass/);
47
+ const hostPolicy = resolveNeverPolicy({ builtins: false, never: { hosts: ["decoy.example"] } });
48
+ assert.match(neverAdapterProblem(spec("gemini", { neverPolicy: hostPolicy, grant: { network: true } }))!, /never.hosts disables raw network/);
49
+ assert.equal(neverAdapterProblem(spec("gemini", { neverPolicy: hostPolicy })), null);
50
+ });
51
+
52
+ test("WP4: switch off admits released ACP/Codex harness variants, refuses Claude's floor-bypassing ones; environment switch restores refusals", () => {
53
+ const saved = process.env[STAGE2_FLAG_ENV];
54
+ try {
55
+ delete process.env[STAGE2_FLAG_ENV];
56
+ const policy = resolveNeverPolicy({ builtins: false, never: { hosts: ["decoy.example"] } });
57
+ for (const id of ["codex", "copilot", "grok", "claude", "gemini"] as const) {
58
+ for (const variant of [{}, { allow_dangerous: true }, { child_hooks: true }, { child_settings: "inherit" }, { child_mcp: "inherit" }, { codex_backend: "exec" }]) for (const grant of [undefined, { network: true }]) {
59
+ const spec = { target: targetDef(id), config: withDefaults({ ...variant, targets: { codex: { stage2: false } } } as any), access: "write", neverPolicy: policy, grant } as TurnSpec;
60
+ if (id === "codex" && (grant?.network || variant.allow_dangerous)) assert.match(neverAdapterProblem(spec)!, /never user.host:decoy.example.*native Codex/);
61
+ // Claude gets the floor whatever stage 2 says (decided 2026-11-04), and with it the variant gates.
62
+ else if (id === "claude" && ("allow_dangerous" in variant || "child_hooks" in variant || "child_settings" in variant || "child_mcp" in variant)) assert.match(neverAdapterProblem(spec)!, /never:.*bypass/, `claude: ${JSON.stringify(variant)}`);
63
+ else assert.equal(neverAdapterProblem(spec), null, `${id}: ${JSON.stringify(variant)}`);
64
+ }
65
+ }
66
+ const spec = { target: targetDef("copilot"), config: withDefaults({}), access: "write", neverPolicy: policy } as TurnSpec;
67
+ process.env[STAGE2_FLAG_ENV] = "1";
68
+ assert.match(neverAdapterProblem(spec)!, /KEYCHAIN\/TRUST/);
69
+ delete process.env[STAGE2_FLAG_ENV];
70
+ const forbidden = resolveNeverPolicy({ builtins: false, never: { paths: [{ path: "/decoy/private" }] } });
71
+ for (const on of [false, true]) {
72
+ spec.config = withDefaults({ targets: { codex: { stage2: on } } });
73
+ assert.match(neverAdapterProblem({ ...spec, neverPolicy: forbidden, grant: { write_paths: ["/decoy/private"] } })!, /never/);
74
+ assert.match(neverAdapterProblem({ ...spec, neverPolicy: { ...forbidden, authorityPins: [{ path: "/decoy/missing", dev: -1, ino: -1, kind: 0 }] } })!, /identity/);
75
+ }
76
+ } finally {
77
+ if (saved === undefined) delete process.env[STAGE2_FLAG_ENV]; else process.env[STAGE2_FLAG_ENV] = saved;
78
+ }
79
+ });
80
+
81
+ test("WP4: stage 2 refuses native dangerous Codex writes while the switch-off route is unchanged", () => {
82
+ const policy = resolveNeverPolicy({ builtins: false });
83
+ const turn = (stage2: boolean, extra = {}) => ({
84
+ target: targetDef("codex"), access: "write", cwd: "/owned/work", neverPolicy: policy,
85
+ config: withDefaults({ allow_dangerous: true, escalation: false, targets: { codex: { stage2 } } }), ...extra,
86
+ }) as TurnSpec;
87
+ assert.match(neverAdapterProblem(turn(true))!, /allow_dangerous.*without stage-2 confinement/);
88
+ assert.match(neverAdapterProblem(turn(true, { sessionId: "resumed-thread" }))!, /allow_dangerous/);
89
+ assert.equal(neverAdapterProblem(turn(false)), null);
90
+ assert.equal(neverAdapterProblem({ ...turn(true), access: "read" }), null);
91
+ assert.equal(neverAdapterProblem({ ...turn(true), grant: { network: true } }), null, "a selected stage-2 route never falls back to native danger-full-access");
92
+ });
93
+
94
+ test("WP4: native Codex refuses unenforceable network floors before initial and resumed launch with either switch", async () => {
95
+ const saved = process.env[STAGE2_FLAG_ENV];
96
+ delete process.env[STAGE2_FLAG_ENV];
97
+ const policy = resolveNeverPolicy({ builtins: false, never: { hosts: ["forbidden.example"] } });
98
+ let launches = 0;
99
+ const backend = { start: async () => { launches++; return { done: Promise.resolve({ status: "ok" }) } as never; } };
100
+ try {
101
+ for (const stage2 of [false, true]) for (const codex_backend of ["app-server", "exec"] as const) {
102
+ // escalation:false affects only network-off origins; standing grants still select stage 2.
103
+ const config = withDefaults({ allow_untested: true, escalation: false, codex_backend, targets: { codex: { stage2, pinned: false } } });
104
+ for (const sessionId of [undefined, "existing-thread"]) for (const access of ["write", "read"] as const) {
105
+ const spec = { target: targetDef("codex"), config, access, sessionId, neverPolicy: policy } as TurnSpec;
106
+ for (const extra of [{ grant: { network: true } }, { config: { ...config, child_network: true } }]) {
107
+ const turn = { ...spec, ...extra };
108
+ if (stage2) {
109
+ assert.equal(neverAdapterProblem(turn), null, "the stage2 provider enforces the host floor");
110
+ await launchTurn(turn.target, turn, backend);
111
+ continue;
112
+ }
113
+ // codex exec read turns have no shell network even when granted it.
114
+ if (access === "read" && codex_backend === "exec") { assert.equal(neverAdapterProblem(turn), null); continue; }
115
+ const why = neverAdapterProblem(turn)!;
116
+ assert.match(why, /never user.host:forbidden.example: native Codex.*cannot enforce/);
117
+ assert.match(why, /Remove the network grant/);
118
+ assert.equal(why.includes("stage-2 mediated route"), stage2);
119
+ if (turn.config.child_network) assert.match(why, /disable child_network/);
120
+ await assert.rejects(launchTurn(turn.target, turn, backend), { message: why });
121
+ }
122
+ assert.equal(neverAdapterProblem(spec), null, "host rules with shell network off are admitted");
123
+ await launchTurn(spec.target, spec, backend);
124
+ const noUserRules = { ...spec, neverPolicy: resolveNeverPolicy({}), grant: { network: true } };
125
+ assert.equal(neverAdapterProblem(noUserRules), null, "built-ins alone preserve admission");
126
+ await launchTurn(spec.target, noUserRules, backend);
127
+ }
128
+ }
129
+ assert.equal(launches, 48, "native refusals stay off the backend; stage2 routes reach backend qualification");
130
+ // child_network on a selected stage-2 route does not turn on the native proxy.
131
+ assert.equal(neverAdapterProblem({ target: targetDef("codex"), config: withDefaults({ child_network: true, targets: { codex: { stage2: true } } }), access: "write", neverPolicy: policy } as TurnSpec), null);
132
+ } finally {
133
+ if (saved === undefined) delete process.env[STAGE2_FLAG_ENV]; else process.env[STAGE2_FLAG_ENV] = saved;
134
+ }
135
+ });
136
+
137
+ test("WP4: native Codex holds the person's this-machine ports like the built-ins, and refuses them where the route opens this Mac", () => {
138
+ const saved = process.env[STAGE2_FLAG_ENV];
139
+ try {
140
+ delete process.env[STAGE2_FLAG_ENV];
141
+ const builtins = resolveNeverPolicy({});
142
+ for (const transport of ["tcp", "udp", "both"] as const) for (const destinations of ["any", "this-machine"] as const) {
143
+ const entry = `user.port:49225/${transport}/${destinations}`;
144
+ const own = resolveNeverPolicy({ never: { ports: [{ port: 49225, transport, destinations }] } });
145
+ // Strict shell network reaches none of this Mac's addresses and sends no UDP: it holds every
146
+ // this-machine entry and every UDP-only one, and cannot hold an "any" entry covering TCP.
147
+ const strictHolds = destinations === "this-machine" || transport === "udp";
148
+ const base = { target: targetDef("codex"), access: "write", neverPolicy: own } as const;
149
+ const off = withDefaults({ targets: { codex: { stage2: false } } });
150
+ const routes: [string, TurnSpec, "strict" | "local" | "unconfined"][] = [
151
+ ["strict write grant", { ...base, config: off, grant: { network: true } } as TurnSpec, "strict"],
152
+ ["strict read grant", { ...base, access: "read", config: off, grant: { network: true } } as TurnSpec, "strict"],
153
+ ["strict exec write grant", { ...base, config: withDefaults({ codex_backend: "exec", targets: { codex: { stage2: false } } }), grant: { network: true } } as TurnSpec, "strict"],
154
+ ["child_network", { ...base, config: withDefaults({ child_network: true, targets: { codex: { stage2: false } } }) } as TurnSpec, "strict"],
155
+ ["local_network", { ...base, config: off, grant: { network: true, local_network: true } } as TurnSpec, "local"],
156
+ ["allow_dangerous", { ...base, config: withDefaults({ allow_dangerous: true, targets: { codex: { stage2: false } } }) } as TurnSpec, "unconfined"],
157
+ ];
158
+ for (const [label, spec, route] of routes) {
159
+ assert.equal(nativeCodexShellRoute(spec), route, label);
160
+ const why = neverAdapterProblem(spec);
161
+ if (route === "strict" && strictHolds) assert.equal(why, null, `${label}: ${entry} is held by strict network`);
162
+ else {
163
+ assert.match(why!, new RegExp(`^never ${entry.replaceAll(".", "\\.")}: native Codex with shell network cannot enforce`), `${label}: ${entry}`);
164
+ if (route === "local") assert.match(why!, /under grant\.local_network, which opens this Mac's loopback and local network.*or give it without local_network/);
165
+ if (route === "unconfined") assert.match(why!, /under allow_dangerous.*disable allow_dangerous/);
166
+ assert.equal(why!.includes("Strict shell network enforces it"), route !== "strict" && strictHolds, `${label}: ${entry} names strict as the way out where it holds`);
167
+ }
168
+ // The built-in this-machine ports keep their admission on every route, as before.
169
+ assert.equal(neverAdapterProblem({ ...spec, neverPolicy: builtins }), null, `${label}: built-ins alone`);
170
+ // Without shell network nothing is refused (local and unconfined always have it).
171
+ if (route === "strict") assert.equal(neverAdapterProblem({ ...spec, grant: undefined, config: { ...spec.config, child_network: false } }), null, `${label}: network off`);
172
+ }
173
+ assert.equal(nativeCodexNeverNetworkEntry(own, "strict"), strictHolds ? null : entry);
174
+ assert.equal(nativeCodexNeverNetworkEntry(own, "local"), entry);
175
+ assert.equal(nativeCodexNeverNetworkEntry(own, "unconfined"), entry);
176
+ for (const route of ["strict", "local", "unconfined"] as const) assert.equal(nativeCodexNeverNetworkEntry(builtins, route), null);
177
+ // Stage 2: relay's sandbox and proxy hold every entry, so no route is refused for one; local
178
+ // mode is refused outright, and allow_dangerous outside the stage-2 route.
179
+ const on = withDefaults({ targets: { codex: { stage2: true } } });
180
+ for (const grant of [{ network: true }, { network: true, raw_network: true }]) assert.equal(neverAdapterProblem({ ...base, config: on, grant } as TurnSpec), null, `stage 2 ${JSON.stringify(grant)}: ${entry}`);
181
+ assert.match(localModeRetired(on)!, /not available while relay's stage 2 is switched on/);
182
+ assert.match(neverAdapterProblem({ ...base, config: withDefaults({ allow_dangerous: true, escalation: false, codex_backend: "exec", targets: { codex: { stage2: true } } }) } as TurnSpec)!, /allow_dangerous would run this write turn without stage-2 confinement/);
183
+ }
184
+ } finally {
185
+ if (saved === undefined) delete process.env[STAGE2_FLAG_ENV]; else process.env[STAGE2_FLAG_ENV] = saved;
186
+ }
187
+ });
188
+
189
+ test("WP4: a this-machine port of the person's is enforced exactly as a built-in one by relay's sandbox and proxy (stage 2, ACP, Claude)", () => {
190
+ const user = resolveNeverPolicy({ builtins: false, never: { ports: [{ port: 22, transport: "both", destinations: "this-machine" }] } });
191
+ const builtin = resolveNeverPolicy({ builtins: false });
192
+ const sshd = resolveNeverPolicy({}).ports.find(p => p.id === "service.sshd")!;
193
+ assert.deepEqual({ ...sshd, id: "" }, { ...user.ports[0], id: "" }, "the same rule but for its name");
194
+ // Relay's Seatbelt (stage-2 raw and mediated, Copilot, Gemini and Grok): the same deny rules.
195
+ const rules = (policy: typeof user) => neverSeatbeltRules(policy, (_k, v) => v, "", { worktree: "/owned/work", tmpDir: "/owned/tmp" });
196
+ const userRules = rules(user), noRules = rules(builtin);
197
+ assert.ok(userRules.length > noRules.length);
198
+ assert.deepEqual(rules({ ...builtin, ports: [sshd] } as typeof user), userRules);
199
+ // Relay's proxy (stage-2 mediated, Claude, ACP): every address of this Mac's refused, other hosts' port 22 not.
200
+ const local = os.networkInterfaces();
201
+ const mine = Object.values(local).flatMap(list => list ?? []).find(a => a.family === "IPv4" && !a.internal)?.address;
202
+ for (const host of ["127.0.0.1", "localhost", "0.0.0.0", ...(mine ? [mine] : [])]) {
203
+ for (const transport of ["tcp", "udp"] as const) assert.match(neverEndpointProblem(user, { host, port: 22, transport })!, /never user\.port:22\/both\/this-machine/, host);
204
+ }
205
+ assert.match(neverEndpointProblem(user, { host: "example.com", port: 22, transport: "tcp", operation: "listen" })!, /never user\.port/, "never bound");
206
+ assert.equal(neverEndpointProblem(user, { host: "192.0.2.10", port: 22, transport: "tcp", addresses: ["192.0.2.10"] }), null, "another host's ssh is not this Mac's");
207
+ // Admission: no target refuses it; relay's sandbox or proxy holds it.
208
+ for (const stage2 of [false, true]) for (const id of ["gemini", "claude"] as const) {
209
+ const config = withDefaults({ child_settings: "isolated", child_hooks: false, child_mcp: "relay-only", targets: { codex: { stage2 } } } as any);
210
+ for (const grant of [undefined, { network: true }]) assert.equal(neverAdapterProblem({ target: targetDef(id), config, access: "write", neverPolicy: user, grant } as TurnSpec), null, `${id} stage2 ${stage2}`);
211
+ }
212
+ });
213
+
214
+ test("WP4: resume admission rechecks new and kept network grants against the cumulative host floor", () => {
215
+ const home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "wp4-resume-")));
216
+ const saved = { RELAY_HOME: process.env.RELAY_HOME, RELAY_CONFIG: process.env.RELAY_CONFIG, [STAGE2_FLAG_ENV]: process.env[STAGE2_FLAG_ENV] };
217
+ try {
218
+ delete process.env[STAGE2_FLAG_ENV];
219
+ process.env.RELAY_HOME = path.join(home, "registry"); process.env.RELAY_CONFIG = path.join(home, "config.json");
220
+ for (const stage2 of [false, true]) {
221
+ const cfg = withDefaults({ targets: { codex: { stage2 } }, escalation: false });
222
+ fs.writeFileSync(process.env.RELAY_CONFIG, JSON.stringify(cfg));
223
+ const run = createRun(home, cfg, "unit");
224
+ const caller = { runId: run, node: null } as never;
225
+ assert.deepEqual(admitWork(caller, "codex", { mode: "write", kept: { network: true }, continues: true }, {}), { grant: undefined });
226
+ // A newly observed host deny must screen a grant kept from a previous turn.
227
+ fs.writeFileSync(process.env.RELAY_CONFIG, JSON.stringify({ ...cfg, never: { hosts: ["forbidden.example"] } }));
228
+ for (const extra of [{ grant: { network: true } }, { kept: { network: true } }]) {
229
+ const answer = admitWork(caller, "codex", { mode: "write", continues: true, ...extra }, {}) as { reason: string };
230
+ if (stage2) { assert.equal(answer.reason, undefined); continue; }
231
+ assert.match(answer.reason, /never user.host:forbidden.example.*cannot enforce/);
232
+ assert.match(answer.reason, /grant is kept/);
233
+ }
234
+ fs.writeFileSync(process.env.RELAY_CONFIG, JSON.stringify(cfg));
235
+ const kept = admitWork(caller, "codex", { mode: "write", kept: { network: true }, continues: true }, {}) as { reason: string };
236
+ const launchProblem = neverAdapterProblem({ target: targetDef("codex"), config: cfg, access: "write", sessionId: "existing-thread", grant: { network: true }, neverPolicy: checkpointNever(run, "launch") } as TurnSpec);
237
+ assert.ok(checkpointNever(run, "launch").hosts.some(h => h.host === "forbidden.example"), "removing live config never shrinks the run floor");
238
+ if (stage2) { assert.equal(kept.reason, undefined); assert.equal(launchProblem, null); }
239
+ else { assert.match(kept.reason, /user.host:forbidden.example/); assert.match(launchProblem!, /user.host:forbidden.example/); }
240
+ assert.deepEqual(admitWork(caller, "codex", { mode: "write", continues: true }, {}), { grant: undefined });
241
+ }
242
+ } finally {
243
+ closeDbForTests(); for (const [k,v] of Object.entries(saved)) if (v === undefined) delete process.env[k]; else process.env[k] = v;
244
+ fs.rmSync(home, { recursive: true, force: true });
245
+ }
246
+ });
247
+
248
+ test("WP4: native Codex profiles carry built-in and user never paths and readback rejects missing denies", () => {
249
+ const home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "wp4-codex-")));
250
+ try {
251
+ const policy = resolveNeverPolicy({ home, never: { paths: [{ path: path.join(home, "private") }, { path: path.join(home, "install"), access: "write" }] } });
252
+ const floor = neverProfileInputs(policy);
253
+ for (const access of ["read", "write"] as const) for (const codex_backend of ["app-server", "exec"] as const) {
254
+ const permissions = codexPermissions({ access, config: withDefaults({ codex_backend }), neverPolicy: policy }, { dangerous: false, network: false, roots: [home] });
255
+ const filesystem = permissions.profile!.filesystem;
256
+ const baseline = codexPermissions({ access, config: withDefaults({ codex_backend }) }, { dangerous: false, network: false, roots: [home] }).profile!.filesystem;
257
+ for (const p of floor.denyAll) assert.equal(filesystem[p], "deny", p);
258
+ for (const p of floor.denyWrite) assert.equal(filesystem[p], floor.denyAll.includes(p) || baseline[p] === "deny" ? "deny" : "read", p);
259
+ assert.equal(filesystem[path.join(home, ".claude/.credentials.json")], "deny");
260
+ const eff = { approvals_reviewer: "user", default_permissions: permissions.id, permissions: { [permissions.id]: structuredClone(permissions.profile) } };
261
+ const expect = { permissions, relay: null, relayOnly: false, accountLogin: false };
262
+ assert.equal(configProblem(eff, expect), null);
263
+ delete eff.permissions[permissions.id]!.filesystem[path.join(home, "private")];
264
+ assert.match(configProblem(eff, expect)!, /permission profile/);
265
+ }
266
+ } finally { fs.rmSync(home, { recursive: true, force: true }); }
267
+ });
268
+
269
+ test("WP4: Claude compiles final shared all/write floor into shell and file-tool denies and closes unsandboxed retries", () => {
270
+ const policy = resolveNeverPolicy({ builtins: false, never: { paths: [{ path: "/decoy/private" }, { path: "/decoy/install", access: "write" }], hosts: ["decoy.example"] } });
271
+ const sandbox = { filesystem: { denyRead: ["/existing/read"], denyWrite: ["/existing/write"], allowWrite: ["/decoy"] }, allowUnsandboxedCommands: true };
272
+ const deny: string[] = []; applyClaudeNeverPolicy(policy, sandbox, deny);
273
+ assert.deepEqual(sandbox.filesystem.denyRead, ["/existing/read", "/decoy/private"]);
274
+ assert.deepEqual(new Set(sandbox.filesystem.denyWrite), new Set(["/existing/write", "/decoy/private", "/decoy/install"]));
275
+ assert.equal(sandbox.allowUnsandboxedCommands, false);
276
+ for (const rule of ["Read(//decoy/private)", "Edit(//decoy/private/**)", "Edit(//decoy/install)", "WebSearch", "WebFetch"]) assert.ok(deny.includes(rule), rule);
277
+ assert.ok(!deny.includes("Read(//decoy/install)"), "write-only X1 remains readable");
278
+ });
279
+
280
+ test("WP4: ACP outer profiles receive the exact shared floor and final parameterized denies", () => {
281
+ const home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "wp4-profile-")));
282
+ try {
283
+ const tmp = path.join(home, "tmp"), work = path.join(home, "work"); fs.mkdirSync(tmp); fs.mkdirSync(work);
284
+ const policy = resolveNeverPolicy({ builtins: false, never: { paths: [{ path: path.join(home, "secret") }], ports: [{ port: 49225 }] } });
285
+ const outer = turnPolicy({ cwd: work, access: "write", target: targetDef("gemini"), neverPolicy: policy, config: withDefaults({ targets: { codex: { stage2: true } } }) }, { stateDirs: [], keychain: false }, tmp, { mode: "on" }, home, "Gemini");
286
+ assert.equal(outer.neverPolicy, policy);
287
+ const compiled = seatbeltProfile(outer);
288
+ assert.ok(compiled.params.some(([, value]) => value === path.join(home, "secret")));
289
+ assert.ok(compiled.params.some(([, value]) => value === "49225"));
290
+ assert.match(compiled.profile, /deny file-read\* file-read-data file-read-metadata file-test-existence.*NEVER_ALL_0/);
291
+ assert.ok(compiled.profile.lastIndexOf("NEVER_ALL_0") > compiled.profile.lastIndexOf("(allow file-write*"), "floor follows applicable write allows");
292
+ } finally { fs.rmSync(home, { recursive: true, force: true }); }
293
+ });
294
+
295
+ test("WP4: switch off preserves ACP credential/TRUST profile allows without experimental final denies", () => {
296
+ const saved = process.env[STAGE2_FLAG_ENV];
297
+ try {
298
+ delete process.env[STAGE2_FLAG_ENV];
299
+ for (const id of ["copilot", "grok"] as const) {
300
+ const outer = turnPolicy({ cwd: "/decoy/work", access: "read", target: targetDef(id), neverPolicy: resolveNeverPolicy({ builtins: false }), config: withDefaults({}) }, { stateDirs: [], keychain: id === "copilot", certificateTrust: true }, "/decoy/tmp", { mode: "on" }, "/decoy/home", id);
301
+ assert.equal(outer.neverPolicy, undefined);
302
+ assert.equal(outer.certificateTrust, true);
303
+ assert.equal(outer.keychain, id === "copilot");
304
+ }
305
+ } finally { if (saved === undefined) delete process.env[STAGE2_FLAG_ENV]; else process.env[STAGE2_FLAG_ENV] = saved; }
306
+ });
307
+
308
+ const CLAUDE_COMMAND_NOTE = "never: Claude command approvals are unavailable under the never floor, so this request was refused and nobody was asked. " +
309
+ "Continue with the work your sandbox permits, report what you needed (under Open issues, or in your final message), or have the root session or the person arrange the work another supported way.";
310
+
311
+ test("WP4: Claude permission-tool command requests, sandboxed or not, are refused before consent with stage 2 off and on, with one accurate note; a Codex command request keeps its own route", async () => {
312
+ const home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "wp4-approval-")));
313
+ const saved = { RELAY_HOME: process.env.RELAY_HOME, RELAY_CONFIG: process.env.RELAY_CONFIG };
314
+ try {
315
+ process.env.RELAY_HOME = path.join(home, "registry"); process.env.RELAY_CONFIG = path.join(home, "config.json");
316
+ for (const on of [false, true]) {
317
+ const cfg = withDefaults({ targets: { codex: { stage2: on } }, escalation: false }); fs.writeFileSync(process.env.RELAY_CONFIG, JSON.stringify(cfg));
318
+ const run = createRun(home, cfg, "unit");
319
+ // A request asking to leave the sandbox, and one Claude's permission tool marks as staying in
320
+ // it (targets/claude.ts toAsk): both refused, with the same note.
321
+ for (const [name, detail] of [["unsandboxed", undefined], ["sandboxed", { sandboxed: true }]] as const) {
322
+ const id = `j_claude_${on}_${name}`;
323
+ insertNode({ id, run_id: run, kind: "job", target: "claude", mode: "write", depth: 1, status: "running", cwd: home, task: "unit" });
324
+ const turn = insertTurn(id, "initial", "unit", "write", "running");
325
+ const answer = await requestApproval(id, turn, { kind: "command", summary: "node build.js", ...(detail ? { detail } : {}) });
326
+ assert.equal(answer.allow, false, `${name}, stage 2 ${on}`);
327
+ assert.equal(answer.note, CLAUDE_COMMAND_NOTE, `${name}, stage 2 ${on}`);
328
+ // Not true of a sandboxed request, and restart overlays exist only for Codex.
329
+ assert.doesNotMatch(answer.note!, /outside the checked sandbox|restart overlay/, `${name}, stage 2 ${on}`);
330
+ }
331
+ // A Codex command request does not take Claude's note: it reaches the generic route, which
332
+ // answers here (escalation off) as it did before.
333
+ const codex = `j_codex_${on}`;
334
+ insertNode({ id: codex, run_id: run, kind: "job", target: "codex", mode: "write", depth: 1, status: "running", cwd: home, task: "unit" });
335
+ const codexTurn = insertTurn(codex, "initial", "unit", "write", "running");
336
+ const codexAnswer = await requestApproval(codex, codexTurn, { kind: "command", summary: "node build.js", detail: { sandboxed: true } });
337
+ assert.deepEqual(codexAnswer, { allow: false, note: "approval requests are turned off; report what you needed under Open issues" });
338
+ }
339
+ } finally { closeDbForTests(); for (const [k,v] of Object.entries(saved)) if (v === undefined) delete process.env[k]; else process.env[k] = v; fs.rmSync(home, { recursive: true, force: true }); }
340
+ });
341
+
342
+ test("WP4: proxy seam opens with the shared never floor and keeps dual-loopback binding", async t => {
343
+ const bindings = [];
344
+ t.mock.method(net, "createServer", () => Object.assign(new EventEmitter(), {
345
+ listen(options, cb) { bindings.push(options); cb(); },
346
+ address: () => ({ port: 49202 }), close(cb) { cb(); },
347
+ }));
348
+ const proxy = await openProxy({ mode: "public", allow: [], neverPolicy: resolveNeverPolicy({ builtins: false }) });
349
+ try {
350
+ assert.deepEqual(bindings, [{ host: "127.0.0.1", port: 0, ipv6Only: false }, { host: "::1", port: 49202, ipv6Only: true }]);
351
+ assert.equal(proxy.port, 49202);
352
+ } finally { await proxy.close(); }
353
+ });
@@ -0,0 +1,136 @@
1
+ import "./helpers.ts";
2
+ import assert from "node:assert/strict";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { spawn } from "node:child_process";
7
+ import { test } from "node:test";
8
+ import { closeDbForTests, closeTurns, createRun, db, insertNode, insertTurn, updateNode, updateTurn, getRun } from "../dist/core/db.js";
9
+ import { withDefaults } from "../dist/core/config.js";
10
+ import { finishLaunchExecutor, finishLaunchReservation, launchExecutorQuarantine, launchReservationProblem, launchReservationState, overlayInterlock, reapLaunchReservations, reserveLaunch, setOverlayClockForTests } from "../dist/core/restart-overlay.js";
11
+ import { localModeRetired } from "../dist/core/raw-network.js";
12
+ import { forgetExecutor, taintExecutor } from "../dist/core/stage2-executors.js";
13
+
14
+ function fixture() {
15
+ const home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "wp4-")));
16
+ const saved = { RELAY_HOME: process.env.RELAY_HOME, RELAY_CONFIG: process.env.RELAY_CONFIG, RELAY_EXPERIMENTAL_CODEX_STAGE2: process.env.RELAY_EXPERIMENTAL_CODEX_STAGE2 };
17
+ process.env.RELAY_HOME = path.join(home, "registry"); process.env.RELAY_CONFIG = path.join(home, "config.json"); delete process.env.RELAY_EXPERIMENTAL_CODEX_STAGE2;
18
+ const cfg = withDefaults({}); fs.writeFileSync(process.env.RELAY_CONFIG, JSON.stringify(cfg));
19
+ const run = createRun(home, cfg, "wp4");
20
+ setOverlayClockForTests({ wall: Date.now, mono: () => 1000, boot: () => "unit", owner: () => ({ pid: process.pid, start: "unit-start" }) });
21
+ const turn = (id: string, grant: object = { network: true, raw_network: true }) => {
22
+ insertNode({ id, run_id: run, kind: "job", target: "codex", cwd: home, mode: "write", depth: 1, status: "running", task: "unit" });
23
+ const turn = insertTurn(id, "initial", "unit", "write"); updateTurn(turn, { grant_json: JSON.stringify(grant) }); return turn;
24
+ };
25
+ return { home, run, turn, close() { setOverlayClockForTests(null); closeDbForTests(); for (const [k,v] of Object.entries(saved)) if (v === undefined) delete process.env[k]; else process.env[k] = v; fs.rmSync(home, { recursive: true, force: true }); } };
26
+ }
27
+
28
+ for (const mode of ["local", "stage2"] as const) test(`WP4: ${mode} reservation blocks opposite starts through every lifecycle state`, () => {
29
+ const f = fixture(); try {
30
+ const id = f.turn("j_first", { network: true, [mode === "local" ? "local_network" : "raw_network"]: true }), other = mode === "local" ? "stage2" : "local";
31
+ reserveLaunch("j_first", id, mode);
32
+ for (const state of ["starting", "running", "stopping", "tainted"] as const) {
33
+ if (state === "running" || state === "stopping") launchReservationState(f.run, id, state);
34
+ if (state === "tainted") finishLaunchReservation(f.run, id, { clean: false, problem: "detached survivor; sweep uncertain" });
35
+ assert.equal(overlayInterlock(mode), null);
36
+ const why = overlayInterlock(other)!;
37
+ assert.match(why, new RegExp(`reservation ${id} of j_first ${state}`));
38
+ assert.match(why, /reap\/cancel and verify cleanup/);
39
+ const blockedNode = `j_${state}`, blockedTurn = f.turn(blockedNode, { network: true, [other === "local" ? "local_network" : "raw_network"]: true });
40
+ assert.throws(() => reserveLaunch(blockedNode, blockedTurn, other), /launch reservation/);
41
+ }
42
+ assert.match(launchReservationProblem(f.run)!, /tainted/);
43
+ finishLaunchReservation(f.run, id, { clean: true });
44
+ assert.equal(overlayInterlock(other), null);
45
+ assert.equal(launchReservationProblem(f.run), null);
46
+ assert.equal((db().prepare("PRAGMA user_version").get() as any).user_version, 4);
47
+ } finally { f.close(); }
48
+ });
49
+
50
+ test("WP4: malformed captured grants fail both directions closed, regardless of flags/node grants", () => {
51
+ const f = fixture(); try {
52
+ const id = f.turn("j_bad"); updateTurn(id, { status: "running" });
53
+ for (const bad of ["{bad", "null", "[]", '"local"', '{"local_network":"yes"}']) {
54
+ updateTurn(id, { grant_json: bad });
55
+ for (const mode of ["local", "stage2"] as const) assert.match(overlayInterlock(mode)!, /j_bad.*state running.*reap\/cancel/);
56
+ }
57
+ updateTurn(id, { grant_json: '{"network":true,"raw_network":true}' });
58
+ assert.match(localModeRetired(withDefaults({}))!, /j_bad.*raw network/);
59
+ updateTurn(id, { grant_json: '{"network":true,"local_network":true}' });
60
+ assert.match(overlayInterlock("stage2")!, /j_bad.*local network mode/);
61
+ updateTurn(id, { status: "done" }); assert.equal(overlayInterlock("stage2"), null);
62
+ updateNode("j_bad", { agent_pgid: 2147483000 });
63
+ assert.match(overlayInterlock("stage2")!, /j_bad.*tainted; terminal turn retains agent group/);
64
+ } finally { f.close(); }
65
+ });
66
+
67
+ test("WP4: malformed reservations retain quarantine; dead executor records block until teardown, including flag-off leftovers", () => {
68
+ const f = fixture(); try {
69
+ db().prepare("UPDATE runs SET config_json=json_set(config_json,'$.params_json.launch_reservations',json(?)) WHERE id=?").run('{"bad":{}}', f.run);
70
+ for (const mode of ["local", "stage2"] as const) assert.match(overlayInterlock(mode)!, /malformed launch reservation bad.*reap\/cancel/);
71
+ db().prepare("UPDATE runs SET config_json=json_remove(config_json,'$.params_json.launch_reservations') WHERE id=?").run(f.run);
72
+ const dir = path.join(process.env.RELAY_HOME!, "executors"); fs.mkdirSync(dir, { recursive: true });
73
+ const file = path.join(dir, "ex-2147483000-abcdef12.json");
74
+ fs.writeFileSync(file, JSON.stringify({ v: 1, pid: 2147483000, pgid: 2147483000, start: "dead", owner: { pid: 2147483000, start: "dead" }, runId: f.run, nodeId: "j_survivor", turnId: null, ports: { exec: 61001, block: [61002] }, tmpDir: f.home, descendants: [], createdAt: 1 }));
75
+ try {
76
+ assert.match(overlayInterlock("local")!, /executor .*j_survivor.*awaiting verified teardown.*reap\/cancel/);
77
+ taintExecutor(file, "sweep uncertain", []);
78
+ assert.match(localModeRetired(withDefaults({}))!, /j_survivor.*tainted.*reap\/cancel/);
79
+ } finally { forgetExecutor(file); }
80
+ // Corrupt records are never an empty executor set.
81
+ fs.writeFileSync(path.join(dir, "ex-999-abcdef12.json"), "{bad");
82
+ assert.match(overlayInterlock("local")!, /unreadable.*record|record.*unreadable/);
83
+ } finally { f.close(); }
84
+ });
85
+
86
+ test("WP4: recovery cannot release an uncertain launch; a proven pre-launch stop or teardown releases it", () => {
87
+ const f = fixture(); try {
88
+ const id = f.turn("j_reap", { network: true, local_network: true }); reserveLaunch("j_reap", id, "local");
89
+ const orphan = () => {
90
+ const config = JSON.parse(getRun(f.run)!.config_json); config.params_json.launch_reservations[String(id)].owner = { pid: 2147483000, start: "dead" };
91
+ db().prepare("UPDATE runs SET config_json=? WHERE id=?").run(JSON.stringify(config), f.run);
92
+ };
93
+ launchReservationState(f.run, id, "running"); orphan();
94
+ reapLaunchReservations(f.run, () => ({ clean: false, problem: "native detached sweep unproven" }));
95
+ assert.match(overlayInterlock("stage2")!, /tainted/);
96
+ reapLaunchReservations(f.run, () => ({ clean: true })); assert.equal(overlayInterlock("stage2"), null);
97
+ reserveLaunch("j_reap", id, "local"); orphan();
98
+ reapLaunchReservations(f.run, () => { throw new Error("no backend was entered"); });
99
+ assert.equal(overlayInterlock("stage2"), null);
100
+ } finally { f.close(); }
101
+ });
102
+
103
+ test("WP4: two processes racing opposite starts cannot both reserve", async () => {
104
+ const f = fixture(); const children: ReturnType<typeof spawn>[] = [];
105
+ try {
106
+ const a = f.turn("j_local", { network: true, local_network: true }), b = f.turn("j_stage2");
107
+ const module = new URL("../dist/core/restart-overlay.js", import.meta.url).href;
108
+ const child = (node: string, turn: number, mode: string) => {
109
+ const code = `import {reserveLaunch,setOverlayClockForTests} from ${JSON.stringify(module)}; setOverlayClockForTests({wall:Date.now,mono:()=>1000,boot:()=>"unit",owner:()=>({pid:process.pid,start:"unit-start"})}); process.stdout.write("ready\\n"); process.stdin.once("data",()=>{try {reserveLaunch(${JSON.stringify(node)},${turn},${JSON.stringify(mode)});process.stdout.write("reserved\\n")}catch(e){process.stdout.write("blocked: "+e.message+"\\n")}process.stdin.pause()});`;
110
+ const p = spawn(process.execPath, ["--input-type=module", "-e", code], { env: process.env, stdio: ["pipe", "pipe", "pipe"] }); children.push(p);
111
+ let output = "", errors = ""; p.stdout!.on("data", x => output += x); p.stderr!.on("data", x => errors += x);
112
+ const ready = new Promise<void>((resolve, reject) => { p.stdout!.on("data", () => { if (output.includes("ready\n")) resolve(); }); p.once("error", reject); p.once("exit", c => { if (!output.includes("ready\n")) reject(new Error(errors || `child exited ${c}`)); }); });
113
+ const done = new Promise<string>((resolve, reject) => { p.once("error", reject); p.once("exit", c => c === 0 ? resolve(output) : reject(new Error(errors))); });
114
+ return { p, ready, done };
115
+ };
116
+ const one = child("j_local", a, "local"), two = child("j_stage2", b, "stage2");
117
+ await Promise.all([one.ready, two.ready]); one.p.stdin!.end("go"); two.p.stdin!.end("go");
118
+ const outputs = await Promise.all([one.done, two.done]);
119
+ assert.equal(outputs.filter(x => x.includes("reserved\n")).length, 1, outputs.join("\n"));
120
+ assert.equal(outputs.filter(x => x.includes("blocked: launch reservation")).length, 1, outputs.join("\n"));
121
+ } finally { for (const p of children) if (p.exitCode === null) p.kill("SIGKILL"); f.close(); }
122
+ });
123
+
124
+ test("WP4: cancel persists stopping; executor sweeps cannot release a lease without verified app-server cleanup", () => {
125
+ const f = fixture(); try {
126
+ const id = f.turn("j_cancel"); reserveLaunch("j_cancel", id, "stage2"); launchReservationState(f.run, id, "running");
127
+ closeTurns("j_cancel", "cancelled", "unit cancellation");
128
+ assert.match(overlayInterlock("local")!, /j_cancel stopping/);
129
+ assert.throws(() => launchReservationState(f.run, id, "running"), /stopping/);
130
+ assert.match(launchExecutorQuarantine(f.run, id)!, /untraceable app-server cleanup.*quarantine retained/);
131
+ finishLaunchExecutor(f.run, id); assert.match(overlayInterlock("local")!, /stopping/);
132
+ finishLaunchReservation(f.run, id, { clean: false, appClean: true, problem: "executor sweep uncertain" });
133
+ assert.equal(launchExecutorQuarantine(f.run, id), undefined);
134
+ finishLaunchExecutor(f.run, id); assert.equal(overlayInterlock("local"), null);
135
+ } finally { f.close(); }
136
+ });