@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,657 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { worktreeDir } from "./config.js";
5
+ import { CONTEXT_DIR, readRegularFile } from "./context.js";
6
+ import { gitExecutable, notFound } from "./executables.js";
7
+ import { sendGroupSignal } from "./procs.js";
8
+ /**
9
+ * Settings for every git command relay runs. Relay's git runs outside any sandbox, with the user's
10
+ * access, in trees an agent has just written to, so nothing in such a tree may get code run
11
+ * through it:
12
+ * - Hooks are off. A relative core.hooksPath (Husky sets one) points inside the worktree, and
13
+ * --no-verify skips only some hooks.
14
+ * - The fsmonitor hook is off, and git does not look inside nested repositories, whose own
15
+ * config an agent can write (see untrustedNestedRepos for the one command this does not cover).
16
+ * This also means the user's own hooks do not run for relay's commits, merges and checkouts.
17
+ * Content filters and merge drivers are refused before any command that could run them
18
+ * (filterRefusal); diff drivers and an external diff are left alone, since relay's own diffs pass
19
+ * --no-ext-diff --no-textconv. A job's worktree is never located through its own `.git` file (jobTree).
20
+ */
21
+ const SAFE = [
22
+ "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-c", "submodule.recurse=false", "-c", "diff.ignoreSubmodules=dirty",
23
+ // Signing can stop to ask for a passphrase, with nobody there. Relay's own commits are unsigned.
24
+ "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false",
25
+ ];
26
+ const GIT_TIMEOUT_MS = 300_000;
27
+ /**
28
+ * For relay's own checkouts and merges: Git LFS leaves its pointer files in place instead of
29
+ * fetching the objects. Its smudge filter downloads from the server the repository's settings name,
30
+ * with your credentials and outside any sandbox, and `.lfsconfig`, a file in the tree an agent
31
+ * wrote, can name another server. Objects already stored locally are not affected by this; files
32
+ * left as pointers are filled in with `git lfs checkout` (or `git lfs pull`).
33
+ */
34
+ const NO_LFS_FETCH = { GIT_LFS_SKIP_SMUDGE: "1" };
35
+ /**
36
+ * For relay's `git worktree add`: write the files with four processes when there are at least 400
37
+ * to write. On a 3,000-file tree this took the checkout from about 200 ms to 130; below about 400
38
+ * files starting the workers costs more than it saves. The workers are git's own
39
+ * (`git checkout--worker`, git 2.32 and later), started by git, in its process group and with its
40
+ * settings; an older git ignores keys it does not know. A file that needs a filter (Git LFS's,
41
+ * whose downloads are skipped all the same) is still written by git itself.
42
+ */
43
+ const PARALLEL_CHECKOUT = ["-c", "checkout.workers=4", "-c", "checkout.thresholdForParallelism=400"];
44
+ /** For relay's commands that name files: every name is that one file, never a pathspec pattern or magic. */
45
+ const LITERAL_PATHS = { GIT_LITERAL_PATHSPECS: "1" };
46
+ export function git(at, args, env = {}) {
47
+ return gitWithin(GIT_TIMEOUT_MS, at, args, env);
48
+ }
49
+ /** git() under another time limit, so that a test can make git overrun; relay itself goes through git(). */
50
+ export function gitWithin(timeoutMs, at, args, env = {}) {
51
+ const cwd = typeof at === "string" ? at : at.worktree;
52
+ // The git found on PATH when this process first ran one, by its absolute name (executables.ts).
53
+ const bin = gitExecutable();
54
+ if (!bin)
55
+ return { ok: false, out: "", raw: "", err: notFound("git"), code: null };
56
+ const options = {
57
+ cwd,
58
+ encoding: "utf8",
59
+ timeout: timeoutMs,
60
+ killSignal: "SIGKILL",
61
+ // Git starts as the leader of a new session, and so of its own process group, so that a git that
62
+ // overruns is stopped together with whatever it started (a filter or credential helper, say),
63
+ // not just git itself. Node's synchronous spawn applies this as its asynchronous one does
64
+ // (spawn_sync.cc), though its types leave it out; test/git-safety.test.ts holds it to that. It
65
+ // replaced a perl wrapper that called setpgrp, a process start on every call.
66
+ detached: true,
67
+ // The C locale, because relay reads some of git's messages.
68
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", LC_ALL: "C", LANG: "C", ...(typeof at === "string" ? {} : at.env), ...env },
69
+ };
70
+ const r = spawnSync(bin, [...SAFE, ...args], options);
71
+ if (r.error) {
72
+ const timedOut = r.error.code === "ETIMEDOUT";
73
+ if (timedOut && r.pid) {
74
+ try {
75
+ sendGroupSignal(r.pid, "SIGKILL");
76
+ }
77
+ catch {
78
+ // Nothing of it is left.
79
+ }
80
+ }
81
+ return { ok: false, out: "", raw: "", err: timedOut ? `git ${args[0]} did not finish within ${timeoutMs / 1000}s` : r.error.message, code: null };
82
+ }
83
+ return { ok: r.status === 0, out: (r.stdout ?? "").trim(), raw: r.stdout ?? "", err: (r.stderr ?? "").trim(), code: r.status };
84
+ }
85
+ /** NUL-separated names from git's -z output. */
86
+ const names = (r) => r.raw.split("\0").filter(Boolean);
87
+ /** A repository's common git directory, its real path, asked of a checkout relay trusts; null when git cannot say. */
88
+ function commonDirOf(at) {
89
+ const r = git(at, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
90
+ if (!r.ok || !r.out)
91
+ return null;
92
+ try {
93
+ return fs.realpathSync(r.out);
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ }
99
+ /** A `.git` file or `gitdir` record as git writes one is a line or two; anything bigger is not git's. */
100
+ const RECORD_MAX_BYTES = 8192;
101
+ const readRecord = (file) => {
102
+ try {
103
+ return readRegularFile(file, RECORD_MAX_BYTES);
104
+ }
105
+ catch {
106
+ return null;
107
+ }
108
+ };
109
+ const realOrNull = (p) => {
110
+ try {
111
+ return fs.realpathSync(p);
112
+ }
113
+ catch {
114
+ return null;
115
+ }
116
+ };
117
+ /**
118
+ * The job worktree `worktree` of the repository whose main checkout is `repo`, with the git
119
+ * directory the repository itself records for it, or why relay will not run git there.
120
+ *
121
+ * The record is found from the repository's side, which no job can write: each linked worktree has
122
+ * a directory `<common>/worktrees/<name>` whose `gitdir` file names the worktree's `.git`. The
123
+ * worktree's own `.git` file must still be the regular file pointing back at that directory. A job's
124
+ * agent can rewrite it, and git would then take its config, and the commands it names, from
125
+ * wherever the file points; relay refuses rather than run git for that worktree at all. Call it
126
+ * before every operation: nothing about a worktree an agent can write stays true between two.
127
+ */
128
+ export function jobTree(repo, worktree) {
129
+ const wt = realOrNull(worktree);
130
+ if (!wt)
131
+ return { error: `the worktree ${worktree} no longer exists` };
132
+ const common = commonDirOf(repo);
133
+ if (!common)
134
+ return { error: `git could not find the git directory of ${repo}, so relay cannot tell which git directory the worktree ${wt} belongs to` };
135
+ const records = path.join(common, "worktrees");
136
+ let entries = [];
137
+ try {
138
+ entries = fs.readdirSync(records);
139
+ }
140
+ catch {
141
+ // No linked worktrees at all.
142
+ }
143
+ const matches = entries.map((name) => path.join(records, name)).filter((admin) => {
144
+ const back = readRecord(path.join(admin, "gitdir"));
145
+ if (back === null)
146
+ return false;
147
+ // Absolute as git writes it by default; relative to the record with worktree.useRelativePaths.
148
+ const target = path.resolve(admin, back.trim());
149
+ return path.basename(target) === ".git" && realOrNull(path.dirname(target)) === wt;
150
+ });
151
+ if (matches.length === 0)
152
+ return { error: `the repository ${repo} has no record of the worktree ${wt} (in ${records}), so relay will not run git there` };
153
+ if (matches.length > 1)
154
+ return { error: `the repository ${repo} records the worktree ${wt} more than once (${matches.join(", ")}), so relay cannot tell which git directory is its own. \`git -C ${repo} worktree prune\` removes stale records` };
155
+ const gitDir = realOrNull(matches[0]);
156
+ if (!gitDir)
157
+ return { error: `the git directory ${matches[0]} of the worktree ${wt} is gone` };
158
+ const dotGit = path.join(wt, ".git");
159
+ const changed = {
160
+ error: `${dotGit} is no longer the file git made for this worktree, pointing at ${gitDir}: the job's agent, which can write there, changed it. ` +
161
+ `Relay will not run git for this worktree while it is so. Look at what the agent did; if the change is not wanted, delete whatever is at ${dotGit} ` +
162
+ `(\`rm -r\`, which does not follow a link; git's own repair would write through one) and run \`git -C ${repo} worktree repair ${wt}\` to put the file back`,
163
+ };
164
+ const text = readRecord(dotGit);
165
+ const m = text === null ? null : /^gitdir: ([^\n]+)\n?$/.exec(text);
166
+ if (!m)
167
+ return changed;
168
+ if (realOrNull(path.resolve(wt, m[1].trim())) !== gitDir)
169
+ return changed;
170
+ return { worktree: wt, gitDir, commonDir: common, env: { GIT_DIR: gitDir, GIT_WORK_TREE: wt } };
171
+ }
172
+ /**
173
+ * The checkout `dir` is in. `holder`: the job whose worktree holds `dir`, from relay's registry,
174
+ * when it is a job's (a launched agent delegating from its own worktree, say). Its git directory
175
+ * then comes from the repository's records (jobTree) and its main checkout from the registry,
176
+ * never from the worktree's `.git` file. Null when `dir` is not in a git repository.
177
+ */
178
+ export function checkoutOf(dir, holder) {
179
+ if (holder) {
180
+ if (!holder.repo || !holder.worktree)
181
+ return { error: `${dir} is in a job's worktree whose repository relay did not record` };
182
+ const tree = jobTree(holder.repo, holder.worktree);
183
+ if ("error" in tree)
184
+ return tree;
185
+ return { at: tree, top: tree.worktree, repo: holder.repo };
186
+ }
187
+ const top = repoRoot(dir);
188
+ if (!top)
189
+ return null;
190
+ return { at: top, top, repo: mainWorktree(top) ?? top };
191
+ }
192
+ /**
193
+ * Configured commands git can run on files in the tree, that relay will not run: content filters
194
+ * (clean, smudge, process) other than Git LFS's, and merge drivers. Git runs these when it stages,
195
+ * checks out or merges a file that names them in its attributes, and relay's git is not sandboxed.
196
+ * Diff drivers (textconv, command) and an external diff are left alone: relay's own diffs and greps
197
+ * pass --no-ext-diff and --no-textconv, and nothing else relay runs uses them, so refusing them would
198
+ * only stop people who have difftastic or the like configured. A command that is a script in the
199
+ * repository, or an interpreter that looks for its modules in the current directory, would run
200
+ * whatever the agent left there. Git LFS is a compiled program that takes nothing of the kind.
201
+ */
202
+ /** Git LFS's filter commands exactly as `git lfs install` writes them, and nothing appended. */
203
+ const LFS = /^git[- ]lfs (?:(?:clean|smudge)(?: --skip)? -- %f|filter-process(?: --skip)?)$/;
204
+ const COMMAND_KEYS = "^(filter\\..*\\.(clean|smudge|process)|merge\\..*\\.driver)$";
205
+ function configuredCommands(at) {
206
+ // NUL-terminated entries of "key\nvalue": a value can itself span lines, and each line must not be read as an entry of its own.
207
+ const r = git(at, ["config", "-z", "--get-regexp", COMMAND_KEYS]);
208
+ // Exit status 1 with nothing printed is git's way of saying there are none. Anything else is not knowing, which counts against.
209
+ if (r.code === 1 && !r.out && !r.err)
210
+ return [];
211
+ if (!r.ok)
212
+ return { error: r.err || `exit ${r.code}` };
213
+ return r.raw.split("\0").filter(Boolean).map((entry) => {
214
+ const nl = entry.indexOf("\n");
215
+ return { key: nl < 0 ? entry : entry.slice(0, nl), command: nl < 0 ? "" : entry.slice(nl + 1) };
216
+ }).filter((f) => f.command && !(f.key.startsWith("filter.") && LFS.test(f.command)));
217
+ }
218
+ const kindOf = (key) => (key.startsWith("filter.") ? "a content filter" : "a merge driver");
219
+ /**
220
+ * Why relay will not run git here, or null: the admission check before every relay git command
221
+ * that can run a content filter or a driver (staging, checking out, merging, and `git status`,
222
+ * which runs the clean filter on files whose timestamps leave it unsure).
223
+ */
224
+ export function filterRefusal(at, trust) {
225
+ if (trust)
226
+ return null;
227
+ const found = configuredCommands(at);
228
+ if ("error" in found) {
229
+ return `relay could not read this repository's filter and driver settings (${found.error}), so it cannot tell what git would run outside the sandbox on files an agent wrote`;
230
+ }
231
+ if (!found.length)
232
+ return null;
233
+ const kinds = [...new Set(found.map((f) => kindOf(f.key)))];
234
+ return `this repository runs ${kinds.join(" and ")} (${found.map((f) => `${f.key} = ${JSON.stringify(f.command)}`).join("; ")}) that relay would have to run outside the sandbox on files an agent wrote. ` +
235
+ `Set "trust_git_filters": true in relay's config if ${found.length > 1 ? "these commands" : "that command"} cannot be redirected by files in the repository`;
236
+ }
237
+ /** Fallback identity so checkpoints work in repos with no user configured. */
238
+ function identityArgs(at) {
239
+ const name = git(at, ["config", "user.name"]).out;
240
+ const email = git(at, ["config", "user.email"]).out;
241
+ const args = [];
242
+ if (!name)
243
+ args.push("-c", "user.name=relay");
244
+ if (!email)
245
+ args.push("-c", "user.email=relay@localhost");
246
+ return args;
247
+ }
248
+ /** For a directory in a checkout relay trusts; a job's worktree is located with jobTree instead. */
249
+ export function repoRoot(cwd) {
250
+ const r = git(cwd, ["rev-parse", "--show-toplevel"]);
251
+ return r.ok ? r.out : null;
252
+ }
253
+ /**
254
+ * The repository's main worktree. Git operations that manage worktrees and branches run from
255
+ * here, because a job's own worktree (where a nested job is started from) can be removed later.
256
+ * For a directory in a checkout relay trusts; for a job's worktree the registry records it.
257
+ */
258
+ function mainWorktree(cwd) {
259
+ const r = git(cwd, ["worktree", "list", "--porcelain"]);
260
+ const first = r.ok ? r.out.split("\n").find((l) => l.startsWith("worktree ")) : undefined;
261
+ return first ? first.slice("worktree ".length) : null;
262
+ }
263
+ /**
264
+ * "unknown" when git could not tell: a failed status query must never be read as clean. `git status`
265
+ * can run the clean filter, so the caller runs filterRefusal first.
266
+ */
267
+ export function treeState(at, env = {}) {
268
+ if (!fs.existsSync(typeof at === "string" ? at : at.worktree))
269
+ return "unknown";
270
+ // Untracked files are asked for explicitly: status.showUntrackedFiles=no would hide new files,
271
+ // and a tree that only looks clean gets removed.
272
+ const r = git(at, ["status", "--porcelain", "--untracked-files=all"], env);
273
+ if (!r.ok)
274
+ return "unknown";
275
+ return r.out.length > 0 ? "dirty" : "clean";
276
+ }
277
+ /**
278
+ * Nested repositories in a worktree whose git directory is not part of the repository itself.
279
+ * An agent can write such a repository's config (filters, for one), and `git add` runs git inside
280
+ * it, so relay does not stage a tree that contains one. A submodule checked out the usual way
281
+ * keeps its git directory inside the main repository's, where a job cannot write, and is fine.
282
+ */
283
+ export function untrustedNestedRepos(at) {
284
+ const worktree = typeof at === "string" ? at : at.worktree;
285
+ const common = typeof at === "string" ? commonDirOf(at) : at.commonDir;
286
+ // NUL-separated output, so that a name with spaces or quotes is read as it is, not as git quotes it.
287
+ const links = git(at, ["ls-files", "-s", "-z"]);
288
+ // git does not list the files of an untracked nested repository, only its directory.
289
+ const status = git(at, ["status", "--porcelain", "-z", "--untracked-files=all"]);
290
+ // Not knowing is not the same as finding none.
291
+ if (!common || !links.ok || !status.ok)
292
+ return null;
293
+ const gitlinks = names(links).filter((l) => l.startsWith("160000 ")).map((l) => l.slice(l.indexOf("\t") + 1));
294
+ const untracked = names(status).filter((l) => l.startsWith("?? ") && l.endsWith("/")).map((l) => l.slice(3, -1));
295
+ return [...new Set([...gitlinks, ...untracked])].filter((rel) => {
296
+ const entry = path.join(worktree, rel, ".git");
297
+ let st;
298
+ try {
299
+ st = fs.lstatSync(entry);
300
+ }
301
+ catch {
302
+ return false;
303
+ }
304
+ if (!st.isFile())
305
+ return true;
306
+ const text = readRecord(entry);
307
+ const m = text === null ? null : /^gitdir:\s*(.+)\s*$/m.exec(text);
308
+ if (!m)
309
+ return true;
310
+ const target = realOrNull(path.resolve(path.dirname(entry), m[1]));
311
+ if (!target)
312
+ return true;
313
+ return !(target === common || target.startsWith(common + path.sep));
314
+ });
315
+ }
316
+ /**
317
+ * Adds relay's context directory to the repository's `info/exclude`, so that the agent's commits
318
+ * leave it out. `common` is the repository's git directory as its main checkout gives it, never as
319
+ * a job's worktree does. Relay appends outside any sandbox, so it follows no link: a link at
320
+ * `info` or `info/exclude`, or a file with a second name elsewhere, would carry the write to
321
+ * another file. Returns why it would not, or null.
322
+ */
323
+ function excludeContextDir(common) {
324
+ const info = path.join(common, "info");
325
+ const exclude = path.join(info, "exclude");
326
+ const line = `${CONTEXT_DIR}/`;
327
+ try {
328
+ if (!fs.existsSync(info) && !isLink(info))
329
+ fs.mkdirSync(info);
330
+ if (!fs.lstatSync(info).isDirectory())
331
+ return `${info} is not a directory, and relay does not write through links there`;
332
+ let fd;
333
+ try {
334
+ fd = fs.openSync(exclude, fs.constants.O_RDWR | fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, 0o644);
335
+ }
336
+ catch (err) {
337
+ if (err.code === "ELOOP")
338
+ return `${exclude} is a symbolic link, and relay does not write through links there`;
339
+ throw err;
340
+ }
341
+ try {
342
+ const st = fs.fstatSync(fd);
343
+ if (!st.isFile())
344
+ return `${exclude} is not a regular file`;
345
+ if (st.nlink !== 1)
346
+ return `${exclude} has ${st.nlink} names (hard links), so writing to it would change another file too`;
347
+ const current = fs.readFileSync(fd, "utf8");
348
+ if (!current.split("\n").includes(line))
349
+ fs.writeSync(fd, `${current.endsWith("\n") || !current ? "" : "\n"}${line}\n`);
350
+ }
351
+ finally {
352
+ fs.closeSync(fd);
353
+ }
354
+ }
355
+ catch (err) {
356
+ return `relay could not add ${line} to ${exclude}: ${err.message}`;
357
+ }
358
+ return null;
359
+ }
360
+ const isLink = (p) => {
361
+ try {
362
+ return fs.lstatSync(p).isSymbolicLink();
363
+ }
364
+ catch {
365
+ return false;
366
+ }
367
+ };
368
+ /**
369
+ * A new worktree and branch for a write job, branched from the caller's HEAD. `holder`: the job
370
+ * whose worktree the caller is in (see checkoutOf), from relay's registry.
371
+ */
372
+ export function createWorktree(callerCwd, runId, jobId, trustFilters = false, holder) {
373
+ const from = checkoutOf(callerCwd, holder);
374
+ if (!from)
375
+ return { error: `${callerCwd} is not inside a git repository, and write jobs need one for their worktree` };
376
+ if ("error" in from)
377
+ return from;
378
+ const filters = filterRefusal(from.at, trustFilters);
379
+ if (filters)
380
+ return { error: filters };
381
+ const head = git(from.at, ["rev-parse", "HEAD"]);
382
+ if (!head.ok)
383
+ return { error: "the repository has no commits yet, so there is nothing to branch a worktree from" };
384
+ // Branch from the caller's HEAD, but manage the worktree from the main one, which outlives jobs.
385
+ const repo = from.repo;
386
+ const common = commonDirOf(repo);
387
+ if (!common)
388
+ return { error: `git could not find the git directory of ${repo}` };
389
+ // Keep relay's context file out of the agent's commits.
390
+ const excluded = excludeContextDir(common);
391
+ if (excluded)
392
+ return { error: excluded };
393
+ // `git worktree add` runs in the main worktree (repo), whose per-worktree config
394
+ // (extensions.worktreeConfig, config.worktree) can name a filter the caller's own context does
395
+ // not show; the checkout of the new worktree runs it. Admit that exact context too, not just the
396
+ // caller's, before adding.
397
+ const mainFilters = filterRefusal(repo, trustFilters);
398
+ if (mainFilters)
399
+ return { error: mainFilters };
400
+ const branch = `relay/${jobId}`;
401
+ const worktree = worktreeDir(runId, jobId);
402
+ fs.mkdirSync(path.dirname(worktree), { recursive: true });
403
+ const add = git(repo, [...PARALLEL_CHECKOUT, "worktree", "add", "-b", branch, worktree, head.out], NO_LFS_FETCH);
404
+ if (!add.ok)
405
+ return { error: `git worktree add failed: ${add.err}` };
406
+ const tree = jobTree(repo, worktree);
407
+ if ("error" in tree)
408
+ return { error: `relay could not find the git directory of the worktree it made: ${tree.error}` };
409
+ // The caller's position in its checkout, told to the agent rather than used as its directory. Only
410
+ // a path that leaves the checkout is dropped: a directory merely named "..something" is inside it.
411
+ const rel = path.relative(fs.realpathSync(from.top), fs.realpathSync(callerCwd));
412
+ const outside = rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel);
413
+ const subdir = outside ? "" : rel.split(path.sep).join("/");
414
+ return { repo, worktree, subdir, branch, baseSha: head.out, callerDirty: treeState(from.at) !== "clean" };
415
+ }
416
+ /** The files still in conflict, from the index alone, NUL-separated; null when git cannot say. */
417
+ function unmergedFiles(at) {
418
+ const r = git(at, ["ls-files", "-u", "-z"]);
419
+ if (!r.ok)
420
+ return null;
421
+ // One entry per stage: "<mode> <object> <stage>\t<name>".
422
+ return [...new Set(names(r).map((e) => e.slice(e.indexOf("\t") + 1)))];
423
+ }
424
+ const mergeInProgress = (at) => git(at, ["rev-parse", "-q", "--verify", "MERGE_HEAD"]).ok;
425
+ /**
426
+ * Commits anything uncommitted in the worktree. Refuses while a merge is unfinished, so conflict
427
+ * markers are never committed on the agent's behalf. A failure is reported, not swallowed.
428
+ */
429
+ export function checkpoint(at, label, trustFilters = false) {
430
+ const filters = filterRefusal(at, trustFilters);
431
+ if (filters)
432
+ return { sha: null, error: `relay did not commit the work, because ${filters}; the work is still in the worktree` };
433
+ const unmerged = unmergedFiles(at);
434
+ if (unmerged === null)
435
+ return { sha: null, error: "git could not report whether the worktree has an unfinished merge, so relay did not commit it; any work is still in the worktree" };
436
+ if (mergeInProgress(at) || unmerged.length) {
437
+ return { sha: null, error: "the worktree has an unfinished merge, so relay did not commit it; the work is still in the worktree" };
438
+ }
439
+ const state = treeState(at);
440
+ if (state === "unknown")
441
+ return { sha: null, error: "git could not report the worktree's state, so relay did not commit it; any work is still in the worktree" };
442
+ if (state === "clean")
443
+ return { sha: null };
444
+ const nested = untrustedNestedRepos(at);
445
+ if (nested === null)
446
+ return { sha: null, error: "git could not report what is in the worktree, so relay did not commit it; the work is still in the worktree" };
447
+ if (nested.length) {
448
+ return { sha: null, error: `the worktree contains a nested git repository (${nested.join(", ")}), which relay will not run git in, so relay did not commit the work; it is still in the worktree` };
449
+ }
450
+ const add = git(at, ["add", "-A"]);
451
+ if (!add.ok)
452
+ return { sha: null, error: `relay could not stage the work (${add.err || add.out}); it is still uncommitted in the worktree` };
453
+ const c = git(at, [...identityArgs(at), "commit", "--no-verify", "-m", `relay: checkpoint ${label}`]);
454
+ if (!c.ok)
455
+ return { sha: null, error: `relay could not commit the work (${c.err || c.out}); it is still uncommitted in the worktree` };
456
+ return { sha: git(at, ["rev-parse", "HEAD"]).out };
457
+ }
458
+ const DIFF = ["diff", "--no-ext-diff", "--no-textconv"];
459
+ /**
460
+ * Between two commits, so no file in the worktree is read; external diffs and textconv are off all
461
+ * the same. `tip`: the commit the summary is of, read once by the caller, so that the summary and
462
+ * the commit it names cannot differ.
463
+ */
464
+ export function diffSummary(at, baseSha, tip = "HEAD") {
465
+ // A commit differs from itself in nothing.
466
+ if (tip === baseSha)
467
+ return { stat: "", files: [] };
468
+ return {
469
+ stat: git(at, [...DIFF, "--stat", `${baseSha}..${tip}`]).out,
470
+ files: names(git(at, [...DIFF, "--name-only", "-z", `${baseSha}..${tip}`])),
471
+ };
472
+ }
473
+ /**
474
+ * What a job's worktree holds that `commit` does not: commits since, uncommitted changes, untracked
475
+ * files. Null when the worktree is at `commit` with nothing else in it. `git status` and a diff
476
+ * against the worktree can run the clean filter, so the caller runs filterRefusal first.
477
+ */
478
+ export function worktreeChanges(at, commit) {
479
+ const head = git(at, ["rev-parse", "--verify", "-q", "HEAD^{commit}"]);
480
+ if (!head.ok)
481
+ return { error: `git could not read the commit ${at.worktree} is at${head.err ? ` (${head.err})` : ""}` };
482
+ // Untracked files are asked for explicitly, as in treeState.
483
+ const status = git(at, ["status", "--porcelain", "-z", "--untracked-files=all"]);
484
+ if (!status.ok)
485
+ return { error: `git could not report the state of ${at.worktree}${status.err ? ` (${status.err})` : ""}` };
486
+ const uncommitted = status.raw.length > 0;
487
+ if (head.out === commit && !uncommitted)
488
+ return null;
489
+ // From the commit to the files in the worktree, so that committed and uncommitted changes are one list.
490
+ const tracked = git(at, [...DIFF, "--name-only", "-z", commit, "--"]);
491
+ const untracked = git(at, ["ls-files", "--others", "--exclude-standard", "-z"]);
492
+ const stat = git(at, [...DIFF, "--stat", commit, "--"]);
493
+ const failed = [tracked, untracked, stat].find((r) => !r.ok);
494
+ if (failed)
495
+ return { error: `git could not list what changed in ${at.worktree} since ${commit}${failed.err ? ` (${failed.err})` : ""}` };
496
+ return { now: head.out, uncommitted, files: [...new Set([...names(tracked), ...names(untracked)])].sort(), stat: stat.out };
497
+ }
498
+ /** What a job's branch holds that `commit` does not, between the two commits, or null when the branch is still at it. */
499
+ export function branchChanges(at, branch, commit) {
500
+ const tip = git(at, ["rev-parse", "--verify", "-q", `refs/heads/${branch}^{commit}`]);
501
+ if (!tip.ok)
502
+ return { error: `the branch ${branch} is no longer in the repository` };
503
+ if (tip.out === commit)
504
+ return null;
505
+ const files = git(at, [...DIFF, "--name-only", "-z", commit, tip.out, "--"]);
506
+ const stat = git(at, [...DIFF, "--stat", commit, tip.out, "--"]);
507
+ const failed = [files, stat].find((r) => !r.ok);
508
+ if (failed)
509
+ return { error: `git could not list what changed on ${branch} since ${commit}${failed.err ? ` (${failed.err})` : ""}` };
510
+ return { now: tip.out, uncommitted: false, files: names(files).sort(), stat: stat.out };
511
+ }
512
+ /**
513
+ * Merges a job's branch into `at`. `commit`: merge exactly that commit of the branch (the one the
514
+ * job's result showed), not wherever the branch is by the time git reads it; the merge commit's
515
+ * message still names the branch.
516
+ */
517
+ export function mergeBranch(at, branch, trustFilters = false, commit) {
518
+ const filters = filterRefusal(at, trustFilters);
519
+ if (filters)
520
+ return { status: "error", error: `nothing was merged, because ${filters}. Or merge ${branch} yourself with git` };
521
+ const what = commit ? ["-m", `Merge branch '${branch}' at ${commit}`, commit] : [branch];
522
+ const m = git(at, [...identityArgs(at), "merge", "--no-ff", "--no-edit", "--no-verify", ...what], NO_LFS_FETCH);
523
+ if (m.ok) {
524
+ if (/Already up to date/i.test(m.out))
525
+ return { status: "up_to_date" };
526
+ return { status: "merged", commit: git(at, ["rev-parse", "HEAD"]).out };
527
+ }
528
+ const conflicted = unmergedFiles(at);
529
+ if (conflicted?.length) {
530
+ return {
531
+ status: "conflict",
532
+ files: conflicted,
533
+ hint: "Resolve the conflict markers in these files, then call merge again with continue = true.",
534
+ };
535
+ }
536
+ return { status: "error", error: m.err || m.out };
537
+ }
538
+ export function continueMerge(at, trustFilters = false) {
539
+ // Staging the resolved files runs the clean filter, and `git status`-like checks can too.
540
+ const filters = filterRefusal(at, trustFilters);
541
+ if (filters)
542
+ return { status: "error", error: `relay did not finish the merge, because ${filters}. Or finish it yourself with git` };
543
+ if (!mergeInProgress(at))
544
+ return { status: "error", error: "no merge is in progress here" };
545
+ const unmerged = unmergedFiles(at);
546
+ if (unmerged === null)
547
+ return { status: "error", error: "git could not list the files still in conflict, so relay did not finish the merge" };
548
+ // The names as the index holds them, each taken literally: a file named like a pathspec (`*`, `:(glob)…`) is only itself.
549
+ let remaining = [];
550
+ if (unmerged.length) {
551
+ const g = git(at, ["grep", "-l", "-z", "--no-textconv", "-E", "^(<<<<<<<|>>>>>>>) ", "--", ...unmerged], LITERAL_PATHS);
552
+ // Exit status 1 is grep finding nothing.
553
+ if (!g.ok && !(g.code === 1 && !g.err))
554
+ return { status: "error", error: `git could not look for conflict markers (${g.err || `exit ${g.code}`}), so relay did not finish the merge` };
555
+ remaining = names(g);
556
+ }
557
+ if (remaining.length)
558
+ return { status: "conflict", files: remaining, hint: "These files still contain conflict markers." };
559
+ // Stage only the files that were in conflict; unrelated work in the tree stays out of the merge commit.
560
+ if (unmerged.length) {
561
+ const add = git(at, ["add", "--", ...unmerged], LITERAL_PATHS);
562
+ if (!add.ok)
563
+ return { status: "error", error: `relay could not stage the resolved files (${add.err || add.out})` };
564
+ }
565
+ const c = git(at, [...identityArgs(at), "commit", "--no-edit", "--no-verify"]);
566
+ if (!c.ok)
567
+ return { status: "error", error: c.err || c.out };
568
+ return { status: "merged", commit: git(at, ["rev-parse", "HEAD"]).out };
569
+ }
570
+ /**
571
+ * Removes a job's worktree directory, but only when everything in it is committed. The branch is
572
+ * left alone, so the work stays reachable. Returns why the worktree was kept, or null once it is gone.
573
+ */
574
+ export function removeWorktree(repo, worktree, trustFilters = false) {
575
+ if (fs.existsSync(worktree)) {
576
+ const tree = jobTree(repo, worktree);
577
+ if ("error" in tree)
578
+ return tree.error;
579
+ if (mergeInProgress(tree))
580
+ return "it has an unfinished merge";
581
+ const filters = filterRefusal(tree, trustFilters);
582
+ if (filters)
583
+ return `relay will not ask git whether it holds uncommitted work, because ${filters}`;
584
+ const state = treeState(tree);
585
+ if (state === "dirty")
586
+ return "it has uncommitted changes";
587
+ if (state === "unknown")
588
+ return "git could not report its state";
589
+ // --force only so that ignored files (relay's own context file among them) do not block removal.
590
+ const r = git(repo, ["worktree", "remove", "--force", tree.worktree]);
591
+ if (!r.ok)
592
+ return `git could not remove it (${r.err})`;
593
+ }
594
+ git(repo, ["worktree", "prune"]);
595
+ return null;
596
+ }
597
+ /** Puts a removed worktree back from its branch, for a job that is resumed after cleanup. */
598
+ export function restoreWorktree(repo, worktree, branch, tipSha, trustFilters = false) {
599
+ if (fs.existsSync(worktree))
600
+ return null;
601
+ const filters = filterRefusal(repo, trustFilters);
602
+ if (filters)
603
+ return `could not restore the worktree for ${branch}: ${filters}`;
604
+ git(repo, ["worktree", "prune"]);
605
+ fs.mkdirSync(path.dirname(worktree), { recursive: true });
606
+ // The branch is gone if the job changed nothing, or if it was merged and then cleaned up. It is
607
+ // recreated at the job's own last commit, so the resumed job finds its earlier work in place.
608
+ const exists = git(repo, ["rev-parse", "-q", "--verify", `refs/heads/${branch}`]).ok;
609
+ if (!exists && tipSha && !git(repo, ["cat-file", "-e", `${tipSha}^{commit}`]).ok)
610
+ return `could not restore the worktree for ${branch}: its last commit ${tipSha} is no longer in the repository`;
611
+ const add = exists || !tipSha
612
+ ? git(repo, [...PARALLEL_CHECKOUT, "worktree", "add", worktree, branch], NO_LFS_FETCH)
613
+ : git(repo, [...PARALLEL_CHECKOUT, "worktree", "add", "-b", branch, worktree, tipSha], NO_LFS_FETCH);
614
+ return add.ok ? null : `could not restore the worktree for ${branch}: ${add.err}`;
615
+ }
616
+ /** For git that only looks (a view): no optional locks, so `git status` does not take the index lock to refresh the index and write it. */
617
+ const LOOK_ONLY = { GIT_OPTIONAL_LOCKS: "0" };
618
+ /**
619
+ * True when a job's worktree is exactly where the job started: the branch has no commits beyond
620
+ * its base and nothing is uncommitted or untracked. Anything git cannot answer counts as changed,
621
+ * and so does a repository whose filters or drivers relay will not run (`git status` can run the
622
+ * clean filter). `lookOnly`, for a view asking again of a worktree that is kept while something
623
+ * the job started may still be running git in it: git takes no optional locks (review C20).
624
+ */
625
+ export function unchanged(at, baseSha, trustFilters = false, lookOnly = false) {
626
+ if (filterRefusal(at, trustFilters))
627
+ return false;
628
+ const env = lookOnly ? LOOK_ONLY : {};
629
+ const head = git(at, ["rev-parse", "HEAD"], env);
630
+ if (!head.ok || head.out !== baseSha || treeState(at, env) !== "clean")
631
+ return false;
632
+ // Asked a second way, since what can follow is deleting someone's new files.
633
+ const others = git(at, ["ls-files", "--others", "--exclude-standard"], env);
634
+ return others.ok && !others.out;
635
+ }
636
+ /**
637
+ * Removes the worktree and branch of a job with no changes to merge, so an empty branch is not left
638
+ * behind. Every question is asked of git again, however recently the caller asked it: relay does
639
+ * not hold git's inputs to itself between two of its calls (another job's agent can write a config
640
+ * the repository includes; a root's merge can move this job's HEAD), and what follows deletes.
641
+ */
642
+ export function discardUnchanged(repo, at, branch, baseSha, trustFilters = false) {
643
+ if (!unchanged(at, baseSha, trustFilters))
644
+ return false;
645
+ if (removeWorktree(repo, at.worktree, trustFilters) !== null)
646
+ return false;
647
+ git(repo, ["branch", "-D", branch]);
648
+ return true;
649
+ }
650
+ /** Deletes a relay branch if its commits are already contained in the repository's current branch. */
651
+ export function deleteBranchIfMerged(repo, branch) {
652
+ if (!git(repo, ["rev-parse", "-q", "--verify", `refs/heads/${branch}`]).ok)
653
+ return "absent";
654
+ if (!git(repo, ["merge-base", "--is-ancestor", branch, "HEAD"]).ok)
655
+ return "unmerged";
656
+ return git(repo, ["branch", "-D", branch]).ok ? "deleted" : "unmerged";
657
+ }