@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,207 @@
1
+ // Waking a poll early. Relay's processes share nothing but the registry, so a call that waits on
2
+ // another process's work polls it, and between looks it naps. A nap ends early once another
3
+ // process has committed to the registry since the poll last looked: SQLite appends every commit
4
+ // to the write-ahead log, a file watch on the log (kqueue) reports the write at once, and
5
+ // PRAGMA data_version, which changes only when another connection has committed, confirms it.
6
+ // The wake is only a hint to look now. What the poll waits for is still read from the registry,
7
+ // and the poll's own interval still bounds every nap: a commit of this process's own, state kept
8
+ // outside the registry (a process that died, a signal), or a watch that could not be set up are
9
+ // seen no later than before.
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { relayHome } from "./config.js";
13
+ import { db, now } from "./db.js";
14
+ /**
15
+ * Early wakes a poll may take in a burst, and how fast it earns them back: a registry that other
16
+ * processes write to without pause (an agent streaming activity) wakes each poll at most once per
17
+ * WAKE_GAP_MS, so a poll's own look never runs more often than that for long.
18
+ */
19
+ const WAKE_BURST = 3;
20
+ const WAKE_GAP_MS = 10;
21
+ /** A watch event can arrive a moment before the commit that caused it is visible: one more look after this long. */
22
+ const RELOOK_MS = 1;
23
+ /**
24
+ * The watch is kept this long after the last nap has ended, so that a poll does not set it up again
25
+ * on every look; and a log that could not be watched is tried again no sooner, since a watch that
26
+ * fails costs more than the naps it would shorten.
27
+ */
28
+ const LINGER_MS = 1000;
29
+ const versions = new WeakMap();
30
+ /** Changes whenever another connection has committed to the registry since this one last asked; never for this connection's own commits. */
31
+ function dataVersion() {
32
+ const d = db();
33
+ let s = versions.get(d);
34
+ if (!s)
35
+ versions.set(d, (s = d.prepare("PRAGMA data_version")));
36
+ return s.get().data_version;
37
+ }
38
+ const nappers = new Set();
39
+ let watched = null;
40
+ let relook = null;
41
+ let linger = null;
42
+ let lastNapEnd = 0;
43
+ let watchFailed = null;
44
+ /** On a write to the log: wakes every nap whose poll has not seen the registry as it is now. */
45
+ function look(again) {
46
+ if (!nappers.size)
47
+ return;
48
+ let v;
49
+ try {
50
+ v = dataVersion();
51
+ }
52
+ catch {
53
+ // Unreadable now: each poll looks when its nap ends.
54
+ return;
55
+ }
56
+ let missed = false;
57
+ for (const n of [...nappers]) {
58
+ if (v !== n.since)
59
+ n.wake();
60
+ else
61
+ missed = true;
62
+ }
63
+ if (missed && again && !relook) {
64
+ relook = setTimeout(() => {
65
+ relook = null;
66
+ look(false);
67
+ }, RELOOK_MS);
68
+ relook.unref();
69
+ }
70
+ }
71
+ function watch() {
72
+ const file = path.join(relayHome(), "relay.db-wal");
73
+ if (watched?.file === file || (watchFailed?.file === file && now() - watchFailed.at < LINGER_MS))
74
+ return;
75
+ unwatch();
76
+ let watcher;
77
+ try {
78
+ // Not persistent: a nap's own timer is what keeps a process waiting, never the watch.
79
+ watcher = fs.watch(file, { persistent: false }, (event) => {
80
+ // On macOS a write that does not extend the file is reported as a rename too, and so is
81
+ // every commit once the log has started over after a checkpoint. Only a log that is gone or
82
+ // replaced ends this watch, which would see no more writes; the next nap sets up another.
83
+ const w = watched;
84
+ if (event === "rename" && w && w.watcher === watcher) {
85
+ const st = fs.statSync(file, { throwIfNoEntry: false });
86
+ if (!st || st.dev !== w.dev || st.ino !== w.ino)
87
+ unwatch();
88
+ }
89
+ look(true);
90
+ });
91
+ const own = watcher;
92
+ own.on("error", () => {
93
+ if (watched?.watcher === own)
94
+ unwatch();
95
+ });
96
+ const st = fs.statSync(file);
97
+ watched = { file, watcher: own, dev: st.dev, ino: st.ino };
98
+ }
99
+ catch {
100
+ // No log to watch (yet): naps run their full length, as polls always did.
101
+ if (watcher && watched?.watcher !== watcher)
102
+ watcher.close();
103
+ watchFailed = { file, at: now() };
104
+ }
105
+ }
106
+ /** The last nap has ended: the watch goes once no nap has been on for LINGER_MS. One timer a second at most, however often a poll looks. */
107
+ function released() {
108
+ lastNapEnd = now();
109
+ if (!linger && watched) {
110
+ linger = setTimeout(lingered, LINGER_MS);
111
+ linger.unref();
112
+ }
113
+ }
114
+ function lingered() {
115
+ linger = null;
116
+ // A nap is on: its end arms this again.
117
+ if (nappers.size)
118
+ return;
119
+ const quiet = now() - lastNapEnd;
120
+ if (quiet >= LINGER_MS)
121
+ return unwatch();
122
+ linger = setTimeout(lingered, LINGER_MS - quiet);
123
+ linger.unref();
124
+ }
125
+ function unwatch() {
126
+ if (linger) {
127
+ clearTimeout(linger);
128
+ linger = null;
129
+ }
130
+ const w = watched;
131
+ watched = null;
132
+ try {
133
+ w?.watcher.close();
134
+ }
135
+ catch {
136
+ // Already closed.
137
+ }
138
+ }
139
+ /**
140
+ * A poll on the registry. Look first, then nap(ms) until the next look: the nap ends after ms, or
141
+ * sooner once another process has committed to the registry since the previous nap ended (or since
142
+ * the poll was made, before the first), or when the signal aborts. Resolves true when a commit
143
+ * ended it early.
144
+ */
145
+ export function registryPoll() {
146
+ const version = () => {
147
+ try {
148
+ return dataVersion();
149
+ }
150
+ catch {
151
+ return NaN;
152
+ }
153
+ };
154
+ let since = version();
155
+ let credit = WAKE_BURST;
156
+ let creditAt = now();
157
+ /** How long this early wake waits for the poll's allowance. */
158
+ const spend = () => {
159
+ const t = now();
160
+ credit = Math.min(WAKE_BURST, credit + (t - creditAt) / WAKE_GAP_MS) - 1;
161
+ creditAt = t;
162
+ return credit >= 0 ? 0 : -credit * WAKE_GAP_MS;
163
+ };
164
+ const nap = (ms, signal) => new Promise((resolve) => {
165
+ let over = false;
166
+ let timer;
167
+ let held;
168
+ const end = (early) => {
169
+ if (over)
170
+ return;
171
+ over = true;
172
+ clearTimeout(timer);
173
+ clearTimeout(held);
174
+ signal?.removeEventListener("abort", onAbort);
175
+ nappers.delete(napper);
176
+ if (!nappers.size)
177
+ released();
178
+ // The next nap wakes for commits after this moment; the caller looks at the registry next.
179
+ since = version();
180
+ resolve(early);
181
+ };
182
+ const onAbort = () => end(false);
183
+ const napper = {
184
+ since,
185
+ wake: () => {
186
+ if (over || held)
187
+ return;
188
+ const wait = spend();
189
+ if (wait > 0)
190
+ held = setTimeout(() => end(true), wait);
191
+ else
192
+ end(true);
193
+ },
194
+ };
195
+ if (ms <= 0 || signal?.aborted)
196
+ return end(false);
197
+ timer = setTimeout(() => end(false), ms);
198
+ signal?.addEventListener("abort", onAbort, { once: true });
199
+ nappers.add(napper);
200
+ watch();
201
+ // A commit between the last look and this nap's watch.
202
+ const v = version();
203
+ if (!Number.isNaN(v) && v !== since)
204
+ napper.wake();
205
+ });
206
+ return { nap };
207
+ }
@@ -0,0 +1,247 @@
1
+ // The root server's regular look at its runs, while it lives: approval requests are put to the
2
+ // user where the host can ask, events are recorded, and each event that no call of the session is
3
+ // waiting on gets a notice where the host takes notices. A tool result carries the events the
4
+ // session has not been given (pendingEvents).
5
+ import { claimElicitation, decide, elicitationState, endElicitation, getRequest, logElicitation, ownedPending } from "./approvals.js";
6
+ import { ownsRun } from "./caller.js";
7
+ import { db, getNode, now, reap, registryMark, sameMark } from "./db.js";
8
+ import { REPORTED_COMPLETION } from "./reported.js";
9
+ import { claimNotice, noticeText, recordEvents, recordLateAnswer, unseenEvents } from "./events.js";
10
+ import { signedNotice } from "./notices.js";
11
+ import { escalationDecisionAuthentication } from "./escalation-authority.js";
12
+ import { refreshEscalationPersonPath } from "./escalation-contract.js";
13
+ // Asking the user
14
+ /**
15
+ * Puts every pending approval request in this root session's runs to the user through the host,
16
+ * as soon as it is filed, and withdraws questions decided elsewhere meanwhile. Called by the root
17
+ * server on a timer while it lives, and by every wait. Each request is asked once: a question the
18
+ * user closed is not asked again, by this server or by one started after it.
19
+ */
20
+ export function watchRequests(inst, o = {}) {
21
+ if (inst.singletonViolation)
22
+ return;
23
+ // Every run this session owns, its default or one taken over, is in since.
24
+ if (inst.ctx.kind !== "root" || !inst.since.size)
25
+ return;
26
+ if (o.beat !== false)
27
+ beat(inst);
28
+ for (const [id, ctl] of inst.asking)
29
+ if (getRequest(id)?.status !== "pending")
30
+ ctl.abort();
31
+ for (const r of ownedPending(inst.token)) {
32
+ if (inst.asking.has(r.id))
33
+ continue;
34
+ if (!inst.host.elicit) {
35
+ if (!inst.noted.has(r.id)) {
36
+ inst.noted.add(r.id);
37
+ logElicitation({ request: r.id, action: "not asked", reading: inst.host.noElicit ?? "the host has not finished starting" });
38
+ }
39
+ continue;
40
+ }
41
+ if (!claimElicitation(r.id, inst.token))
42
+ continue;
43
+ const ctl = new AbortController();
44
+ inst.asking.set(r.id, ctl);
45
+ void inst.host.elicit(r, ctl.signal)
46
+ .catch((err) => ({ reading: "error", outcome: String(err?.message ?? err).slice(0, 120) }))
47
+ .then((a) => {
48
+ inst.asking.delete(r.id);
49
+ if (inst.singletonViolation || !ownsRun(inst, r.run_id))
50
+ return endElicitation(r.id, inst.token, `late after ownership changed: ${a.outcome}`, "withdrawn");
51
+ if (a.reading !== "decided")
52
+ return endElicitation(r.id, inst.token, a.outcome, a.reading);
53
+ if (!("error" in decide(r.id, a.allow, "user", a.note, a.forJob ? "job" : "once", escalationDecisionAuthentication(r, "person-dialog", inst))))
54
+ return endElicitation(r.id, inst.token, a.outcome, a.reading);
55
+ // Decided elsewhere (or closed) in the moment before relay would have withdrawn the
56
+ // question: the answer came too late to decide anything, and is reported as such.
57
+ const said = a.outcome === "decline" ? "decline" : !a.allow ? "deny" : a.forJob ? "allow for the rest of this job" : "allow";
58
+ endElicitation(r.id, inst.token, `late: ${said}`, "withdrawn");
59
+ logElicitation({ request: r.id, action: "late", reading: `${said} crossed a decision made elsewhere: changed nothing` });
60
+ lateAnswer(r.id, said, "user");
61
+ })
62
+ .catch(() => {
63
+ // The registry may be gone (a test cleaning up); nothing is waiting on this.
64
+ });
65
+ }
66
+ }
67
+ /**
68
+ * A question was answered after the request was decided elsewhere (a host that keeps a withdrawn
69
+ * form, see HostView.formStays, or an answer crossing a decision made elsewhere): nothing changes,
70
+ * and the root agent is told whose answer it was (see recordLateAnswer).
71
+ */
72
+ export function lateAnswer(requestId, said, by) {
73
+ const r = getRequest(requestId);
74
+ if (r && r.status !== "pending")
75
+ recordLateAnswer(r, said, by);
76
+ }
77
+ // Events
78
+ /** How often a root server's watch looks for jobs whose worker has died. */
79
+ const REAP_EVERY_MS = 5000;
80
+ /**
81
+ * How often the watch renews the person route's heartbeat, which lasts 5 s
82
+ * (escalation-person-path.ts): about once a second, whatever the watch's own tick (mcp/server.ts).
83
+ */
84
+ const BEAT_EVERY_MS = 900;
85
+ const beaten = new WeakMap();
86
+ const qualified = (inst) => ({ confirm: inst.host.confirmTool === true, dialog: inst.host.personDialog === true && !!inst.host.elicit });
87
+ /** Renews the person route's heartbeat for this root session (escalation-person-path.ts). */
88
+ function beat(inst) {
89
+ const q = qualified(inst);
90
+ beaten.set(inst, { at: now(), ...q });
91
+ refreshEscalationPersonPath(inst.token, q);
92
+ }
93
+ /** Due once a second, and at once when what the host is qualified for has changed (a demotion withdraws the heartbeat). */
94
+ function beatDue(inst) {
95
+ const last = beaten.get(inst), q = qualified(inst);
96
+ return !last || now() - last.at >= BEAT_EVERY_MS || last.confirm !== q.confirm || last.dialog !== q.dialog;
97
+ }
98
+ /**
99
+ * What each root session's last full look went by: the registry's change mark (registryMark: other
100
+ * connections' commits as they stood when the look began, this connection's own changes as they
101
+ * stood when it ended), the host view, and the session's own state that the look reads. While all of
102
+ * them are the same, nothing the look reads has changed, and a look would find nothing to record,
103
+ * ask or post.
104
+ */
105
+ const looked = new WeakMap();
106
+ /** What of a root session's own state (not in the registry) its look reads. handedOff only grows. */
107
+ const sessionState = (inst) => JSON.stringify([[...inst.since], [...inst.asking.keys()], [...inst.waiting].map(([k, w]) => [k, w.runId, [...w.items]]), inst.handedOff.size]);
108
+ /**
109
+ * True while nothing a look at this session's runs reads has changed since its last one. A question
110
+ * still open on a pending request of these runs counts as a change: whether its asker is alive (and
111
+ * so whether it is asked again, or handed to the agent) is not written anywhere when it dies.
112
+ */
113
+ function unchanged(inst) {
114
+ const last = looked.get(inst);
115
+ return Boolean(last && !last.open && last.host === inst.host && sameMark(last.mark, registryMark()) && last.state === sessionState(inst));
116
+ }
117
+ /** Whether a question is open on a pending request of this session's runs (written in the registry, so known for as long as its mark holds). */
118
+ function openQuestion(inst) {
119
+ const runs = [...inst.since.keys()];
120
+ return runs.length > 0 && Boolean(db().prepare(`SELECT 1 FROM elicitations e JOIN requests r ON r.id = e.request_id WHERE e.outcome IS NULL AND r.status = 'pending' AND r.run_id IN (${runs.map(() => "?").join(", ")}) LIMIT 1`).get(...runs));
121
+ }
122
+ /**
123
+ * The root server's regular look at its runs, on a timer while it lives: approval requests are put
124
+ * to the user, events are recorded, and each event no call of this session is waiting on gets a
125
+ * notice, once, where the host takes notices. A tick that finds nothing changed since the last look
126
+ * (unchanged) does only what goes by the clock: the person route's heartbeat (beat) and the reap of
127
+ * jobs whose worker has died; and looks after all if that reap changed anything.
128
+ */
129
+ export function watch(inst) {
130
+ if (inst.singletonViolation)
131
+ return;
132
+ if (unchanged(inst)) {
133
+ if (inst.ctx.kind !== "root" || !inst.since.size)
134
+ return;
135
+ if (beatDue(inst))
136
+ beat(inst);
137
+ reapDue(inst);
138
+ if (unchanged(inst))
139
+ return;
140
+ }
141
+ const begun = registryMark();
142
+ look(inst);
143
+ looked.set(inst, { mark: { ...begun, own: registryMark().own }, host: inst.host, state: sessionState(inst), open: openQuestion(inst) });
144
+ }
145
+ /** Every few seconds, the jobs of the session's runs whose worker has died are marked lost (reap). */
146
+ function reapDue(inst) {
147
+ // A job whose worker died settles (as lost) only when someone looks: look every few seconds, so
148
+ // that it becomes an event whether or not any call asks about it.
149
+ if (now() - (inst.reapedAt ?? 0) >= REAP_EVERY_MS) {
150
+ inst.reapedAt = now();
151
+ for (const runId of inst.since.keys())
152
+ reap(runId);
153
+ }
154
+ }
155
+ function look(inst) {
156
+ for (const id of inst.since.keys())
157
+ if (!ownsRun(inst, id))
158
+ inst.since.delete(id);
159
+ watchRequests(inst, { beat: beatDue(inst) });
160
+ if (inst.ctx.kind !== "root" || !inst.since.size)
161
+ return;
162
+ reapDue(inst);
163
+ recordEvents(inst.since, (id) => inst.asking.has(id) || elicitationState(id) === "asking");
164
+ if (!inst.host.notice)
165
+ return;
166
+ const waits = [...inst.waiting.values()];
167
+ for (const e of unseenEvents([...inst.since.keys()])) {
168
+ // A person's decision is for the agent's next result; the person knows already.
169
+ if (e.noticed_at || e.kind === "decided")
170
+ continue;
171
+ // A call waiting on the item gets the news in its result; one waiting anywhere in the run is
172
+ // handed a new approval request when it returns.
173
+ const covered = waits.some((w) => w.runId === e.run_id && (e.kind === "approval"
174
+ ? !inst.handedOff.has(e.subject) : w.items.has(e.item_id) || w.items.has(e.subject)));
175
+ if (covered)
176
+ continue;
177
+ if (e.kind === "approval" && getRequest(e.subject)?.status !== "pending")
178
+ continue;
179
+ if (claimNotice(e.id))
180
+ inst.host.notice(signedNotice(inst, e), e.id);
181
+ }
182
+ }
183
+ const ID = /^[jtpdrq]_[0-9a-f]{8}$/;
184
+ /** Fields of relay's own results that name the items and requests a result reports on. */
185
+ const ITEM_FIELDS = ["id", "job_id", "thread_id", "discussion_id", "review_id", "reviewer_job", "participant", "request_id"];
186
+ /**
187
+ * The items and requests a result reports on, read only from the fields relay itself fills (ids
188
+ * of the item, its children and the run's items, and requests in needs_approval), never from text
189
+ * that came from an agent (its result, reply or task), which could name any id.
190
+ */
191
+ function reportedIn(result) {
192
+ const out = new Set();
193
+ const take = (v) => {
194
+ if (typeof v === "string" && ID.test(v))
195
+ out.add(v);
196
+ };
197
+ for (const k of ITEM_FIELDS)
198
+ take(result[k]);
199
+ for (const list of ["nodes", "children"]) {
200
+ for (const n of Array.isArray(result[list]) ? result[list] : [])
201
+ take(n?.id);
202
+ }
203
+ for (const r of Array.isArray(result.needs_approval) ? result.needs_approval : [])
204
+ take(r?.request_id);
205
+ for (const id of Array.isArray(result.cancelled) ? result.cancelled : [])
206
+ take(id);
207
+ return out;
208
+ }
209
+ /**
210
+ * The events a root session's tool result is to carry: every event of its runs it has not been
211
+ * given yet, except those about items the result itself reports on, and approval requests no longer
212
+ * pending. `given` is every event the result settles, to be marked seen once the result is delivered.
213
+ */
214
+ export function pendingEvents(inst, result) {
215
+ if (inst.singletonViolation)
216
+ return { events: [], given: [] };
217
+ for (const id of inst.since.keys())
218
+ if (!ownsRun(inst, id))
219
+ inst.since.delete(id);
220
+ if (inst.ctx.kind !== "root" || !inst.since.size)
221
+ return { events: [], given: [] };
222
+ recordEvents(inst.since, (id) => inst.asking.has(id) || elicitationState(id) === "asking");
223
+ const named = reportedIn(result);
224
+ const views = [result, ...["nodes", "children"].flatMap((k) => Array.isArray(result[k]) ? result[k] : [])];
225
+ const completed = views.map((v) => v[REPORTED_COMPLETION]);
226
+ const events = [];
227
+ const unseen = unseenEvents([...inst.since.keys()]);
228
+ for (const e of unseen) {
229
+ // A person's decision is reported only by a result that names the request: one about the job
230
+ // that asked does not say who decided.
231
+ // A late answer is news whatever the result is about.
232
+ if (e.kind === "settled") {
233
+ // Reply events name the discussion/review and its participant separately. Generic node
234
+ // listings convey no reply, so keep that news explicit even if both ids are in the result.
235
+ // For ordinary completions the delivered snapshot must show the same settled state.
236
+ const node = getNode(e.subject);
237
+ if (e.item_id === e.subject && completed.some((v) => v?.id === e.subject && v.status === node?.status && v.endedAt === node?.ended_at))
238
+ continue;
239
+ }
240
+ else if (e.kind !== "late" && named.has(e.subject))
241
+ continue;
242
+ if (e.kind === "approval" && getRequest(e.subject)?.status !== "pending")
243
+ continue;
244
+ events.push({ event_id: e.id, kind: e.kind, item: e.item_id, about: e.subject, notice: noticeText(e) });
245
+ }
246
+ return { events, given: unseen.map((e) => e.id) };
247
+ }
@@ -0,0 +1,213 @@
1
+ // A job worktree's life, above git.ts's safe git commands: made for a write job (and dropped again
2
+ // if the job is never recorded), put back and checked before each turn, committed and looked at
3
+ // when a turn ends, and retired after a merge or by relay clean. Relay runs git unsandboxed in trees
4
+ // an agent wrote, so its rules are here in one place: a worktree's `.git` file is never trusted (git
5
+ // runs with the git directory the repository records, jobTree), the worktree is pinned by identity,
6
+ // relay's identity file is written by relay, and filters are refused unless trusted.
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { CONTEXT_DIR, writeWorktreeContext } from "./context.js";
10
+ import { busy, descendants, nextQueuedTurn, runConfig, setParam, updateNode, workCwd, worktreeHolder } from "./db.js";
11
+ import { checkoutOf, checkpoint, createWorktree, diffSummary, discardUnchanged, git, jobTree, removeWorktree, restoreWorktree, unchanged, } from "./git.js";
12
+ import { hardLinksOutside } from "../confine/hardlinks.js";
13
+ import { HARNESS_CONFIG } from "../confine/harness-config.js";
14
+ import { dirIdentity } from "../confine/index.js";
15
+ import { targetDef } from "../targets/index.js";
16
+ /**
17
+ * Makes a new write job's worktree and branch, from where the caller is: a caller inside a job's
18
+ * worktree (a launched agent in its own) branches from that worktree, found through relay's
19
+ * registry and the repository's records, not through its `.git` file. Returns why not, worded for
20
+ * the caller, when relay will not.
21
+ */
22
+ export function openJobWorktree(callerCwd, runId, jobId, trustFilters) {
23
+ const holder = worktreeHolder(callerCwd);
24
+ if (holder === "unknown")
25
+ return { refusal: `${callerCwd} is inside relay's worktree directory but in no job's worktree relay knows of, so relay will not run git there. Do this part yourself, or delegate it in read mode.` };
26
+ const wt = createWorktree(callerCwd, runId, jobId, trustFilters, holder ?? undefined);
27
+ if ("error" in wt)
28
+ return { refusal: `${wt.error}. Do this part yourself, or delegate it in read mode.` };
29
+ return wt;
30
+ }
31
+ /**
32
+ * A worktree and branch made for a job that was then never recorded belong to nothing: they are
33
+ * removed where git can do so cleanly (nothing has been written in them but relay's identity file).
34
+ */
35
+ export function discardJobWorktree(wt, trustFilters) {
36
+ try {
37
+ if (!removeWorktree(wt.repo, wt.worktree, trustFilters))
38
+ git(wt.repo, ["branch", "-D", wt.branch]);
39
+ }
40
+ catch {
41
+ // Left as they are; relay clean lists them.
42
+ }
43
+ }
44
+ /**
45
+ * Puts a job's worktree back before a turn, if it was removed after its branch was merged (or by
46
+ * clean), re-pins it if it was made again, and writes the turn's identity file. Returns why the turn
47
+ * must not start, or null. A session without a worktree of its own has nothing to prepare.
48
+ */
49
+ export function prepareTurnTree(node, cfg) {
50
+ if (!node.worktree || !node.repo || !node.branch)
51
+ return null;
52
+ const absent = !fs.lstatSync(node.worktree, { throwIfNoEntry: false });
53
+ const problem = restoreWorktree(node.repo, node.worktree, node.branch, node.head_sha ?? node.base_sha, cfg.trust_git_filters);
54
+ if (problem)
55
+ return problem;
56
+ // Made again here, so pinned again: the directory a relay-enforced turn checks it still is.
57
+ // Only the pin is set: a grant written meanwhile (restoring can take a while) is kept (review C11).
58
+ if (absent)
59
+ setParam(node.id, "worktree_pin", dirIdentity(node.worktree));
60
+ // The identity file. A write that cannot be made safely settles the turn failed rather than throwing.
61
+ try {
62
+ writeWorktreeContext(node.worktree, { run_id: node.run_id, node_id: node.id, depth: node.depth });
63
+ }
64
+ catch (err) {
65
+ return `relay could not write this turn's identity file in ${node.worktree}: ${err.message}`;
66
+ }
67
+ return null;
68
+ }
69
+ /** The job worktree a node's turns run in, found as jobTree finds it: its own, or the one it works in place in. */
70
+ export function turnTree(node) {
71
+ const holder = node.worktree ? node : worktreeHolder(workCwd(node));
72
+ if (holder === null)
73
+ return undefined;
74
+ if (holder === "unknown")
75
+ return { error: `its working directory ${node.cwd} is inside relay's worktree directory but in no job's worktree relay knows of, so relay will not start it there` };
76
+ if (!holder.repo || !holder.worktree)
77
+ return { error: `relay did not record the repository of the worktree ${node.cwd} is in` };
78
+ return jobTree(holder.repo, holder.worktree);
79
+ }
80
+ /**
81
+ * Why a write turn of a target with verified confinement (Claude's, Codex's own sandbox) must not
82
+ * start, or null: a file in the job's worktree or a granted write path that is a hard link to a file
83
+ * outside them. The sandbox decides by path, so a write to such a file goes through to the other
84
+ * name. Names in each root's `.git` and in the worktree's `.relay` count as outside: the sandboxes
85
+ * keep the agent from writing there (Claude's denies both in the worktree, Codex's a writable
86
+ * root's `.git`), and a second name elsewhere would let it. Relay-enforced launches make the same
87
+ * check in confine/index.ts (prepareLaunch), against the paths their profile hard-denies. `grant`
88
+ * is the turn's (session.ts grantFor): its write paths are roots too. `confinement`: the turn's own
89
+ * (backends/codex-stage2.ts turnConfinement): a stage-2 Codex turn of a verified target is
90
+ * relay-enforced, and its executor's launch makes the check.
91
+ */
92
+ export function hardLinkProblem(node, access, dangerous, tree, grant, confinement = "verified") {
93
+ if (access !== "write" || dangerous || confinement !== "verified" || targetDef(node.target).capabilities.confinement !== "verified")
94
+ return null;
95
+ const worktree = path.resolve(tree?.worktree ?? workCwd(node));
96
+ const roots = [worktree, ...(grant?.write_paths ?? []).map((p) => path.resolve(p))];
97
+ const denied = [...roots.flatMap((root) => [path.join(root, ".git"), ...HARNESS_CONFIG.map(name => path.join(root, name))]), path.join(worktree, CONTEXT_DIR)];
98
+ let linked;
99
+ try {
100
+ linked = hardLinksOutside(roots, { denied }).linked;
101
+ }
102
+ catch (err) {
103
+ return `relay could not check the worktree for hard links (${err.message}), so it did not start the turn`;
104
+ }
105
+ if (!linked.length)
106
+ return null;
107
+ return `relay will not launch a write turn here: ${linked[0]} is a hard link to a file outside the job's worktree${roots.length > 1 ? " and granted write paths" : ""}, and the sandbox, which decides by path, would let writes through to it. Replace it with a copy (pnpm: use a copying package-import method) and try again.`;
108
+ }
109
+ /**
110
+ * The git half of a job's result when a turn ends: relay commits what a write turn left (Codex's
111
+ * sandbox does not let the agent write .git), records the branch's tip, and summarises the change
112
+ * from the base up to that tip, which the result names (`commit`: what merge takes). A turn that
113
+ * finished with the branch still at its base, nothing uncommitted or untracked, has no changes to
114
+ * merge (no_changes; files git ignores are not looked at), whether or not the worktree can then be
115
+ * dropped. Returns the fields for the result, in the order it has them, or nothing for a job
116
+ * without a worktree.
117
+ */
118
+ export function endJobTurn(node, turn, o, cfg) {
119
+ // Every git command for the worktree runs with the git directory the repository records for it:
120
+ // the agent has just had the run of the worktree, `.git` file included.
121
+ const tree = node.worktree && node.base_sha ? (node.repo ? jobTree(node.repo, node.worktree) : { error: "relay did not record the job's repository" }) : null;
122
+ if (!tree)
123
+ return {};
124
+ if ("error" in tree) {
125
+ return { branch: node.branch, base_sha: node.base_sha, checkpoint_error: `relay did not commit or look at the work, because ${tree.error}. The work is still in the worktree` };
126
+ }
127
+ let out = {};
128
+ // Each step below asks git for itself rather than going by what an earlier one found: with this
129
+ // job's agent gone, other writers can still change what git reads between two of relay's calls (an
130
+ // included config another job may write, a root's merge into this worktree).
131
+ const cp = turn.access === "write" ? checkpoint(tree, node.id, cfg.trust_git_filters) : { sha: null };
132
+ if (cp.error)
133
+ out = { ...out, checkpoint_error: cp.error };
134
+ // The commit the diff summary is of, read once and named in the result (`commit`): merge takes
135
+ // exactly this commit, and nothing while the worktree or branch holds more, since a process the
136
+ // agent started can outlive the turn and go on writing to the worktree (ops.ts merge).
137
+ const tip = git(tree, ["rev-parse", "--verify", "HEAD^{commit}"]);
138
+ if (!tip.ok) {
139
+ // Without the commit there is no summary to show, and nothing to say the turn changed nothing.
140
+ return {
141
+ ...out, branch: node.branch, base_sha: node.base_sha, commit: null,
142
+ checkpoint_error: cp.error ?? `relay could not read the commit the worktree is at (${tip.err || `exit ${tip.code}`}), so it could not show the work. The work is still in the worktree`,
143
+ };
144
+ }
145
+ updateNode(node.id, { head_sha: tip.out });
146
+ const diff = diffSummary(tree, node.base_sha, tip.out);
147
+ out = { ...out, branch: node.branch, base_sha: node.base_sha, commit: tip.out, files_changed_git: diff.files, diff_stat: diff.stat };
148
+ if (!cp.error && o.status === "ok" && !diff.files.length && unchanged(tree, node.base_sha, cfg.trust_git_filters)) {
149
+ out = { ...out, no_changes: true };
150
+ // Nothing more is queued: drop the worktree and the empty branch. Both come back if the job is
151
+ // resumed. Not while agents this job started are still running (read jobs and consults work
152
+ // inside its worktree), nor while something the agent started may be (the turn's process
153
+ // warnings). Nor after a discussion turn (review C9): its result is not the job's, which keeps
154
+ // naming the worktree and branch its own turn kept (review X3: these gates are the worker's).
155
+ const discussionTurn = turn.source.startsWith("discussion:");
156
+ const inUse = descendants(node.id).some((d) => busy(d));
157
+ if (!discussionTurn && !inUse && !o.warnings.length && !nextQueuedTurn(node.id) && node.repo && node.branch && discardUnchanged(node.repo, tree, node.branch, node.base_sha, cfg.trust_git_filters)) {
158
+ out = { ...out, branch: null };
159
+ }
160
+ }
161
+ return out;
162
+ }
163
+ /**
164
+ * Whether a settled job's kept worktree is still as its turn left it, unchanged: true, or what
165
+ * says otherwise (a change, or why relay cannot look). A worktree that is not there any more has
166
+ * nothing to say against it. Asked through the git directory the repository records for the
167
+ * worktree, never its `.git` file (jobTree); a worktree relay will not run git in cannot be vouched for.
168
+ */
169
+ export function stillUnchanged(n) {
170
+ if (!n.worktree || !fs.existsSync(n.worktree))
171
+ return true;
172
+ const tree = nodeTree(n);
173
+ if ("error" in tree)
174
+ return tree;
175
+ return unchanged(tree, n.base_sha, runConfig(n.run_id).trust_git_filters, true) ? true : { changed: true };
176
+ }
177
+ /** A job's worktree as relay runs git in it (jobTree), or why it cannot. */
178
+ export const nodeTree = (n) => (n.repo ? jobTree(n.repo, n.worktree) : { error: `relay did not record ${n.id}'s repository` });
179
+ /**
180
+ * Where relay runs git for work in `dir`: inside a job's worktree, that worktree with the git
181
+ * directory the repository records for it (never what its `.git` file says); elsewhere, the
182
+ * checkout `dir` is in. Null when `dir` is in no git repository.
183
+ */
184
+ export function checkoutAt(dir) {
185
+ const holder = worktreeHolder(dir);
186
+ if (holder === "unknown")
187
+ return { error: `${dir} is inside relay's worktree directory but in no job's worktree relay knows of, so relay will not run git there` };
188
+ return checkoutOf(dir, holder ?? undefined);
189
+ }
190
+ /**
191
+ * Records where a job's branch stands, before its worktree or branch is removed. Relay can commit
192
+ * in a job's worktree after the job's own turn (before a merge, during clean), so the tip is read
193
+ * at the moment it matters, not only when a turn ends.
194
+ */
195
+ function saveTip(n) {
196
+ if (!n.worktree || !n.repo || !fs.existsSync(n.worktree))
197
+ return;
198
+ const tree = jobTree(n.repo, n.worktree);
199
+ // A worktree relay will not run git in is not removed either, so the tip recorded last stands.
200
+ if ("error" in tree)
201
+ return;
202
+ const tip = git(tree, ["rev-parse", "HEAD"]);
203
+ if (tip.ok)
204
+ updateNode(n.id, { head_sha: tip.out });
205
+ }
206
+ /**
207
+ * Retires a job's worktree: records where its branch stands (saveTip), then removes it. Returns why
208
+ * git kept it, or null once it is gone. The branch stays; resuming the job puts the worktree back.
209
+ */
210
+ export function retire(n, trustFilters) {
211
+ saveTip(n);
212
+ return removeWorktree(n.repo, n.worktree, trustFilters);
213
+ }