@defrex/autobuild 1.10.0 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (255) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +745 -69
  3. package/bin/ab-dispatch-generation.ts +3 -1
  4. package/docs/accounts.md +2 -1
  5. package/docs/answering-blocked-builds.md +20 -0
  6. package/docs/architecture.md +165 -29
  7. package/docs/build-store.md +10 -7
  8. package/docs/cli.md +33 -1
  9. package/docs/configuration-overview.md +4 -1
  10. package/docs/configuration.md +381 -29
  11. package/docs/dispatcher.md +64 -4
  12. package/docs/forges.md +7 -0
  13. package/docs/integration-tree.md +2 -2
  14. package/docs/operating.md +4 -2
  15. package/docs/operator-api.md +134 -6
  16. package/docs/operator-surfaces.md +85 -0
  17. package/docs/optimization-nodes.md +69 -11
  18. package/docs/plugin-authoring.md +37 -1
  19. package/docs/remote-store-protocol.md +94 -13
  20. package/docs/remote-ticket-protocol.md +40 -0
  21. package/docs/restacking.md +20 -4
  22. package/docs/setup.md +14 -2
  23. package/docs/ticket-dependencies.md +10 -3
  24. package/docs/ticket-sources.md +24 -2
  25. package/docs/tickets.md +7 -1
  26. package/docs/troubleshooting.md +8 -0
  27. package/docs/verification.md +4 -3
  28. package/docs/workspaces.md +3 -0
  29. package/package.json +9 -5
  30. package/packages/core/src/cli/accounts.ts +7 -2
  31. package/packages/core/src/cli/attention.ts +3 -1
  32. package/packages/core/src/cli/binary-direct.ts +2 -0
  33. package/packages/core/src/cli/binary-lifecycle.ts +2 -1
  34. package/packages/core/src/cli/build-control.ts +79 -1
  35. package/packages/core/src/cli/context.ts +4 -0
  36. package/packages/core/src/cli/dashboard/facts.ts +49 -53
  37. package/packages/core/src/cli/dashboard/header.ts +111 -0
  38. package/packages/core/src/cli/dashboard/model.ts +31 -39
  39. package/packages/core/src/cli/dashboard/objective-row.ts +46 -14
  40. package/packages/core/src/cli/dashboard/poll.ts +179 -76
  41. package/packages/core/src/cli/dashboard/render.ts +159 -230
  42. package/packages/core/src/cli/dashboard/row-text.ts +538 -0
  43. package/packages/core/src/cli/dashboard/timeline.ts +288 -0
  44. package/packages/core/src/cli/dashboard/vocabulary.ts +188 -0
  45. package/packages/core/src/cli/dispatch-args.ts +44 -1
  46. package/packages/core/src/cli/dispatch-frontend.ts +40 -40
  47. package/packages/core/src/cli/dispatch-launch-stop.ts +18 -0
  48. package/packages/core/src/cli/dispatch-launcher.ts +20 -7
  49. package/packages/core/src/cli/dispatch-web.ts +155 -0
  50. package/packages/core/src/cli/dispatch.ts +202 -38
  51. package/packages/core/src/cli/help.ts +87 -3
  52. package/packages/core/src/cli/init-validation.ts +3 -3
  53. package/packages/core/src/cli/main.ts +70 -6
  54. package/packages/core/src/cli/mcp.ts +35 -3
  55. package/packages/core/src/cli/objective.ts +1 -1
  56. package/packages/core/src/cli/operator-preference.ts +57 -0
  57. package/packages/core/src/cli/repo-lease.ts +2 -0
  58. package/packages/core/src/cli/repo-state.ts +56 -6
  59. package/packages/core/src/cli/repository-status.ts +105 -49
  60. package/packages/core/src/cli/status.ts +82 -1
  61. package/packages/core/src/cli/terminal-restore.ts +32 -7
  62. package/packages/core/src/cli/ticket.ts +98 -36
  63. package/packages/core/src/cli/wait.ts +14 -6
  64. package/packages/core/src/cli/watch.ts +20 -4
  65. package/packages/core/src/cli/web.ts +139 -0
  66. package/packages/core/src/config/live.ts +99 -14
  67. package/packages/core/src/config/load.ts +61 -20
  68. package/packages/core/src/config/local.ts +212 -0
  69. package/packages/core/src/config/pipeline-source.ts +2 -0
  70. package/packages/core/src/config/reference.ts +18 -0
  71. package/packages/core/src/config/schema.ts +45 -10
  72. package/packages/core/src/events/catalog.ts +4 -0
  73. package/packages/core/src/events/payloads.ts +97 -0
  74. package/packages/core/src/events/policy.ts +10 -0
  75. package/packages/core/src/events/repository.ts +46 -3
  76. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +381 -30
  77. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/017d8dd5bb6dd80b.json.gz +0 -0
  78. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/178e12f1759b7552.json.gz +0 -0
  79. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4932c70a2af97faf.json.gz +0 -0
  80. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/536085773daf6b58.json.gz +0 -0
  81. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6bd6275061aaffa5.json.gz +0 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/89625654b02e9ac1.json.gz +0 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a98af134be2da8a9.json.gz +0 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d5d5ccca80a893d8.json.gz +0 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f8155387eb5f375c.json.gz +0 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3c27f918b194e3b3.json +465 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/46196d8f0076496a.json +97 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/79f0e0f4ccd43ba2.json +455 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
  92. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
  93. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
  94. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
  95. package/packages/core/src/kernel/build-roster.ts +230 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +4 -2
  97. package/packages/core/src/kernel/dispatch-status.ts +139 -0
  98. package/packages/core/src/kernel/engine.ts +43 -5
  99. package/packages/core/src/kernel/execution-intervals.ts +61 -0
  100. package/packages/core/src/kernel/generators/optimization-log.ts +101 -0
  101. package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
  102. package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
  103. package/packages/core/src/kernel/leaf-restack-state.ts +82 -3
  104. package/packages/core/src/kernel/log-index.ts +19 -0
  105. package/packages/core/src/kernel/optimization-admission.ts +244 -3
  106. package/packages/core/src/kernel/optimization.ts +183 -4
  107. package/packages/core/src/kernel/phase-failures.ts +121 -0
  108. package/packages/core/src/kernel/published-branch-head.ts +60 -0
  109. package/packages/core/src/kernel/read-facts.ts +15 -13
  110. package/packages/core/src/kernel/reducer-registry.ts +27 -8
  111. package/packages/core/src/kernel/reducer-revisions.ts +27 -0
  112. package/packages/core/src/kernel/reducer.ts +63 -4
  113. package/packages/core/src/kernel/rollup.ts +61 -0
  114. package/packages/core/src/kernel/setup-streak.ts +38 -0
  115. package/packages/core/src/kernel/step-durations.ts +257 -0
  116. package/packages/core/src/kernel/target-observation.ts +6 -1
  117. package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
  118. package/packages/core/src/kernel/verify-diff-base.ts +5 -0
  119. package/packages/core/src/kernel/verify-stages.ts +13 -3
  120. package/packages/core/src/ontology.ts +5 -0
  121. package/packages/core/src/operator/agent-context-serve.ts +631 -0
  122. package/packages/core/src/operator/annotations.ts +75 -5
  123. package/packages/core/src/operator/attention.ts +470 -0
  124. package/packages/core/src/operator/canonical-skills.ts +35 -0
  125. package/packages/core/src/operator/cli-equivalents.ts +270 -0
  126. package/packages/core/src/operator/context-prompts.ts +61 -0
  127. package/packages/core/src/operator/index.ts +49 -1
  128. package/packages/core/src/operator/landings.ts +28 -19
  129. package/packages/core/src/operator/optimization.ts +7 -0
  130. package/packages/core/src/operator/protocol.ts +3 -0
  131. package/packages/core/src/operator/query.ts +129 -74
  132. package/packages/core/src/operator/read-view.ts +5 -2
  133. package/packages/core/src/operator/registry.ts +406 -46
  134. package/packages/core/src/operator/requests.ts +20 -18
  135. package/packages/core/src/operator/sandbox-host.ts +107 -11
  136. package/packages/core/src/operator/sandbox-resolver.ts +253 -0
  137. package/packages/core/src/operator/sandbox.ts +778 -82
  138. package/packages/core/src/operator/ticket-asset-list.ts +77 -0
  139. package/packages/core/src/operator/ticket-assets.ts +167 -0
  140. package/packages/core/src/operator/tickets.ts +33 -2
  141. package/packages/core/src/plugin-sdk/index.ts +22 -0
  142. package/packages/core/src/plugins/manifest.ts +1 -1
  143. package/packages/core/src/ports/forge/fake.ts +92 -1
  144. package/packages/core/src/ports/forge/git-blob.ts +15 -0
  145. package/packages/core/src/ports/forge/github.ts +82 -0
  146. package/packages/core/src/ports/forge/local-git.ts +61 -1
  147. package/packages/core/src/ports/forge-failure.ts +24 -0
  148. package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
  149. package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
  150. package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
  151. package/packages/core/src/ports/tickets/contract.ts +71 -0
  152. package/packages/core/src/ports/tickets/fake.ts +11 -0
  153. package/packages/core/src/ports/tickets/file.ts +18 -0
  154. package/packages/core/src/ports/tickets/github-fake.ts +136 -4
  155. package/packages/core/src/ports/tickets/github.ts +387 -30
  156. package/packages/core/src/ports/tickets/hosted-index.ts +10 -0
  157. package/packages/core/src/ports/tickets/linear.ts +130 -0
  158. package/packages/core/src/ports/tickets/priority.ts +9 -0
  159. package/packages/core/src/ports/tickets/remote-protocol.ts +34 -0
  160. package/packages/core/src/ports/tickets/remote.ts +70 -6
  161. package/packages/core/src/ports/tickets/search.ts +139 -0
  162. package/packages/core/src/ports/types.ts +104 -2
  163. package/packages/core/src/ports/workspace/builtin-capabilities.ts +9 -0
  164. package/packages/core/src/ports/workspace/create.ts +15 -1
  165. package/packages/core/src/ports/workspace/fake.ts +340 -12
  166. package/packages/core/src/ports/workspace/git-worktree.ts +833 -42
  167. package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
  168. package/packages/core/src/ports/workspace/process-group.ts +48 -0
  169. package/packages/core/src/ports/workspace/vercel-sandbox.ts +1260 -123
  170. package/packages/core/src/processes/agent-context-assemble.ts +576 -0
  171. package/packages/core/src/processes/agent-context.ts +469 -0
  172. package/packages/core/src/processes/build-runner.ts +387 -236
  173. package/packages/core/src/processes/dispatcher.ts +211 -55
  174. package/packages/core/src/processes/execution-no-progress.ts +4 -0
  175. package/packages/core/src/processes/optimization-activity.ts +120 -0
  176. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  177. package/packages/core/src/processes/repo-view.ts +78 -2
  178. package/packages/core/src/processes/sandbox-state.ts +53 -6
  179. package/packages/core/src/processes/tick-publication.ts +2 -0
  180. package/packages/core/src/processes/workspace-preparation.ts +76 -0
  181. package/packages/core/src/scenarios/harness.ts +0 -5
  182. package/packages/core/src/store/account-redaction.ts +1 -0
  183. package/packages/core/src/store/adapter.ts +52 -1
  184. package/packages/core/src/store/agent-context.ts +432 -0
  185. package/packages/core/src/store/build-feed.ts +291 -0
  186. package/packages/core/src/store/build-scope.ts +19 -1
  187. package/packages/core/src/store/contract.ts +911 -14
  188. package/packages/core/src/store/digest.ts +19 -6
  189. package/packages/core/src/store/histogram.ts +113 -0
  190. package/packages/core/src/store/local/schema.ts +62 -0
  191. package/packages/core/src/store/local/store.ts +628 -22
  192. package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
  193. package/packages/core/src/store/memory.ts +461 -69
  194. package/packages/core/src/store/open-builds.ts +19 -0
  195. package/packages/core/src/store/phase-session.ts +32 -4
  196. package/packages/core/src/store/reduced-reads.ts +14 -4
  197. package/packages/core/src/store/reducer-value-shapes.json +7027 -5751
  198. package/packages/core/src/store/reducer-values.ts +6 -1
  199. package/packages/core/src/store/remote/client.ts +208 -2
  200. package/packages/core/src/store/remote/compatibility.ts +1 -1
  201. package/packages/core/src/store/remote/index.ts +33 -0
  202. package/packages/core/src/store/remote/protocol.ts +69 -0
  203. package/packages/core/src/store/remote/released-clients.json +22 -0
  204. package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
  205. package/packages/core/src/store/remote/released-reducer-values/1.11.1.json +35718 -0
  206. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  207. package/packages/core/src/store/retention.ts +23 -1
  208. package/packages/core/src/store/rollups.ts +337 -0
  209. package/packages/core/src/store/session-handle.ts +20 -2
  210. package/packages/core/src/store/snapshots.ts +10 -0
  211. package/packages/core/src/store/types.ts +108 -9
  212. package/packages/core/src/testing/dispatch-journals.ts +117 -0
  213. package/packages/core/src/testing/dispatch-read-budget.ts +1092 -2
  214. package/packages/core/src/testing/git-config-isolation.ts +7 -5
  215. package/packages/core/src/testing/index.ts +27 -0
  216. package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
  217. package/packages/core/src/testing/reduced-read-budget.ts +1873 -98
  218. package/packages/core/src/web/analytics-source.ts +303 -0
  219. package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
  220. package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
  221. package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
  222. package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
  223. package/packages/core/src/web/assets/app.css +1 -0
  224. package/packages/core/src/web/assets/app.js +9 -0
  225. package/packages/core/src/web/assets/manifest.json +31 -0
  226. package/packages/core/src/web/assets/theme.js +1 -0
  227. package/packages/core/src/web/bounded.ts +31 -0
  228. package/packages/core/src/web/http.ts +315 -0
  229. package/packages/core/src/web/hub.ts +160 -0
  230. package/packages/core/src/web/options.ts +38 -0
  231. package/packages/core/src/web/overview-source.ts +322 -0
  232. package/packages/core/src/web/page.ts +56 -0
  233. package/packages/core/src/web/protocol.ts +151 -0
  234. package/packages/core/src/web/read-only.ts +23 -0
  235. package/packages/core/src/web/repository-source.ts +39 -0
  236. package/packages/core/src/web/server.ts +97 -0
  237. package/skills/code-review/SKILL.md +10 -2
  238. package/skills/guide/SKILL.md +376 -54
  239. package/skills/guide/references/accounts.md +2 -1
  240. package/skills/guide/references/integration-tree.md +2 -2
  241. package/skills/guide/references/operator-api.md +134 -6
  242. package/skills/guide/references/optimization-nodes.md +69 -11
  243. package/skills/guide/references/plugin-authoring.md +37 -1
  244. package/skills/guide/references/remote-store-protocol.md +94 -13
  245. package/skills/guide/references/remote-ticket-protocol.md +40 -0
  246. package/skills/guide/references/restacking.md +20 -4
  247. package/skills/guide/references/setup.md +14 -2
  248. package/skills/guide/references/ticket-dependencies.md +10 -3
  249. package/skills/implement/SKILL.md +23 -4
  250. package/skills/operate/SKILL.md +134 -32
  251. package/skills/plan/SKILL.md +10 -4
  252. package/skills/plan-review/SKILL.md +9 -2
  253. package/skills/spec/SKILL.md +34 -8
  254. package/skills/tickets/SKILL.md +51 -5
  255. package/templates/hosted-service/package.json +2 -2
@@ -8,19 +8,33 @@ import { publishBranch, remoteBranchHead, refreshBranchCache } from '../forge/gi
8
8
  * resume-after-sandbox-death (§15.6-C) a re-run, not a special path
9
9
  * (constitution #2).
10
10
  */
11
- import { mkdir, realpath } from 'node:fs/promises'
11
+ import { lstat, mkdir, realpath, rename } from 'node:fs/promises'
12
12
  import { createHash, randomBytes } from 'node:crypto'
13
- import { readFile as fsReadFile, rm, stat, writeFile as fsWriteFile } from 'node:fs/promises'
14
- import { join, resolve, sep } from 'node:path'
13
+ import {
14
+ readdir,
15
+ readFile as fsReadFile,
16
+ rm,
17
+ stat,
18
+ writeFile as fsWriteFile,
19
+ } from 'node:fs/promises'
20
+ import { basename, dirname, join, resolve, sep } from 'node:path'
15
21
  import type { WorkspaceBase } from '../../ontology'
16
22
  import {
23
+ redactSandboxMessage,
24
+ SANDBOX_INTERRUPTED_MESSAGE,
25
+ SANDBOX_REFRESH_DIRTY_MESSAGE,
26
+ sandboxRefreshDivergedMessage,
17
27
  SandboxOperationError,
18
28
  type OperatorSandboxExecution,
19
29
  type SandboxCommandRequest,
20
30
  type SandboxCommandResult,
21
31
  type SandboxEnvironmentIdentity,
32
+ type SandboxProviderStatus,
33
+ type SandboxProvisionStage,
34
+ type SandboxRefreshResult,
22
35
  type SandboxWaitResult,
23
36
  } from './operator-sandbox'
37
+ import { groupAlive, terminateProcessGroup } from './process-group'
24
38
  import type {
25
39
  WorkspaceHandle,
26
40
  WorkspaceProvider,
@@ -37,13 +51,20 @@ export interface ExecResult {
37
51
  /** Injectable exec seam — the default shells out via Bun.spawn. */
38
52
  export type Exec = (
39
53
  cmd: string[],
40
- opts: { cwd?: string; signal?: AbortSignal; env?: Record<string, string | undefined> },
54
+ opts: {
55
+ cwd?: string
56
+ signal?: AbortSignal
57
+ env?: Record<string, string | undefined>
58
+ /** Bytes written to the child's stdin; omitted means no stdin at all.
59
+ * Wrappers that delegate must forward it (spread the opts). */
60
+ stdin?: string
61
+ },
41
62
  ) => Promise<ExecResult>
42
63
 
43
64
  export const spawnExec: Exec = async (cmd, opts) => {
44
65
  const proc = Bun.spawn(cmd, {
45
66
  cwd: opts.cwd,
46
- stdin: 'ignore',
67
+ stdin: opts.stdin === undefined ? 'ignore' : new Blob([opts.stdin]),
47
68
  stdout: 'pipe',
48
69
  stderr: 'pipe',
49
70
  env: {
@@ -76,6 +97,82 @@ export class GitError extends Error {
76
97
  }
77
98
  }
78
99
 
100
+ /**
101
+ * No build worktree destination is isolated from the checkout's packages:
102
+ * the chosen root resolves inside the checkout, or a directory from the root
103
+ * up to `/` holds a `node_modules` entry that Node and Bun resolution would
104
+ * walk into. The message names the offending path and the remedy.
105
+ */
106
+ export class WorktreeIsolationError extends Error {
107
+ constructor(
108
+ /** The chosen build worktree root, as configured. */
109
+ readonly root: string,
110
+ /** The canonical checkout the provider provisions from. */
111
+ readonly checkout: string,
112
+ /** The canonical directory holding `node_modules`, when that is the fault. */
113
+ readonly ancestor?: string,
114
+ ) {
115
+ super(
116
+ (ancestor !== undefined
117
+ ? `build worktree root ${root} is not isolated: ${join(ancestor, 'node_modules')} lies above it, so package resolution in a worktree would reach packages the build does not own`
118
+ : `build worktree root ${root} resolves inside the checkout ${checkout}, so package resolution in a worktree would reach the checkout's node_modules`) +
119
+ `; set XDG_STATE_HOME to an absolute directory outside ${checkout} with no node_modules above it, or select a local store outside the checkout`,
120
+ )
121
+ this.name = 'WorktreeIsolationError'
122
+ }
123
+ }
124
+
125
+ /** A startup notice for a host where new build worktrees cannot be
126
+ * provisioned, or `undefined` when the destination is isolated. Never a gate:
127
+ * builds already in a worktree keep running and release. Errors other than
128
+ * `WorktreeIsolationError` are genuine IO faults and propagate. */
129
+ export async function worktreeIsolationNotice(
130
+ provider: GitWorktreeProvider,
131
+ checkout: string,
132
+ ): Promise<string | undefined> {
133
+ try {
134
+ await provider.assertIsolatedRoot(checkout)
135
+ return undefined
136
+ } catch (error) {
137
+ if (!(error instanceof WorktreeIsolationError)) throw error
138
+ return `new build worktrees cannot be provisioned: ${error.message}; builds already in a worktree continue`
139
+ }
140
+ }
141
+
142
+ function isInside(path: string, dir: string): boolean {
143
+ return path === dir || path.startsWith(dir.endsWith(sep) ? dir : dir + sep)
144
+ }
145
+
146
+ function missing(error: unknown): boolean {
147
+ const code = (error as NodeJS.ErrnoException).code
148
+ return code === 'ENOENT' || code === 'ENOTDIR'
149
+ }
150
+
151
+ /** The realpath of the nearest existing ancestor joined with the remaining
152
+ * segments: a canonical answer for a path that may not exist yet, without
153
+ * creating anything. */
154
+ async function canonicalize(path: string): Promise<string> {
155
+ const absolute = resolve(path)
156
+ const rest: string[] = []
157
+ for (let current = absolute; ; current = dirname(current)) {
158
+ try {
159
+ return join(await realpath(current), ...rest)
160
+ } catch (error) {
161
+ if (!missing(error)) throw error
162
+ }
163
+ if (dirname(current) === current) return absolute
164
+ rest.unshift(basename(current))
165
+ }
166
+ }
167
+
168
+ /** Where a provisioning repository's build worktrees go. `legacy` is the
169
+ * in-checkout state-tree root that existing registrations are adopted from. */
170
+ interface WorktreeLayout {
171
+ checkoutReal: string
172
+ chosen: string
173
+ legacy?: string
174
+ }
175
+
79
176
  /** `ab/build-123` → `ab-build-123` — one subdir per branch under the root. */
80
177
  function sanitizeBranch(branch: string): string {
81
178
  const cleaned = branch.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[.-]+/, '')
@@ -90,14 +187,41 @@ interface WorktreeEntry {
90
187
  }
91
188
 
92
189
  interface WorktreeSelection {
93
- /** Requested branch attached inside this provider's root. */
190
+ /** Requested branch attached inside the chosen or legacy root. */
94
191
  attached?: WorktreeEntry
95
192
  /** Detached registration at the requested branch's deterministic path. */
96
193
  detached?: WorktreeEntry
97
194
  /** The requested branch is attached anywhere, including outside our root. */
98
195
  branchAttached: boolean
196
+ /** Every registration attached to the requested branch anywhere, plus a
197
+ * detached registration at one of its deterministic paths. */
198
+ holders: WorktreeEntry[]
99
199
  }
100
200
 
201
+ /** Foreign registrations set aside at first provision live under
202
+ * `<chosen root>/.displaced/<leaf>/<head>`. */
203
+ const DISPLACED_DIR = '.displaced'
204
+ /** The lock reason, and the admin-directory record, of a relocation in flight. */
205
+ const DISPLACEMENT_LOCK = 'autobuild: relocating a displaced worktree'
206
+ const RELOCATION_RECORD = 'autobuild-relocation'
207
+
208
+ async function readOptional(path: string): Promise<string | undefined> {
209
+ try {
210
+ return await fsReadFile(path, 'utf8')
211
+ } catch (error) {
212
+ if (missing(error)) return undefined
213
+ throw error
214
+ }
215
+ }
216
+
217
+ /** Where fresh-provision creation receipts for `branch` live. */
218
+ function receiptPrefix(branch: string): string {
219
+ return `refs/autobuild/provision/${branch}/created`
220
+ }
221
+
222
+ /** Owner tokens are opaque, ref-safe and bounded. */
223
+ const OWNER_PATTERN = /^[A-Za-z0-9_-]{1,64}$/
224
+
101
225
  function parseWorktreeList(porcelain: string): WorktreeEntry[] {
102
226
  const entries: WorktreeEntry[] = []
103
227
  for (const block of porcelain.split('\n\n')) {
@@ -117,26 +241,50 @@ function parseWorktreeList(porcelain: string): WorktreeEntry[] {
117
241
  return entries
118
242
  }
119
243
 
244
+ /** The provisioning marker written into a finished operator sandbox. */
245
+ const SANDBOX_MARKER = '.autobuild-sandbox-provisioned'
246
+ const SHA_PATTERN = /^[0-9a-f]{40,64}$/i
247
+
248
+ /** A provision attempt stopped by `close` or `release`; not a failure. */
249
+ class SandboxCancelledError extends Error {
250
+ override readonly name = 'SandboxCancelledError'
251
+ constructor() {
252
+ super('operator sandbox provisioning was cancelled')
253
+ }
254
+ }
255
+
120
256
  export class GitWorktreeProvider implements WorkspaceProvider {
121
257
  readonly name = 'git-worktree'
122
258
  readonly orchestratorSandbox: OperatorSandboxExecution
123
259
  readonly sandboxPublication: WorkspacePublication
124
260
  private readonly root: string
261
+ private readonly isolatedRoot: string | undefined
125
262
  private readonly sandboxRoot: string
126
263
  private readonly setupCommand: string | undefined
127
264
  private readonly sandboxEnvironmentVariables: readonly string[]
128
265
  private readonly sandboxEnvSource: Record<string, string | undefined>
129
- /** Canonicalized (symlink-free) root, resolved lazily — git reports
130
- * worktree paths canonicalized, so comparisons must be too. */
131
- private rootReal: string | null = null
266
+ /** Placement per canonical provisioning repository. Paths are compared
267
+ * canonicalized (symlink-free) because git reports worktree paths that way;
268
+ * the isolation check itself is never cached. */
269
+ private readonly layouts = new Map<string, WorktreeLayout>()
132
270
  private readonly exec: Exec
133
271
  /** worktree path → repo it was provisioned from, so `release` can find the
134
272
  * repo without re-deriving it. Rebuilt lazily after a restart (release of a
135
273
  * still-on-disk worktree rediscovers the repo via git-common-dir). */
136
274
  private readonly repos = new Map<string, string>()
137
275
 
276
+ /**
277
+ * `root` is the state tree's own worktree directory. When it resolves
278
+ * inside the provisioning checkout and `isolatedRoot` is set, build
279
+ * worktrees go to `isolatedRoot` and `root` becomes the legacy root whose
280
+ * existing registrations are still adopted in place. Either way the chosen
281
+ * root is validated before any worktree is created or reused there.
282
+ */
138
283
  constructor(opts: {
139
284
  root: string
285
+ /** Build worktree root outside the checkout's package ancestry, used
286
+ * when `root` resolves inside the checkout. */
287
+ isolatedRoot?: string
140
288
  exec?: Exec
141
289
  /** Test-only override of the exit-stamp drain grace
142
290
  * (`DEFAULT_SANDBOX_EXIT_DRAIN_GRACE_MS`); production behavior is
@@ -155,6 +303,7 @@ export class GitWorktreeProvider implements WorkspaceProvider {
155
303
  envSource?: Record<string, string | undefined>
156
304
  }) {
157
305
  this.root = resolve(opts.root)
306
+ this.isolatedRoot = opts.isolatedRoot === undefined ? undefined : resolve(opts.isolatedRoot)
158
307
  this.sandboxRoot = resolve(opts.sandboxRoot ?? join(opts.root, '..', 'orchestrator-sandboxes'))
159
308
  this.setupCommand = opts.setupCommand
160
309
  this.sandboxEnvironmentVariables = opts.sandboxEnvironmentVariables ?? []
@@ -163,6 +312,11 @@ export class GitWorktreeProvider implements WorkspaceProvider {
163
312
  opts.exitDrainGraceMs ?? GitWorktreeProvider.DEFAULT_SANDBOX_EXIT_DRAIN_GRACE_MS
164
313
  this.exec = opts.exec ?? spawnExec
165
314
  this.orchestratorSandbox = {
315
+ lifecycleSupported: true,
316
+ open: (input) => this.openSandbox(input),
317
+ status: (input) => this.sandboxStatus(input),
318
+ close: (input) => this.closeSandbox(input),
319
+ refresh: (handle, input) => this.refreshSandbox(handle, input),
166
320
  describe: (input) => Promise.resolve(this.sandboxIdentity(input.repo, input.operator)),
167
321
  ensure: (input) => this.ensureSandbox(input),
168
322
  exec: (handle, request) => this.sandboxExec(handle, request),
@@ -179,12 +333,45 @@ export class GitWorktreeProvider implements WorkspaceProvider {
179
333
  }
180
334
  }
181
335
 
182
- private async realRoot(): Promise<string> {
183
- if (!this.rootReal) {
184
- await mkdir(this.root, { recursive: true })
185
- this.rootReal = await realpath(this.root)
336
+ private async layout(repo: string): Promise<WorktreeLayout> {
337
+ const checkoutReal = await realpath(repo)
338
+ const cached = this.layouts.get(checkoutReal)
339
+ if (cached) return cached
340
+ const root = await canonicalize(this.root)
341
+ const layout: WorktreeLayout =
342
+ this.isolatedRoot !== undefined && isInside(root, checkoutReal)
343
+ ? { checkoutReal, chosen: this.isolatedRoot, legacy: root }
344
+ : { checkoutReal, chosen: this.root }
345
+ this.layouts.set(checkoutReal, layout)
346
+ return layout
347
+ }
348
+
349
+ /**
350
+ * Validate the build worktree root chosen for `repo` and return its real
351
+ * path, creating it. Throws `WorktreeIsolationError` when it resolves
352
+ * inside the checkout or any directory from it up to `/` holds a
353
+ * `node_modules` entry; a worktree's own `node_modules` lies below the root,
354
+ * so the build owns it. Not cached: a `node_modules` that appears later is
355
+ * noticed on the next provision.
356
+ */
357
+ async assertIsolatedRoot(repo: string): Promise<string> {
358
+ const { checkoutReal, chosen } = await this.layout(repo)
359
+ const canonical = await canonicalize(chosen)
360
+ if (isInside(canonical, checkoutReal)) throw new WorktreeIsolationError(chosen, checkoutReal)
361
+ for (let dir = canonical; ; dir = dirname(dir)) {
362
+ try {
363
+ await lstat(join(dir, 'node_modules'))
364
+ throw new WorktreeIsolationError(chosen, checkoutReal, dir)
365
+ } catch (error) {
366
+ if (error instanceof WorktreeIsolationError || !missing(error)) throw error
367
+ }
368
+ if (dirname(dir) === dir) break
186
369
  }
187
- return this.rootReal
370
+ await mkdir(chosen, { recursive: true })
371
+ const real = await realpath(chosen)
372
+ // A symlink created between the check and mkdir must not slip through.
373
+ if (isInside(real, checkoutReal)) throw new WorktreeIsolationError(chosen, checkoutReal)
374
+ return real
188
375
  }
189
376
 
190
377
  /** Runs git against `dir` via `-C` so a nonexistent dir surfaces as git's
@@ -199,6 +386,31 @@ export class GitWorktreeProvider implements WorkspaceProvider {
199
386
  return result
200
387
  }
201
388
 
389
+ /** `git` with `input` on stdin; used only by the creation transactions. */
390
+ private async gitWithInput(dir: string, args: string[], input: string): Promise<ExecResult> {
391
+ return this.exec(['git', '-C', dir, ...args], { stdin: input })
392
+ }
393
+
394
+ private async gitWithInputOrThrow(
395
+ dir: string,
396
+ args: string[],
397
+ input: string,
398
+ ): Promise<ExecResult> {
399
+ const result = await this.gitWithInput(dir, args, input)
400
+ if (result.exitCode !== 0) throw new GitError(['-C', dir, ...args], result)
401
+ return result
402
+ }
403
+
404
+ /** True only for a local `refs/heads/<branch>` in `repo`; throws when the
405
+ * probe itself fails. Claim-time slug deduplication (#1261). */
406
+ async localBranchExists(repo: string, branch: string): Promise<boolean> {
407
+ const args = ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]
408
+ const result = await this.git(repo, args)
409
+ if (result.exitCode === 0) return true
410
+ if (result.exitCode === 1) return false
411
+ throw new GitError(['-C', repo, ...args], result)
412
+ }
413
+
202
414
  private shaFrom(dir: string, args: string[], result: ExecResult): string {
203
415
  if (result.exitCode !== 0) {
204
416
  throw new GitError(['-C', dir, ...args], result)
@@ -358,17 +570,48 @@ export class GitWorktreeProvider implements WorkspaceProvider {
358
570
  baseBranch: string
359
571
  branch: string
360
572
  publication?: { sha: string; cacheHeads: string[] }
573
+ fresh?: { owner: string }
361
574
  }): Promise<WorkspaceProvisionResult> {
362
575
  const { repo, baseBranch, branch } = opts
363
576
  // Fails with git's stderr for a missing path or a non-repo directory.
364
577
  await this.gitOrThrow(repo, ['rev-parse', '--git-dir'])
578
+ const layout = await this.layout(repo)
579
+ const leaf = sanitizeBranch(branch)
580
+ const chosenDir = await canonicalize(layout.chosen)
581
+ // Finish an interrupted rename-based displacement before pruning, so its
582
+ // registration (index, merge state) is never mistaken for a deleted one.
583
+ await this.recoverDisplaced(repo, join(chosenDir, DISPLACED_DIR, leaf))
365
584
  // Drop registrations whose directories were deleted out-of-band, so
366
585
  // re-provision after a hand-cleaned sandbox still succeeds.
367
586
  await this.gitOrThrow(repo, ['worktree', 'prune'])
368
-
369
- const rootDir = await this.realRoot()
370
- const worktreePath = join(rootDir, sanitizeBranch(branch))
371
- const worktrees = await this.findWorktrees(repo, branch, rootDir, worktreePath)
587
+ let worktreePath = join(chosenDir, leaf)
588
+ const roots = layout.legacy !== undefined ? [chosenDir, layout.legacy] : [chosenDir]
589
+ const worktrees = await this.findWorktrees(
590
+ repo,
591
+ branch,
592
+ roots,
593
+ roots.map((root) => join(root, leaf)),
594
+ )
595
+ if (opts.fresh) {
596
+ return this.provisionFresh({
597
+ repo,
598
+ baseBranch,
599
+ branch,
600
+ owner: opts.fresh.owner,
601
+ leaf,
602
+ chosenDir,
603
+ roots,
604
+ holders: worktrees.holders,
605
+ })
606
+ }
607
+ // A registration that already exists at the legacy in-checkout root is
608
+ // adopted in place without the isolation check, so builds provisioned
609
+ // before worktrees moved resume, clean up and release. Nothing new is
610
+ // ever created there.
611
+ const legacy = layout.legacy
612
+ const adopted = worktrees.attached ?? worktrees.detached
613
+ const exempt = legacy !== undefined && adopted?.path.startsWith(legacy + sep) === true
614
+ if (!exempt) worktreePath = join(await this.assertIsolatedRoot(repo), leaf)
372
615
  if (worktrees.attached) {
373
616
  // Idempotent provision (constitution #2): the registered worktree — at
374
617
  // the branch's current tip — is the resume point, not a fresh checkout.
@@ -510,17 +753,270 @@ export class GitWorktreeProvider implements WorkspaceProvider {
510
753
  }
511
754
  await this.gitOrThrow(repo, ['worktree', 'prune'])
512
755
  this.repos.delete(path)
756
+ // Every later provision of a released build is non-fresh, so its creation
757
+ // receipts are spent. Best effort: a leftover receipt only pins a commit.
758
+ if (handle.branch) {
759
+ const listed = await this.git(repo, [
760
+ 'for-each-ref',
761
+ '--format=%(refname)',
762
+ `${receiptPrefix(handle.branch)}/`,
763
+ ])
764
+ if (listed.exitCode === 0) {
765
+ for (const ref of listed.stdout.split('\n').filter((line) => line !== '')) {
766
+ await this.git(repo, ['update-ref', '-d', ref])
767
+ }
768
+ }
769
+ }
770
+ }
771
+
772
+ /** This owner's creation receipt for `branch`, when one exists. */
773
+ private async ownCreation(
774
+ repo: string,
775
+ branch: string,
776
+ owner: string,
777
+ ): Promise<string | undefined> {
778
+ if (!OWNER_PATTERN.test(owner)) {
779
+ throw new Error(`invalid fresh-provision owner ${JSON.stringify(owner)}`)
780
+ }
781
+ return (
782
+ (await this.resolveOptionalCommit(repo, `${receiptPrefix(branch)}/${owner}`)) ?? undefined
783
+ )
784
+ }
785
+
786
+ /**
787
+ * A build's first provision (#1261). A pre-existing branch of this name is
788
+ * not the build's work: on 2026-11-25 a new build adopted a months-old
789
+ * merged branch's local ref as its base and parked forever on
790
+ * `target-rewritten`. Ownership is proven only by this owner's creation
791
+ * receipt, which is written in one atomic ref transaction with the build's
792
+ * own branch write, after every foreign holder is set aside. Ancestry is
793
+ * never consulted. Foreign holders are detached in place (and moved under
794
+ * `.displaced/` when they occupy a provider path), never destroyed; a
795
+ * foreign tip is kept under `refs/autobuild/displaced/<branch>/<sha>`.
796
+ */
797
+ private async provisionFresh(input: {
798
+ repo: string
799
+ baseBranch: string
800
+ branch: string
801
+ owner: string
802
+ leaf: string
803
+ chosenDir: string
804
+ roots: string[]
805
+ holders: WorktreeEntry[]
806
+ }): Promise<WorkspaceProvisionResult> {
807
+ const { repo, baseBranch, branch, owner, leaf, chosenDir, roots } = input
808
+ const branchRef = `refs/heads/${branch}`
809
+ const receiptRef = `${receiptPrefix(branch)}/${owner}`
810
+ const leafPaths = roots.map((root) => join(root, leaf))
811
+ const ownPath = join(chosenDir, leaf)
812
+ const tip = (await this.resolveOptionalCommit(repo, branchRef)) ?? undefined
813
+ const receipt = await this.ownCreation(repo, branch, owner)
814
+ let holders = input.holders
815
+
816
+ // This owner's interrupted creation: adopt it, so a lost
817
+ // `workspace.provisioned` append re-runs as a no-op.
818
+ if (
819
+ tip !== undefined &&
820
+ receipt === tip &&
821
+ holders.every((holder) => holder.branch === branch && holder.path === ownPath)
822
+ ) {
823
+ const attached = holders[0]
824
+ let path = attached?.path
825
+ if (path === undefined) {
826
+ path = join(await this.assertIsolatedRoot(repo), leaf)
827
+ await this.gitOrThrow(repo, ['worktree', 'add', path, branch])
828
+ const head = await this.resolveCommit(path, 'HEAD')
829
+ if (head !== tip) {
830
+ throw new Error(`checked out ${path} at ${head}, expected own creation ${tip}`)
831
+ }
832
+ }
833
+ this.repos.set(path, repo)
834
+ return {
835
+ provider: this.name,
836
+ ref: path,
837
+ path,
838
+ localPath: path,
839
+ branch,
840
+ base: { source: 'existing', sha: tip },
841
+ }
842
+ }
843
+
844
+ // Set every foreign holder aside before any ref moves. Nothing is written
845
+ // yet, so an interrupted attempt leaves no receipt and simply repeats.
846
+ for (const holder of holders) {
847
+ let head = holder.head ?? tip
848
+ if (holder.branch === branch) {
849
+ if (tip === undefined) {
850
+ throw new Error(`worktree ${holder.path} holds ${branchRef}, which does not resolve`)
851
+ }
852
+ await this.gitOrThrow(holder.path, ['update-ref', '--no-deref', 'HEAD', tip])
853
+ const symbolic = await this.git(holder.path, ['symbolic-ref', '-q', 'HEAD'])
854
+ const detachedHead = await this.resolveCommit(holder.path, 'HEAD')
855
+ if (symbolic.exitCode === 0 || detachedHead !== tip) {
856
+ throw new Error(`could not detach worktree ${holder.path} from ${branchRef} at ${tip}`)
857
+ }
858
+ head = tip
859
+ }
860
+ if (leafPaths.includes(holder.path)) {
861
+ await this.moveAside(
862
+ repo,
863
+ holder.path,
864
+ join(chosenDir, DISPLACED_DIR, leaf, head ?? 'unknown'),
865
+ )
866
+ }
867
+ }
868
+ holders = (await this.findWorktrees(repo, branch, roots, leafPaths)).holders
869
+ if (holders.length > 0) {
870
+ throw new Error(
871
+ `${branchRef} is still held by ${holders.map((holder) => holder.path).join(', ')} after displacement`,
872
+ )
873
+ }
874
+
875
+ const worktreePath = join(await this.assertIsolatedRoot(repo), leaf)
876
+ const base = await this.selectNewBranchBase(repo, baseBranch, branch)
877
+ const archiveRef =
878
+ tip !== undefined && tip !== base.sha
879
+ ? `refs/autobuild/displaced/${branch}/${tip}`
880
+ : undefined
881
+ const transaction = [
882
+ 'start',
883
+ tip === undefined
884
+ ? `create ${branchRef} ${base.sha}`
885
+ : `update ${branchRef} ${base.sha} ${tip}`,
886
+ ...(archiveRef !== undefined ? [`update ${archiveRef} ${tip}`] : []),
887
+ `update ${receiptRef} ${base.sha}`,
888
+ 'prepare',
889
+ 'commit',
890
+ '',
891
+ ].join('\n')
892
+ await this.gitWithInputOrThrow(repo, ['update-ref', '--stdin'], transaction)
893
+ // A seam that dropped stdin would let git commit an empty transaction
894
+ // and exit 0; read every ref back so that fails loudly.
895
+ const expected: Array<[string, string]> = [
896
+ [branchRef, base.sha],
897
+ [receiptRef, base.sha],
898
+ ...(archiveRef !== undefined ? [[archiveRef, tip!] as [string, string]] : []),
899
+ ]
900
+ for (const [ref, sha] of expected) {
901
+ const actual = await this.resolveOptionalCommit(repo, ref)
902
+ if (actual !== sha) {
903
+ throw new Error(`ref transaction left ${ref} at ${actual ?? '(missing)'}, expected ${sha}`)
904
+ }
905
+ }
906
+
907
+ await this.gitOrThrow(repo, ['worktree', 'add', worktreePath, branch])
908
+ const actualSha = await this.resolveCommit(repo, branchRef)
909
+ if (actualSha !== base.sha) {
910
+ throw new Error(`created ${branchRef} at ${actualSha}, expected selected base ${base.sha}`)
911
+ }
912
+ const head = await this.resolveCommit(worktreePath, 'HEAD')
913
+ if (head !== base.sha) {
914
+ throw new Error(`checked out ${worktreePath} at ${head}, expected selected base ${base.sha}`)
915
+ }
916
+ this.repos.set(worktreePath, repo)
917
+ return {
918
+ provider: this.name,
919
+ ref: worktreePath,
920
+ path: worktreePath,
921
+ localPath: worktreePath,
922
+ branch,
923
+ base: { ...base, sha: actualSha },
924
+ }
925
+ }
926
+
927
+ /** Move a foreign registration off a provider-derived path, keeping every
928
+ * file and its lock. Git refuses `worktree move` with submodules; a
929
+ * same-filesystem rename plus `worktree repair` keeps the files then. */
930
+ private async moveAside(repo: string, from: string, preferred: string): Promise<void> {
931
+ let dest = preferred
932
+ for (
933
+ let n = 2;
934
+ await lstat(dest).then(
935
+ () => true,
936
+ () => false,
937
+ );
938
+ n += 1
939
+ ) {
940
+ dest = `${preferred}-${n}`
941
+ }
942
+ await mkdir(dirname(dest), { recursive: true })
943
+ const moved = await this.git(repo, ['worktree', 'move', '--force', '--force', from, dest])
944
+ if (moved.exitCode === 0) {
945
+ // An earlier interrupted fallback may have left its lock and record.
946
+ await this.recoverDisplaced(repo, dirname(dest))
947
+ return
948
+ }
949
+ if (!/submodule/i.test(moved.stderr)) {
950
+ throw new GitError(['-C', repo, 'worktree', 'move', '--force', '--force', from, dest], moved)
951
+ }
952
+ // A rename and the repair that follows are two steps. Until the repair
953
+ // lands, the registration points at a missing path and any `worktree
954
+ // prune` (this provider's or another build's) would delete its admin
955
+ // directory, index and merge state. Lock it and leave a relocation record
956
+ // first; `recoverDisplaced` finishes an interrupted relocation.
957
+ const admin = (await this.gitOrThrow(from, ['rev-parse', '--absolute-git-dir'])).stdout.trim()
958
+ const lock = await readOptional(join(admin, 'locked'))
959
+ const ownLock = lock === undefined || lock.trim() === DISPLACEMENT_LOCK
960
+ if (lock === undefined) {
961
+ await this.gitOrThrow(repo, ['worktree', 'lock', '--reason', DISPLACEMENT_LOCK, from])
962
+ }
963
+ await fsWriteFile(join(admin, RELOCATION_RECORD), JSON.stringify({ dest, unlock: ownLock }))
964
+ await rename(from, dest)
965
+ await this.finishRelocation(repo, dest, admin, ownLock)
966
+ }
967
+
968
+ /** Repair the moved registration, drop this provider's lock, then the record. */
969
+ private async finishRelocation(
970
+ repo: string,
971
+ dest: string,
972
+ admin: string,
973
+ unlock: boolean,
974
+ ): Promise<void> {
975
+ await this.gitOrThrow(repo, ['worktree', 'repair', dest])
976
+ if (unlock && (await readOptional(join(admin, 'locked')))?.trim() === DISPLACEMENT_LOCK) {
977
+ await this.gitOrThrow(repo, ['worktree', 'unlock', dest])
978
+ }
979
+ await rm(join(admin, RELOCATION_RECORD), { force: true })
980
+ }
981
+
982
+ /** Finish every relocation under `dir` that `moveAside` started and did not
983
+ * complete: only a copy whose admin directory still holds a record naming
984
+ * exactly that copy is repaired. */
985
+ private async recoverDisplaced(repo: string, dir: string): Promise<void> {
986
+ let names: string[]
987
+ try {
988
+ names = await readdir(dir)
989
+ } catch (error) {
990
+ if (missing(error)) return
991
+ throw error
992
+ }
993
+ for (const name of names) {
994
+ const path = join(dir, name)
995
+ const link = await readOptional(join(path, '.git'))
996
+ const admin = link?.match(/^gitdir: (.+)$/m)?.[1]?.trim()
997
+ if (admin === undefined) continue
998
+ const raw = await readOptional(join(admin, RELOCATION_RECORD))
999
+ if (raw === undefined) continue
1000
+ let record: { dest?: unknown; unlock?: unknown }
1001
+ try {
1002
+ record = JSON.parse(raw) as typeof record
1003
+ } catch {
1004
+ continue
1005
+ }
1006
+ if (record.dest !== path) continue
1007
+ await this.finishRelocation(repo, path, admin, record.unlock === true)
1008
+ }
513
1009
  }
514
1010
 
515
1011
  /** Discover only registrations relevant to the requested branch. Attached
516
- * reuse stays root-scoped (and therefore excludes the main checkout); a
517
- * detached registration is recoverable only at this branch's exact,
518
- * deterministic provider-owned path. */
1012
+ * reuse stays scoped to the chosen and legacy roots (and therefore excludes
1013
+ * the main checkout); a detached registration is recoverable only at this
1014
+ * branch's exact, deterministic provider-owned path under either root. */
519
1015
  private async findWorktrees(
520
1016
  repo: string,
521
1017
  branch: string,
522
- rootDir: string,
523
- worktreePath: string,
1018
+ rootDirs: readonly string[],
1019
+ worktreePaths: readonly string[],
524
1020
  ): Promise<WorktreeSelection> {
525
1021
  const list = await this.gitOrThrow(repo, ['worktree', 'list', '--porcelain'])
526
1022
  const entries = parseWorktreeList(list.stdout).map((entry) => ({
@@ -529,10 +1025,17 @@ export class GitWorktreeProvider implements WorkspaceProvider {
529
1025
  }))
530
1026
  return {
531
1027
  attached: entries.find(
532
- (entry) => entry.branch === branch && entry.path.startsWith(rootDir + sep),
1028
+ (entry) =>
1029
+ entry.branch === branch && rootDirs.some((root) => entry.path.startsWith(root + sep)),
533
1030
  ),
534
- detached: entries.find((entry) => entry.detached && entry.path === worktreePath),
1031
+ detached: worktreePaths
1032
+ .map((path) => entries.find((entry) => entry.detached && entry.path === path))
1033
+ .find((entry) => entry !== undefined),
535
1034
  branchAttached: entries.some((entry) => entry.branch === branch),
1035
+ holders: entries.filter(
1036
+ (entry) =>
1037
+ entry.branch === branch || (entry.detached && worktreePaths.includes(entry.path)),
1038
+ ),
536
1039
  }
537
1040
  }
538
1041
 
@@ -607,12 +1110,22 @@ export class GitWorktreeProvider implements WorkspaceProvider {
607
1110
  return parseWorktreeList(list.stdout).some((entry) => resolve(entry.path) === resolve(path))
608
1111
  }
609
1112
 
610
- private async ensureSandbox(input: {
611
- repo: string
612
- operator: string
613
- baseBranch: string
614
- }): Promise<SandboxEnvironmentIdentity> {
1113
+ /** Blocking provision primitive. `onStage` reports `checkout` before the
1114
+ * base is resolved and the worktree added, and `setup` before the setup
1115
+ * command; `signal` cancels between steps and kills a running setup, and a
1116
+ * cancelled attempt removes its half worktree and throws
1117
+ * `SandboxCancelledError`. The marker records the selected base head as
1118
+ * JSON `{"baseSha":"<sha>"}` so a later process can recover it. */
1119
+ private async ensureSandbox(
1120
+ input: {
1121
+ repo: string
1122
+ operator: string
1123
+ baseBranch: string
1124
+ },
1125
+ control: { onStage?: (stage: SandboxProvisionStage) => void; signal?: AbortSignal } = {},
1126
+ ): Promise<SandboxEnvironmentIdentity> {
615
1127
  const identity = this.sandboxIdentity(input.repo, input.operator)
1128
+ const { signal } = control
616
1129
  if (await this.isRegisteredWorktree(identity.environmentId, input.repo)) {
617
1130
  // Pre-existing sandboxes provisioned before the info/exclude write
618
1131
  // landed (AUT-580) keep an unexcluded marker; write the exclusion on
@@ -622,8 +1135,11 @@ export class GitWorktreeProvider implements WorkspaceProvider {
622
1135
  await this.excludeProvisioningMarker(identity.workspacePath)
623
1136
  return identity
624
1137
  }
1138
+ control.onStage?.('checkout')
1139
+ if (signal?.aborted) throw new SandboxCancelledError()
625
1140
  await mkdir(this.sandboxRoot, { recursive: true })
626
1141
  const baseHead = await this.resolveCommit(input.repo, `refs/heads/${input.baseBranch}`)
1142
+ if (signal?.aborted) throw new SandboxCancelledError()
627
1143
  await this.gitOrThrow(input.repo, [
628
1144
  'worktree',
629
1145
  'add',
@@ -632,18 +1148,27 @@ export class GitWorktreeProvider implements WorkspaceProvider {
632
1148
  baseHead,
633
1149
  ])
634
1150
  try {
1151
+ if (signal?.aborted) throw new SandboxCancelledError()
635
1152
  await this.excludeProvisioningMarker(identity.workspacePath)
636
- const marker = join(identity.workspacePath, '.autobuild-sandbox-provisioned')
1153
+ const marker = join(identity.workspacePath, SANDBOX_MARKER)
637
1154
  const provisioned = await stat(marker).then(
638
1155
  () => true,
639
1156
  () => false,
640
1157
  )
641
1158
  if (!provisioned && this.setupCommand !== undefined && this.setupCommand.trim() !== '') {
1159
+ control.onStage?.('setup')
1160
+ if (signal?.aborted) throw new SandboxCancelledError()
642
1161
  // The setup command runs with the same credential-free guest
643
1162
  // environment as every tool exec — never the host environment
644
1163
  // wholesale, or a setup script would be a second route to build
645
1164
  // state. Unbounded: provisioning may install for a long time.
646
- const result = await this.spawnSandboxCommand(this.setupCommand, identity.workspacePath)
1165
+ const result = await this.spawnSandboxCommand(
1166
+ this.setupCommand,
1167
+ identity.workspacePath,
1168
+ undefined,
1169
+ signal,
1170
+ )
1171
+ if (signal?.aborted) throw new SandboxCancelledError()
647
1172
  if (result.exitCode !== 0) {
648
1173
  throw new SandboxOperationError(
649
1174
  'provision',
@@ -651,16 +1176,250 @@ export class GitWorktreeProvider implements WorkspaceProvider {
651
1176
  )
652
1177
  }
653
1178
  }
654
- await fsWriteFile(marker, '')
1179
+ if (signal?.aborted) throw new SandboxCancelledError()
1180
+ await fsWriteFile(marker, JSON.stringify({ baseSha: baseHead }))
655
1181
  } catch (error) {
656
1182
  // A half-provisioned worktree is removed so the next call starts over.
657
1183
  await this.git(input.repo, ['worktree', 'remove', '--force', identity.environmentId])
658
1184
  await this.git(input.repo, ['worktree', 'prune'])
1185
+ await rm(identity.environmentId, { recursive: true, force: true }).catch(() => {})
659
1186
  throw error
660
1187
  }
661
1188
  return { ...identity, baseSha: baseHead }
662
1189
  }
663
1190
 
1191
+ /** The provisioning marker's recorded metadata: `null` when the marker is
1192
+ * missing, `{}` for a legacy empty or unparseable marker. */
1193
+ private async readSandboxMarker(workspacePath: string): Promise<{ baseSha?: string } | null> {
1194
+ let content: string
1195
+ try {
1196
+ content = await fsReadFile(join(workspacePath, SANDBOX_MARKER), 'utf8')
1197
+ } catch {
1198
+ return null
1199
+ }
1200
+ try {
1201
+ const parsed = JSON.parse(content) as { baseSha?: unknown }
1202
+ return typeof parsed?.baseSha === 'string' && SHA_PATTERN.test(parsed.baseSha)
1203
+ ? { baseSha: parsed.baseSha }
1204
+ : {}
1205
+ } catch {
1206
+ return {}
1207
+ }
1208
+ }
1209
+
1210
+ // ── Operator sandbox lifecycle (#1223) ─────────────────────────
1211
+ //
1212
+ // `open` starts provisioning as an in-process background attempt; `status`
1213
+ // probes the in-flight map, the recorded failure, and the worktree plus its
1214
+ // marker; `close` cancels an attempt and kills detached commands but keeps
1215
+ // the checkout; `refresh` fast-forwards a clean detached checkout.
1216
+
1217
+ private readonly sandboxInflight = new Map<
1218
+ string,
1219
+ {
1220
+ kind: 'provision' | 'resume'
1221
+ promise: Promise<SandboxProviderStatus>
1222
+ abort: AbortController
1223
+ }
1224
+ >()
1225
+ private readonly sandboxFailures = new Map<
1226
+ string,
1227
+ { stage: SandboxProvisionStage; message: string }
1228
+ >()
1229
+ /** environmentId → process groups of its detached commands, kept past
1230
+ * `wait` consuming a command's result (a finished command can leave
1231
+ * background children). Groups with no live member are pruned on every
1232
+ * `start`, so the set stays bounded by the live groups. */
1233
+ private readonly sandboxGroups = new Map<string, Set<number>>()
1234
+
1235
+ private async openSandbox(input: {
1236
+ repo: string
1237
+ operator: string
1238
+ baseBranch: string
1239
+ }): Promise<{
1240
+ status: SandboxProviderStatus
1241
+ settled?: Promise<SandboxProviderStatus>
1242
+ }> {
1243
+ const identity = this.sandboxIdentity(input.repo, input.operator)
1244
+ const id = identity.environmentId
1245
+ const inflight = this.sandboxInflight.get(id)
1246
+ if (inflight !== undefined) {
1247
+ return {
1248
+ status: {
1249
+ state: inflight.kind === 'resume' ? 'resuming' : 'provisioning',
1250
+ kind: inflight.kind,
1251
+ },
1252
+ settled: inflight.promise,
1253
+ }
1254
+ }
1255
+ if (await this.isRegisteredWorktree(id, input.repo)) {
1256
+ const marker = await this.readSandboxMarker(identity.workspacePath)
1257
+ if (marker !== null) {
1258
+ // Keeps the AUT-580 heal on the reuse path.
1259
+ await this.excludeProvisioningMarker(identity.workspacePath)
1260
+ this.sandboxFailures.delete(id)
1261
+ const headSha = await this.resolveOptionalCommit(identity.workspacePath, 'HEAD')
1262
+ return {
1263
+ status: {
1264
+ state: 'ready',
1265
+ handle: {
1266
+ ...identity,
1267
+ ...(marker.baseSha !== undefined ? { baseSha: marker.baseSha } : {}),
1268
+ },
1269
+ kind: 'resume',
1270
+ ...(headSha !== null ? { headSha } : {}),
1271
+ },
1272
+ }
1273
+ }
1274
+ // An interrupted provision: start over.
1275
+ await this.git(input.repo, ['worktree', 'remove', '--force', id])
1276
+ await this.git(input.repo, ['worktree', 'prune'])
1277
+ }
1278
+ this.sandboxFailures.delete(id)
1279
+ const abort = new AbortController()
1280
+ const entry = {
1281
+ kind: 'provision' as const,
1282
+ abort,
1283
+ promise: Promise.resolve<SandboxProviderStatus>({ state: 'absent' }),
1284
+ }
1285
+ this.sandboxInflight.set(id, entry)
1286
+ entry.promise = (async (): Promise<SandboxProviderStatus> => {
1287
+ let stage: SandboxProvisionStage = 'checkout'
1288
+ try {
1289
+ const handle = await this.ensureSandbox(input, {
1290
+ signal: abort.signal,
1291
+ onStage: (next) => {
1292
+ stage = next
1293
+ },
1294
+ })
1295
+ const headSha = await this.resolveOptionalCommit(handle.workspacePath, 'HEAD')
1296
+ return {
1297
+ state: 'ready',
1298
+ handle,
1299
+ kind: 'provision',
1300
+ ...(headSha !== null ? { headSha } : {}),
1301
+ }
1302
+ } catch (error) {
1303
+ if (error instanceof SandboxCancelledError) return { state: 'absent', cancelled: true }
1304
+ const failure = {
1305
+ stage:
1306
+ error instanceof SandboxOperationError && error.stage === 'environment'
1307
+ ? ('environment' as const)
1308
+ : stage,
1309
+ message:
1310
+ redactSandboxMessage(error instanceof Error ? error.message : String(error)) ||
1311
+ 'operator sandbox provisioning failed',
1312
+ }
1313
+ this.sandboxFailures.set(id, failure)
1314
+ return { state: 'failed', failure }
1315
+ } finally {
1316
+ if (this.sandboxInflight.get(id) === entry) this.sandboxInflight.delete(id)
1317
+ }
1318
+ })()
1319
+ return { status: { state: 'provisioning', kind: 'provision' }, settled: entry.promise }
1320
+ }
1321
+
1322
+ private async sandboxStatus(input: {
1323
+ repo: string
1324
+ operator: string
1325
+ }): Promise<SandboxProviderStatus> {
1326
+ const identity = this.sandboxIdentity(input.repo, input.operator)
1327
+ const id = identity.environmentId
1328
+ const inflight = this.sandboxInflight.get(id)
1329
+ if (inflight !== undefined) {
1330
+ return { state: inflight.kind === 'resume' ? 'resuming' : 'provisioning' }
1331
+ }
1332
+ const failure = this.sandboxFailures.get(id)
1333
+ if (failure !== undefined) return { state: 'failed', failure }
1334
+ if (!(await this.isRegisteredWorktree(id, input.repo))) return { state: 'absent' }
1335
+ const marker = await this.readSandboxMarker(identity.workspacePath)
1336
+ if (marker === null) {
1337
+ return {
1338
+ state: 'failed',
1339
+ failure: {
1340
+ stage: 'provision',
1341
+ message: SANDBOX_INTERRUPTED_MESSAGE,
1342
+ },
1343
+ }
1344
+ }
1345
+ const headSha = await this.resolveOptionalCommit(identity.workspacePath, 'HEAD')
1346
+ return {
1347
+ state: 'ready',
1348
+ handle: { ...identity, ...(marker.baseSha !== undefined ? { baseSha: marker.baseSha } : {}) },
1349
+ ...(headSha !== null ? { headSha } : {}),
1350
+ }
1351
+ }
1352
+
1353
+ /** Abort an in-flight attempt and wait for it to finish its own cleanup. */
1354
+ private async cancelSandboxAttempt(id: string): Promise<SandboxProviderStatus | undefined> {
1355
+ const inflight = this.sandboxInflight.get(id)
1356
+ if (inflight === undefined) return undefined
1357
+ inflight.abort.abort()
1358
+ return inflight.promise
1359
+ }
1360
+
1361
+ private async closeSandbox(input: {
1362
+ repo: string
1363
+ operator: string
1364
+ environmentId: string
1365
+ }): Promise<{ outcome: 'closed' | 'absent'; attempt?: SandboxProviderStatus }> {
1366
+ const id = resolve(input.environmentId)
1367
+ const attempt = await this.cancelSandboxAttempt(id)
1368
+ // Every detached command leads its own process group; stop each whole
1369
+ // group (a finished leader can leave background children running) and
1370
+ // confirm it is gone before reporting the environment closed.
1371
+ const groups = [...(this.sandboxGroups.get(id) ?? [])]
1372
+ this.sandboxGroups.delete(id)
1373
+ const stopped = await Promise.all(groups.map((pgid) => terminateProcessGroup(pgid)))
1374
+ if (stopped.includes(false)) {
1375
+ throw new SandboxOperationError(
1376
+ 'close',
1377
+ 'a detached sandbox command survived SIGKILL; the environment is not stopped',
1378
+ )
1379
+ }
1380
+ const kept =
1381
+ (await this.isRegisteredWorktree(id, input.repo)) &&
1382
+ (await this.readSandboxMarker(id)) !== null
1383
+ return { outcome: kept ? 'closed' : 'absent', ...(attempt !== undefined ? { attempt } : {}) }
1384
+ }
1385
+
1386
+ private async refreshSandbox(
1387
+ handle: SandboxEnvironmentIdentity,
1388
+ input: { repo: string; baseBranch: string },
1389
+ ): Promise<SandboxRefreshResult> {
1390
+ const cwd = handle.workspacePath
1391
+ const base = await this.resolveCommit(input.repo, `refs/heads/${input.baseBranch}`)
1392
+ const head = await this.resolveCommit(cwd, 'HEAD')
1393
+ const status = await this.gitOrThrow(cwd, ['status', '--porcelain'])
1394
+ if (status.stdout.trim() !== '') {
1395
+ return {
1396
+ outcome: 'refused',
1397
+ reason: 'dirty',
1398
+ message: SANDBOX_REFRESH_DIRTY_MESSAGE,
1399
+ }
1400
+ }
1401
+ if (head === base || (await this.isAncestor(cwd, base, head))) {
1402
+ return { outcome: 'current', headSha: head, baseSha: base, previousHeadSha: head }
1403
+ }
1404
+ if (!(await this.isAncestor(cwd, head, base))) {
1405
+ return {
1406
+ outcome: 'refused',
1407
+ reason: 'diverged',
1408
+ message: sandboxRefreshDivergedMessage(head, input.baseBranch, base),
1409
+ }
1410
+ }
1411
+ await this.gitOrThrow(cwd, [
1412
+ '-c',
1413
+ 'advice.detachedHead=false',
1414
+ 'checkout',
1415
+ '--quiet',
1416
+ '--detach',
1417
+ base,
1418
+ ])
1419
+ await fsWriteFile(join(cwd, SANDBOX_MARKER), JSON.stringify({ baseSha: base }))
1420
+ return { outcome: 'refreshed', headSha: base, baseSha: base, previousHeadSha: head }
1421
+ }
1422
+
664
1423
  /** Idempotently exclude the provisioning marker in the worktree's
665
1424
  * info/exclude so it never counts as dirt for the publish service's
666
1425
  * untracked-inclusive dirty check (f_c748dc6a). Runs on both ensure
@@ -674,7 +1433,7 @@ export class GitWorktreeProvider implements WorkspaceProvider {
674
1433
  * failure string — the fake workspace uses for the same case, keeping
675
1434
  * the two workspace-port implementations aligned. */
676
1435
  private async excludeProvisioningMarker(workspacePath: string): Promise<void> {
677
- const markerName = '.autobuild-sandbox-provisioned'
1436
+ const markerName = SANDBOX_MARKER
678
1437
  const exclude = await this.gitOrThrow(workspacePath, [
679
1438
  'rev-parse',
680
1439
  '--git-path',
@@ -703,11 +1462,16 @@ export class GitWorktreeProvider implements WorkspaceProvider {
703
1462
  * guest environment (an empty record plus the host PATH and the forwarded
704
1463
  * names — never the host environment wholesale). `timeoutSeconds` bounds
705
1464
  * the child and kills it past the bound; undefined runs unbounded (the
706
- * setup command may install for a long time). */
1465
+ * setup command may install for a long time). `signal` runs the command
1466
+ * in its own process group (`setsid`) and, on abort, terminates the whole
1467
+ * group with SIGTERM then SIGKILL, escalating on the group's liveness
1468
+ * rather than the shell's exit, so a cancelled setup and the children it
1469
+ * forked stop together and release the output pipes this call awaits. */
707
1470
  private async spawnSandboxCommand(
708
1471
  command: string,
709
1472
  cwd: string,
710
1473
  timeoutSeconds?: number,
1474
+ signal?: AbortSignal,
711
1475
  ): Promise<SandboxCommandResult> {
712
1476
  const proc = Bun.spawn(['sh', '-c', command], {
713
1477
  cwd,
@@ -715,14 +1479,27 @@ export class GitWorktreeProvider implements WorkspaceProvider {
715
1479
  stdout: 'pipe',
716
1480
  stderr: 'pipe',
717
1481
  env: this.sandboxEnv(),
1482
+ ...(signal !== undefined ? { detached: true } : {}),
718
1483
  })
1484
+ let onAbort: (() => void) | undefined
1485
+ if (signal !== undefined) {
1486
+ onAbort = () => void terminateProcessGroup(proc.pid)
1487
+ if (signal.aborted) onAbort()
1488
+ else signal.addEventListener('abort', onAbort, { once: true })
1489
+ }
719
1490
  if (timeoutSeconds === undefined) {
720
- const [stdout, stderr, exitCode] = await Promise.all([
721
- new Response(proc.stdout).text(),
722
- new Response(proc.stderr).text(),
723
- proc.exited,
724
- ])
725
- return { exitCode: exitCode ?? -1, stdout, stderr }
1491
+ try {
1492
+ // A child that keeps the pipes open keeps this pending, and the abort
1493
+ // listener armed, until the group is gone.
1494
+ const [stdout, stderr, exitCode] = await Promise.all([
1495
+ new Response(proc.stdout).text(),
1496
+ new Response(proc.stderr).text(),
1497
+ proc.exited,
1498
+ ])
1499
+ return { exitCode: exitCode ?? -1, stdout, stderr }
1500
+ } finally {
1501
+ if (onAbort !== undefined) signal?.removeEventListener('abort', onAbort)
1502
+ }
726
1503
  }
727
1504
  const timer = AbortSignal.timeout(timeoutSeconds * 1000)
728
1505
  const exitedOrTimeout = Promise.race([
@@ -905,15 +1682,27 @@ export class GitWorktreeProvider implements WorkspaceProvider {
905
1682
  ): Promise<{ commandId: string }> {
906
1683
  const cwd =
907
1684
  request.cwd === undefined ? handle.workspacePath : join(handle.workspacePath, request.cwd)
1685
+ // Its own process group (`setsid`), so `close` can stop the command and
1686
+ // everything it forked.
908
1687
  const proc = Bun.spawn(['sh', '-c', request.command], {
909
1688
  cwd,
910
1689
  stdin: 'ignore',
911
1690
  stdout: 'pipe',
912
1691
  stderr: 'pipe',
913
1692
  env: this.sandboxEnv(),
1693
+ detached: true,
914
1694
  })
1695
+ const environmentGroups = this.sandboxGroups.get(resolve(handle.environmentId)) ?? new Set()
1696
+ for (const pgid of environmentGroups) if (!groupAlive(pgid)) environmentGroups.delete(pgid)
1697
+ environmentGroups.add(proc.pid)
1698
+ this.sandboxGroups.set(resolve(handle.environmentId), environmentGroups)
915
1699
  const commandId = `sbcmd-${randomBytes(8).toString('hex')}`
916
- this.sandboxChildren.set(commandId, { proc, stdout: '', stderr: '', exitCode: null })
1700
+ this.sandboxChildren.set(commandId, {
1701
+ proc,
1702
+ stdout: '',
1703
+ stderr: '',
1704
+ exitCode: null,
1705
+ })
917
1706
  this.evictFinishedBeyondCap()
918
1707
  this.trackChildStreams(commandId, { proc })
919
1708
  return { commandId }
@@ -1005,6 +1794,8 @@ export class GitWorktreeProvider implements WorkspaceProvider {
1005
1794
  environmentId: string
1006
1795
  }): Promise<{ snapshots: { outcome: 'confirmed' } }> {
1007
1796
  const path = resolve(input.environmentId)
1797
+ await this.cancelSandboxAttempt(path)
1798
+ this.sandboxFailures.delete(path)
1008
1799
  const repo = this.repos.get(path) ?? (await this.discoverRepo(path)) ?? input.repo
1009
1800
  const removed = await this.git(repo, ['worktree', 'remove', '--force', path])
1010
1801
  if (