@defrex/autobuild 1.10.0 → 1.11.0

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 (250) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +738 -68
  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 +155 -25
  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 +63 -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 +101 -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 +178 -76
  41. package/packages/core/src/cli/dashboard/render.ts +129 -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 +29 -38
  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 +200 -34
  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 +97 -43
  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 +316 -0
  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/79f0e0f4ccd43ba2.json +455 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
  92. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
  93. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
  94. package/packages/core/src/kernel/build-roster.ts +230 -0
  95. package/packages/core/src/kernel/dispatch-capacity.ts +4 -2
  96. package/packages/core/src/kernel/engine.ts +43 -5
  97. package/packages/core/src/kernel/execution-intervals.ts +61 -0
  98. package/packages/core/src/kernel/generators/optimization-log.ts +101 -0
  99. package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
  100. package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
  101. package/packages/core/src/kernel/leaf-restack-state.ts +82 -3
  102. package/packages/core/src/kernel/log-index.ts +19 -0
  103. package/packages/core/src/kernel/optimization-admission.ts +244 -3
  104. package/packages/core/src/kernel/optimization.ts +183 -4
  105. package/packages/core/src/kernel/phase-failures.ts +121 -0
  106. package/packages/core/src/kernel/published-branch-head.ts +60 -0
  107. package/packages/core/src/kernel/reducer-registry.ts +27 -8
  108. package/packages/core/src/kernel/reducer-revisions.ts +25 -0
  109. package/packages/core/src/kernel/reducer.ts +63 -4
  110. package/packages/core/src/kernel/rollup.ts +61 -0
  111. package/packages/core/src/kernel/setup-streak.ts +38 -0
  112. package/packages/core/src/kernel/step-durations.ts +257 -0
  113. package/packages/core/src/kernel/target-observation.ts +6 -1
  114. package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
  115. package/packages/core/src/kernel/verify-diff-base.ts +5 -0
  116. package/packages/core/src/kernel/verify-stages.ts +13 -3
  117. package/packages/core/src/ontology.ts +5 -0
  118. package/packages/core/src/operator/agent-context-serve.ts +631 -0
  119. package/packages/core/src/operator/annotations.ts +75 -5
  120. package/packages/core/src/operator/attention.ts +470 -0
  121. package/packages/core/src/operator/canonical-skills.ts +35 -0
  122. package/packages/core/src/operator/cli-equivalents.ts +270 -0
  123. package/packages/core/src/operator/context-prompts.ts +61 -0
  124. package/packages/core/src/operator/index.ts +49 -1
  125. package/packages/core/src/operator/landings.ts +28 -19
  126. package/packages/core/src/operator/optimization.ts +7 -0
  127. package/packages/core/src/operator/protocol.ts +3 -0
  128. package/packages/core/src/operator/query.ts +122 -72
  129. package/packages/core/src/operator/read-view.ts +5 -2
  130. package/packages/core/src/operator/registry.ts +406 -46
  131. package/packages/core/src/operator/requests.ts +20 -18
  132. package/packages/core/src/operator/sandbox-host.ts +107 -11
  133. package/packages/core/src/operator/sandbox-resolver.ts +253 -0
  134. package/packages/core/src/operator/sandbox.ts +778 -82
  135. package/packages/core/src/operator/ticket-asset-list.ts +77 -0
  136. package/packages/core/src/operator/ticket-assets.ts +167 -0
  137. package/packages/core/src/operator/tickets.ts +33 -2
  138. package/packages/core/src/plugin-sdk/index.ts +22 -0
  139. package/packages/core/src/plugins/manifest.ts +1 -1
  140. package/packages/core/src/ports/forge/fake.ts +92 -1
  141. package/packages/core/src/ports/forge/git-blob.ts +15 -0
  142. package/packages/core/src/ports/forge/github.ts +82 -0
  143. package/packages/core/src/ports/forge/local-git.ts +61 -1
  144. package/packages/core/src/ports/forge-failure.ts +24 -0
  145. package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
  146. package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
  147. package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
  148. package/packages/core/src/ports/tickets/contract.ts +71 -0
  149. package/packages/core/src/ports/tickets/fake.ts +11 -0
  150. package/packages/core/src/ports/tickets/file.ts +18 -0
  151. package/packages/core/src/ports/tickets/github-fake.ts +136 -4
  152. package/packages/core/src/ports/tickets/github.ts +387 -30
  153. package/packages/core/src/ports/tickets/hosted-index.ts +10 -0
  154. package/packages/core/src/ports/tickets/linear.ts +130 -0
  155. package/packages/core/src/ports/tickets/priority.ts +9 -0
  156. package/packages/core/src/ports/tickets/remote-protocol.ts +34 -0
  157. package/packages/core/src/ports/tickets/remote.ts +70 -6
  158. package/packages/core/src/ports/tickets/search.ts +139 -0
  159. package/packages/core/src/ports/types.ts +104 -2
  160. package/packages/core/src/ports/workspace/builtin-capabilities.ts +9 -0
  161. package/packages/core/src/ports/workspace/create.ts +15 -1
  162. package/packages/core/src/ports/workspace/fake.ts +340 -12
  163. package/packages/core/src/ports/workspace/git-worktree.ts +833 -42
  164. package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
  165. package/packages/core/src/ports/workspace/process-group.ts +48 -0
  166. package/packages/core/src/ports/workspace/vercel-sandbox.ts +1260 -123
  167. package/packages/core/src/processes/agent-context-assemble.ts +576 -0
  168. package/packages/core/src/processes/agent-context.ts +469 -0
  169. package/packages/core/src/processes/build-runner.ts +387 -236
  170. package/packages/core/src/processes/dispatcher.ts +211 -55
  171. package/packages/core/src/processes/execution-no-progress.ts +4 -0
  172. package/packages/core/src/processes/optimization-activity.ts +120 -0
  173. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  174. package/packages/core/src/processes/repo-view.ts +78 -2
  175. package/packages/core/src/processes/sandbox-state.ts +53 -6
  176. package/packages/core/src/processes/tick-publication.ts +2 -0
  177. package/packages/core/src/processes/workspace-preparation.ts +76 -0
  178. package/packages/core/src/scenarios/harness.ts +0 -5
  179. package/packages/core/src/store/account-redaction.ts +1 -0
  180. package/packages/core/src/store/adapter.ts +52 -1
  181. package/packages/core/src/store/agent-context.ts +432 -0
  182. package/packages/core/src/store/build-feed.ts +291 -0
  183. package/packages/core/src/store/build-scope.ts +19 -1
  184. package/packages/core/src/store/contract.ts +911 -14
  185. package/packages/core/src/store/digest.ts +19 -6
  186. package/packages/core/src/store/histogram.ts +113 -0
  187. package/packages/core/src/store/local/schema.ts +62 -0
  188. package/packages/core/src/store/local/store.ts +628 -22
  189. package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
  190. package/packages/core/src/store/memory.ts +461 -69
  191. package/packages/core/src/store/open-builds.ts +19 -0
  192. package/packages/core/src/store/phase-session.ts +32 -4
  193. package/packages/core/src/store/reduced-reads.ts +14 -4
  194. package/packages/core/src/store/reducer-value-shapes.json +6987 -5749
  195. package/packages/core/src/store/reducer-values.ts +6 -1
  196. package/packages/core/src/store/remote/client.ts +208 -2
  197. package/packages/core/src/store/remote/compatibility.ts +1 -1
  198. package/packages/core/src/store/remote/index.ts +33 -0
  199. package/packages/core/src/store/remote/protocol.ts +69 -0
  200. package/packages/core/src/store/remote/released-clients.json +11 -0
  201. package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
  202. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  203. package/packages/core/src/store/retention.ts +23 -1
  204. package/packages/core/src/store/rollups.ts +337 -0
  205. package/packages/core/src/store/session-handle.ts +20 -2
  206. package/packages/core/src/store/snapshots.ts +10 -0
  207. package/packages/core/src/store/types.ts +108 -9
  208. package/packages/core/src/testing/dispatch-read-budget.ts +1092 -2
  209. package/packages/core/src/testing/git-config-isolation.ts +7 -5
  210. package/packages/core/src/testing/index.ts +27 -0
  211. package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
  212. package/packages/core/src/testing/reduced-read-budget.ts +1873 -98
  213. package/packages/core/src/web/analytics-source.ts +303 -0
  214. package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
  215. package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
  216. package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
  217. package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
  218. package/packages/core/src/web/assets/app.css +1 -0
  219. package/packages/core/src/web/assets/app.js +9 -0
  220. package/packages/core/src/web/assets/manifest.json +31 -0
  221. package/packages/core/src/web/assets/theme.js +1 -0
  222. package/packages/core/src/web/bounded.ts +31 -0
  223. package/packages/core/src/web/http.ts +315 -0
  224. package/packages/core/src/web/hub.ts +160 -0
  225. package/packages/core/src/web/options.ts +38 -0
  226. package/packages/core/src/web/overview-source.ts +322 -0
  227. package/packages/core/src/web/page.ts +56 -0
  228. package/packages/core/src/web/protocol.ts +151 -0
  229. package/packages/core/src/web/read-only.ts +23 -0
  230. package/packages/core/src/web/repository-source.ts +35 -0
  231. package/packages/core/src/web/server.ts +97 -0
  232. package/skills/code-review/SKILL.md +10 -2
  233. package/skills/guide/SKILL.md +366 -52
  234. package/skills/guide/references/accounts.md +2 -1
  235. package/skills/guide/references/integration-tree.md +2 -2
  236. package/skills/guide/references/operator-api.md +134 -6
  237. package/skills/guide/references/optimization-nodes.md +69 -11
  238. package/skills/guide/references/plugin-authoring.md +37 -1
  239. package/skills/guide/references/remote-store-protocol.md +94 -13
  240. package/skills/guide/references/remote-ticket-protocol.md +40 -0
  241. package/skills/guide/references/restacking.md +20 -4
  242. package/skills/guide/references/setup.md +14 -2
  243. package/skills/guide/references/ticket-dependencies.md +10 -3
  244. package/skills/implement/SKILL.md +23 -4
  245. package/skills/operate/SKILL.md +134 -32
  246. package/skills/plan/SKILL.md +10 -4
  247. package/skills/plan-review/SKILL.md +9 -2
  248. package/skills/spec/SKILL.md +34 -8
  249. package/skills/tickets/SKILL.md +51 -5
  250. package/templates/hosted-service/package.json +2 -2
@@ -22,12 +22,17 @@ import {
22
22
  import { dirname, join, resolve, sep } from 'node:path'
23
23
  import type { WorkspaceBase } from '../../ontology'
24
24
  import {
25
+ redactSandboxMessage,
25
26
  SandboxOperationError,
26
27
  type OperatorSandboxExecution,
27
28
  type SandboxCommandResult,
28
29
  type SandboxEnvironmentIdentity,
30
+ type SandboxProviderStatus,
31
+ type SandboxProvisionStage,
32
+ type SandboxRefreshResult,
29
33
  type SandboxWaitResult,
30
34
  } from './operator-sandbox'
35
+ import { groupAlive, terminateProcessGroup } from './process-group'
31
36
  import type {
32
37
  WorkspaceHandle,
33
38
  WorkspaceProvider,
@@ -39,10 +44,22 @@ export interface ProvisionRecord {
39
44
  repo: string
40
45
  baseBranch: string
41
46
  branch: string
47
+ fresh?: { owner: string }
42
48
  }
43
49
 
44
50
  export type FakeWorkspaceMode = 'filesystem' | 'logical'
45
51
 
52
+ const SANDBOX_MARKER = '.autobuild-sandbox-provisioned'
53
+ const SHA_PATTERN = /^[0-9a-f]{40,64}$/i
54
+
55
+ /** A provision attempt stopped by `close` or `release`; not a failure. */
56
+ class SandboxCancelledError extends Error {
57
+ override readonly name = 'SandboxCancelledError'
58
+ constructor() {
59
+ super('operator sandbox provisioning was cancelled')
60
+ }
61
+ }
62
+
46
63
  async function pathExists(path: string): Promise<boolean> {
47
64
  try {
48
65
  await stat(path)
@@ -120,6 +137,11 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
120
137
  this.sandboxEnvironmentVariables = opts.sandboxEnvironmentVariables ?? []
121
138
  this.sandboxEnvSource = opts.envSource ?? {}
122
139
  this.orchestratorSandbox = {
140
+ lifecycleSupported: true,
141
+ open: (input) => this.openSandbox(input),
142
+ status: (input) => this.sandboxStatus(input),
143
+ close: (input) => this.closeSandbox(input),
144
+ refresh: (handle, input) => this.refreshSandbox(handle, input),
123
145
  describe: (input) => Promise.resolve(this.sandboxIdentity(input.repo, input.operator)),
124
146
  ensure: (input) => this.ensureSandbox(input),
125
147
  exec: (handle, request) => this.sandboxExec(handle, request),
@@ -176,10 +198,19 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
176
198
  this.branchHeads.set(branch, sha)
177
199
  }
178
200
 
201
+ /** Test seam: local branches `localBranchExists` reports, independent of
202
+ * `branchHeads` so tests that set a head keep their slugs. */
203
+ readonly localBranches = new Set<string>()
204
+
205
+ async localBranchExists(_repo: string, branch: string): Promise<boolean> {
206
+ return this.localBranches.has(branch)
207
+ }
208
+
179
209
  async provision(opts: {
180
210
  repo: string
181
211
  baseBranch: string
182
212
  branch: string
213
+ fresh?: { owner: string }
183
214
  }): Promise<WorkspaceProvisionResult> {
184
215
  const failure = this.failures.get('provision')
185
216
  if (failure) throw failure
@@ -257,7 +288,12 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
257
288
  /** Serialization probe: in-flight exec recording, for overlap tests. */
258
289
  private readonly sandboxChildren = new Map<
259
290
  string,
260
- { proc: ReturnType<typeof Bun.spawn>; stdout: string; stderr: string; exitCode: number | null }
291
+ {
292
+ proc: ReturnType<typeof Bun.spawn>
293
+ stdout: string
294
+ stderr: string
295
+ exitCode: number | null
296
+ }
261
297
  >()
262
298
 
263
299
  private sandboxIdentity(repo: string, operator: string): SandboxEnvironmentIdentity {
@@ -285,13 +321,17 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
285
321
  return env
286
322
  }
287
323
 
288
- private async ensureSandbox(input: {
289
- repo: string
290
- operator: string
291
- baseBranch: string
292
- }): Promise<SandboxEnvironmentIdentity> {
324
+ private async ensureSandbox(
325
+ input: {
326
+ repo: string
327
+ operator: string
328
+ baseBranch: string
329
+ },
330
+ control: { onStage?: (stage: SandboxProvisionStage) => void; signal?: AbortSignal } = {},
331
+ ): Promise<SandboxEnvironmentIdentity> {
293
332
  const identity = this.sandboxIdentity(input.repo, input.operator)
294
- if (await pathExists(join(identity.workspacePath, '.autobuild-sandbox-provisioned'))) {
333
+ const { signal } = control
334
+ if (await pathExists(join(identity.workspacePath, SANDBOX_MARKER))) {
295
335
  // Pre-existing sandboxes provisioned before the info/exclude write
296
336
  // landed (AUT-580) keep an unexcluded marker; write the exclusion on
297
337
  // every ensure, mirroring GitWorktreeProvider, so the publish
@@ -306,10 +346,13 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
306
346
  'the logical fake mode has no filesystem to host an operator sandbox',
307
347
  )
308
348
  }
349
+ control.onStage?.('checkout')
350
+ if (signal?.aborted) throw new SandboxCancelledError()
309
351
  await mkdir(dirname(identity.workspacePath), { recursive: true })
310
352
  await rm(identity.workspacePath, { recursive: true, force: true })
311
353
  await cp(input.repo, identity.workspacePath, { recursive: true })
312
354
  try {
355
+ if (signal?.aborted) throw new SandboxCancelledError()
313
356
  // Real git checkout (publish-service parity): the three git checks the
314
357
  // publish service runs through capability.exec (rev-parse, status,
315
358
  // merge-base) must work against the fake exactly as against the real
@@ -353,24 +396,34 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
353
396
  }
354
397
  const baseSha = head.stdout.trim()
355
398
  this.sandboxBaseBranches.set(identity.environmentId, input.baseBranch)
399
+ if (signal?.aborted) throw new SandboxCancelledError()
356
400
  if (this.sandboxSetupCommand !== undefined && this.sandboxSetupCommand.trim() !== '') {
401
+ control.onStage?.('setup')
357
402
  this.sandboxExecEnvironments.push({
358
403
  op: 'setup',
359
404
  command: this.sandboxSetupCommand,
360
405
  env: this.sandboxEnv(),
361
406
  })
407
+ // Its own process group, so a cancel stops setup and its children
408
+ // together and releases the pipes awaited below (mirrors the real
409
+ // provider).
362
410
  const proc = Bun.spawn(['sh', '-c', this.sandboxSetupCommand], {
363
411
  cwd: identity.workspacePath,
364
412
  stdin: 'ignore',
365
413
  stdout: 'pipe',
366
414
  stderr: 'pipe',
367
415
  env: this.sandboxEnv(),
416
+ detached: true,
368
417
  })
418
+ const onAbort = (): void => void terminateProcessGroup(proc.pid)
419
+ if (signal?.aborted) onAbort()
420
+ else signal?.addEventListener('abort', onAbort, { once: true })
369
421
  const [stdout, stderr, exitCode] = await Promise.all([
370
422
  new Response(proc.stdout).text(),
371
423
  new Response(proc.stderr).text(),
372
424
  proc.exited,
373
- ])
425
+ ]).finally(() => signal?.removeEventListener('abort', onAbort))
426
+ if (signal?.aborted) throw new SandboxCancelledError()
374
427
  if (exitCode !== 0) {
375
428
  throw new SandboxOperationError(
376
429
  'provision',
@@ -383,7 +436,8 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
383
436
  // excludeProvisioningMarker: that helper is the info/exclude exclusion
384
437
  // logic alone (the early-return heal runs it too), while this write is
385
438
  // provisioning-specific.
386
- await fsWriteFile(join(identity.workspacePath, '.autobuild-sandbox-provisioned'), '')
439
+ if (signal?.aborted) throw new SandboxCancelledError()
440
+ await fsWriteFile(join(identity.workspacePath, SANDBOX_MARKER), JSON.stringify({ baseSha }))
387
441
  return { ...identity, baseSha }
388
442
  } catch (error) {
389
443
  await rm(identity.workspacePath, { recursive: true, force: true })
@@ -391,6 +445,268 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
391
445
  }
392
446
  }
393
447
 
448
+ // ── Operator sandbox lifecycle (#1223), mirroring GitWorktreeProvider ──
449
+
450
+ private readonly sandboxInflight = new Map<
451
+ string,
452
+ {
453
+ kind: 'provision' | 'resume'
454
+ promise: Promise<SandboxProviderStatus>
455
+ abort: AbortController
456
+ }
457
+ >()
458
+ private readonly sandboxFailures = new Map<
459
+ string,
460
+ { stage: SandboxProvisionStage; message: string }
461
+ >()
462
+ /** environmentId → process groups of its detached commands; dead groups
463
+ * are pruned on every `start`. */
464
+ private readonly sandboxGroups = new Map<string, Set<number>>()
465
+
466
+ /** The marker's recorded metadata: `null` when missing, `{}` when legacy. */
467
+ private async readSandboxMarker(workspacePath: string): Promise<{ baseSha?: string } | null> {
468
+ let content: string
469
+ try {
470
+ content = await fsReadFile(join(workspacePath, SANDBOX_MARKER), 'utf8')
471
+ } catch {
472
+ return null
473
+ }
474
+ try {
475
+ const parsed = JSON.parse(content) as { baseSha?: unknown }
476
+ return typeof parsed?.baseSha === 'string' && SHA_PATTERN.test(parsed.baseSha)
477
+ ? { baseSha: parsed.baseSha }
478
+ : {}
479
+ } catch {
480
+ return {}
481
+ }
482
+ }
483
+
484
+ private async sandboxHead(workspacePath: string): Promise<string | undefined> {
485
+ const head = await this.runSandboxGit(workspacePath, ['rev-parse', 'HEAD'])
486
+ return head.exitCode === 0 && head.stdout.trim() !== '' ? head.stdout.trim() : undefined
487
+ }
488
+
489
+ private async openSandbox(input: {
490
+ repo: string
491
+ operator: string
492
+ baseBranch: string
493
+ }): Promise<{
494
+ status: SandboxProviderStatus
495
+ settled?: Promise<SandboxProviderStatus>
496
+ }> {
497
+ const identity = this.sandboxIdentity(input.repo, input.operator)
498
+ const id = identity.environmentId
499
+ const inflight = this.sandboxInflight.get(id)
500
+ if (inflight !== undefined) {
501
+ return {
502
+ status: {
503
+ state: inflight.kind === 'resume' ? 'resuming' : 'provisioning',
504
+ kind: inflight.kind,
505
+ },
506
+ settled: inflight.promise,
507
+ }
508
+ }
509
+ const marker =
510
+ this.mode === 'filesystem' ? await this.readSandboxMarker(identity.workspacePath) : null
511
+ if (marker !== null) {
512
+ await this.excludeProvisioningMarker(identity.workspacePath)
513
+ this.sandboxFailures.delete(id)
514
+ const headSha = await this.sandboxHead(identity.workspacePath)
515
+ return {
516
+ status: {
517
+ state: 'ready',
518
+ handle: {
519
+ ...identity,
520
+ ...(marker.baseSha !== undefined ? { baseSha: marker.baseSha } : {}),
521
+ },
522
+ kind: 'resume',
523
+ ...(headSha !== undefined ? { headSha } : {}),
524
+ },
525
+ }
526
+ }
527
+ this.sandboxFailures.delete(id)
528
+ const abort = new AbortController()
529
+ const entry = {
530
+ kind: 'provision' as const,
531
+ abort,
532
+ promise: Promise.resolve<SandboxProviderStatus>({ state: 'absent' }),
533
+ }
534
+ this.sandboxInflight.set(id, entry)
535
+ entry.promise = (async (): Promise<SandboxProviderStatus> => {
536
+ let stage: SandboxProvisionStage = 'provision'
537
+ try {
538
+ const handle = await this.ensureSandbox(input, {
539
+ signal: abort.signal,
540
+ onStage: (next) => {
541
+ stage = next
542
+ },
543
+ })
544
+ const headSha = await this.sandboxHead(handle.workspacePath)
545
+ return {
546
+ state: 'ready',
547
+ handle,
548
+ kind: 'provision',
549
+ ...(headSha !== undefined ? { headSha } : {}),
550
+ }
551
+ } catch (error) {
552
+ if (error instanceof SandboxCancelledError) {
553
+ await rm(id, { recursive: true, force: true })
554
+ return { state: 'absent', cancelled: true }
555
+ }
556
+ const failure = {
557
+ stage:
558
+ error instanceof SandboxOperationError && error.stage === 'environment'
559
+ ? ('environment' as const)
560
+ : stage,
561
+ message:
562
+ redactSandboxMessage(error instanceof Error ? error.message : String(error)) ||
563
+ 'operator sandbox provisioning failed',
564
+ }
565
+ this.sandboxFailures.set(id, failure)
566
+ return { state: 'failed', failure }
567
+ } finally {
568
+ if (this.sandboxInflight.get(id) === entry) this.sandboxInflight.delete(id)
569
+ }
570
+ })()
571
+ return { status: { state: 'provisioning', kind: 'provision' }, settled: entry.promise }
572
+ }
573
+
574
+ private async sandboxStatus(input: {
575
+ repo: string
576
+ operator: string
577
+ }): Promise<SandboxProviderStatus> {
578
+ const identity = this.sandboxIdentity(input.repo, input.operator)
579
+ const id = identity.environmentId
580
+ const inflight = this.sandboxInflight.get(id)
581
+ if (inflight !== undefined) {
582
+ return { state: inflight.kind === 'resume' ? 'resuming' : 'provisioning' }
583
+ }
584
+ const failure = this.sandboxFailures.get(id)
585
+ if (failure !== undefined) return { state: 'failed', failure }
586
+ if (this.mode !== 'filesystem' || !(await pathExists(identity.workspacePath))) {
587
+ return { state: 'absent' }
588
+ }
589
+ const marker = await this.readSandboxMarker(identity.workspacePath)
590
+ if (marker === null) {
591
+ return {
592
+ state: 'failed',
593
+ failure: {
594
+ stage: 'provision',
595
+ message: 'provisioning was interrupted before it finished; call sandbox.open to retry',
596
+ },
597
+ }
598
+ }
599
+ const headSha = await this.sandboxHead(identity.workspacePath)
600
+ return {
601
+ state: 'ready',
602
+ handle: { ...identity, ...(marker.baseSha !== undefined ? { baseSha: marker.baseSha } : {}) },
603
+ ...(headSha !== undefined ? { headSha } : {}),
604
+ }
605
+ }
606
+
607
+ private async cancelSandboxAttempt(id: string): Promise<SandboxProviderStatus | undefined> {
608
+ const inflight = this.sandboxInflight.get(id)
609
+ if (inflight === undefined) return undefined
610
+ inflight.abort.abort()
611
+ return inflight.promise
612
+ }
613
+
614
+ private async closeSandbox(input: {
615
+ repo: string
616
+ operator: string
617
+ environmentId: string
618
+ }): Promise<{ outcome: 'closed' | 'absent'; attempt?: SandboxProviderStatus }> {
619
+ const attempt = await this.cancelSandboxAttempt(input.environmentId)
620
+ const groups = [...(this.sandboxGroups.get(input.environmentId) ?? [])]
621
+ this.sandboxGroups.delete(input.environmentId)
622
+ const stopped = await Promise.all(groups.map((pgid) => terminateProcessGroup(pgid)))
623
+ if (stopped.includes(false)) {
624
+ throw new SandboxOperationError(
625
+ 'close',
626
+ 'a detached sandbox command survived SIGKILL; the environment is not stopped',
627
+ )
628
+ }
629
+ const kept =
630
+ this.mode === 'filesystem' && (await this.readSandboxMarker(input.environmentId)) !== null
631
+ return { outcome: kept ? 'closed' : 'absent', ...(attempt !== undefined ? { attempt } : {}) }
632
+ }
633
+
634
+ /** The base head comes from the source repository when it is a git
635
+ * repository (fetched into the checkout), else the checkout's own base
636
+ * branch; then the same clean/ancestor/diverged rules as the real
637
+ * provider apply. */
638
+ private async refreshSandbox(
639
+ handle: SandboxEnvironmentIdentity,
640
+ input: { repo: string; baseBranch: string },
641
+ ): Promise<SandboxRefreshResult> {
642
+ const cwd = handle.workspacePath
643
+ let base: string | undefined
644
+ if (await pathExists(join(input.repo, '.git'))) {
645
+ const fetched = await this.runSandboxGit(cwd, [
646
+ 'fetch',
647
+ '--quiet',
648
+ input.repo,
649
+ `refs/heads/${input.baseBranch}`,
650
+ ])
651
+ if (fetched.exitCode !== 0) {
652
+ throw new SandboxOperationError(
653
+ 'refresh',
654
+ `operator sandbox could not fetch ${input.baseBranch}: ${fetched.stderr.trim() || `exit ${fetched.exitCode}`}`,
655
+ )
656
+ }
657
+ const resolved = await this.runSandboxGit(cwd, ['rev-parse', 'FETCH_HEAD'])
658
+ base = resolved.stdout.trim()
659
+ } else {
660
+ const resolved = await this.runSandboxGit(cwd, [
661
+ 'rev-parse',
662
+ `refs/heads/${input.baseBranch}`,
663
+ ])
664
+ base = resolved.stdout.trim()
665
+ }
666
+ const head = await this.sandboxHead(cwd)
667
+ if (base === '' || head === undefined) {
668
+ throw new SandboxOperationError('refresh', 'operator sandbox could not resolve its heads')
669
+ }
670
+ const status = await this.runSandboxGit(cwd, ['status', '--porcelain'])
671
+ if (status.stdout.trim() !== '') {
672
+ return {
673
+ outcome: 'refused',
674
+ reason: 'dirty',
675
+ message:
676
+ 'the sandbox checkout has uncommitted changes; commit or discard them before refreshing',
677
+ }
678
+ }
679
+ const isAncestor = async (ancestor: string, descendant: string): Promise<boolean> =>
680
+ (await this.runSandboxGit(cwd, ['merge-base', '--is-ancestor', ancestor, descendant]))
681
+ .exitCode === 0
682
+ if (head === base || (await isAncestor(base, head))) {
683
+ return { outcome: 'current', headSha: head, baseSha: base, previousHeadSha: head }
684
+ }
685
+ if (!(await isAncestor(head, base))) {
686
+ return {
687
+ outcome: 'refused',
688
+ reason: 'diverged',
689
+ message: `the checkout head ${head} has diverged from ${input.baseBranch} (${base}); a fast-forward is impossible`,
690
+ }
691
+ }
692
+ const moved = await this.runSandboxGit(cwd, [
693
+ '-c',
694
+ 'advice.detachedHead=false',
695
+ 'checkout',
696
+ '--quiet',
697
+ '--detach',
698
+ base,
699
+ ])
700
+ if (moved.exitCode !== 0) {
701
+ throw new SandboxOperationError(
702
+ 'refresh',
703
+ `operator sandbox could not check out ${base}: ${moved.stderr.trim() || `exit ${moved.exitCode}`}`,
704
+ )
705
+ }
706
+ await fsWriteFile(join(cwd, SANDBOX_MARKER), JSON.stringify({ baseSha: base }))
707
+ return { outcome: 'refreshed', headSha: base, baseSha: base, previousHeadSha: head }
708
+ }
709
+
394
710
  /** Idempotently exclude the provisioning marker in the checkout's
395
711
  * info/exclude so the publish service's untracked-inclusive dirty check
396
712
  * never counts it as dirt (f_c748dc6a). Runs on both ensure paths —
@@ -415,12 +731,12 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
415
731
  (content) => content,
416
732
  () => '',
417
733
  )
418
- if (!existingExclude.split('\n').includes('.autobuild-sandbox-provisioned')) {
734
+ if (!existingExclude.split('\n').includes(SANDBOX_MARKER)) {
419
735
  const prefix =
420
736
  existingExclude === '' || existingExclude.endsWith('\n')
421
737
  ? existingExclude
422
738
  : `${existingExclude}\n`
423
- await fsWriteFile(excludePath, `${prefix}.autobuild-sandbox-provisioned\n`)
739
+ await fsWriteFile(excludePath, `${prefix}${SANDBOX_MARKER}\n`)
424
740
  }
425
741
  }
426
742
 
@@ -506,9 +822,19 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
506
822
  stdout: 'pipe',
507
823
  stderr: 'pipe',
508
824
  env,
825
+ detached: true,
509
826
  })
827
+ const environmentGroups = this.sandboxGroups.get(handle.environmentId) ?? new Set()
828
+ for (const pgid of environmentGroups) if (!groupAlive(pgid)) environmentGroups.delete(pgid)
829
+ environmentGroups.add(proc.pid)
830
+ this.sandboxGroups.set(handle.environmentId, environmentGroups)
510
831
  const commandId = `sbcmd-${Math.random().toString(36).slice(2, 12)}`
511
- const tracked = { proc, stdout: '', stderr: '', exitCode: null as number | null }
832
+ const tracked = {
833
+ proc,
834
+ stdout: '',
835
+ stderr: '',
836
+ exitCode: null as number | null,
837
+ }
512
838
  this.sandboxChildren.set(commandId, tracked)
513
839
  void (async () => {
514
840
  const decoder = new TextDecoder()
@@ -595,6 +921,8 @@ export class FakeWorkspaceProvider implements WorkspaceProvider {
595
921
  environmentId: string
596
922
  }): Promise<{ snapshots: { outcome: 'confirmed' } }> {
597
923
  this.sandboxReleases.push({ ...input })
924
+ await this.cancelSandboxAttempt(input.environmentId)
925
+ this.sandboxFailures.delete(input.environmentId)
598
926
  await rm(input.environmentId, { recursive: true, force: true })
599
927
  return { snapshots: { outcome: 'confirmed' } }
600
928
  }