@defrex/autobuild 1.0.0-beta.1 → 1.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/SPEC.md +285 -53
  2. package/bin/ab-build-runner.ts +10 -8
  3. package/docs/architecture.md +173 -23
  4. package/docs/configuration.md +35 -4
  5. package/docs/hosted-service.md +35 -0
  6. package/docs/integration-tree.md +81 -4
  7. package/docs/landing-policy.md +11 -0
  8. package/docs/migration-1.0.md +9 -0
  9. package/docs/operator-api.md +18 -0
  10. package/docs/remote-store-protocol.md +11 -0
  11. package/docs/restacking.md +42 -7
  12. package/docs/setup.md +21 -0
  13. package/docs/ticket-dependencies.md +6 -45
  14. package/package.json +3 -3
  15. package/packages/core/src/cli/attention.ts +4 -1
  16. package/packages/core/src/cli/binary.ts +17 -1
  17. package/packages/core/src/cli/context.ts +53 -1
  18. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  19. package/packages/core/src/cli/dashboard/detail.ts +45 -1
  20. package/packages/core/src/cli/dashboard/facts.ts +7 -2
  21. package/packages/core/src/cli/dashboard/integration-detail.ts +142 -0
  22. package/packages/core/src/cli/dashboard/integration-row.ts +248 -0
  23. package/packages/core/src/cli/dashboard/landing-display.ts +64 -0
  24. package/packages/core/src/cli/dashboard/model.ts +140 -16
  25. package/packages/core/src/cli/dashboard/poll.ts +40 -4
  26. package/packages/core/src/cli/dashboard/render.ts +106 -5
  27. package/packages/core/src/cli/dashboard/transcript.ts +2 -1
  28. package/packages/core/src/cli/dispatch-frontend.ts +6 -0
  29. package/packages/core/src/cli/dispatch.ts +44 -14
  30. package/packages/core/src/cli/help.ts +16 -1
  31. package/packages/core/src/cli/main.ts +37 -0
  32. package/packages/core/src/cli/publication-settlement.ts +49 -5
  33. package/packages/core/src/cli/repository-status.ts +97 -2
  34. package/packages/core/src/cli/status.ts +24 -1
  35. package/packages/core/src/cli/terminals.ts +94 -93
  36. package/packages/core/src/cli/wait.ts +11 -2
  37. package/packages/core/src/cli/watch.ts +12 -0
  38. package/packages/core/src/config/schema.ts +3 -0
  39. package/packages/core/src/events/catalog.ts +38 -0
  40. package/packages/core/src/events/compatibility.ts +183 -0
  41. package/packages/core/src/events/native-session.ts +13 -0
  42. package/packages/core/src/events/payloads.ts +148 -2
  43. package/packages/core/src/events/policy.ts +209 -0
  44. package/packages/core/src/events/repository.ts +48 -0
  45. package/packages/core/src/integration/harness.ts +4 -4
  46. package/packages/core/src/kernel/__snapshots__/{reducer-registry.test.ts.snap → reducer-accumulator-shapes.json} +771 -538
  47. package/packages/core/src/kernel/change-presence.ts +4 -2
  48. package/packages/core/src/kernel/dispatch-capacity.ts +119 -0
  49. package/packages/core/src/kernel/dispatcher-liveness.ts +5 -1
  50. package/packages/core/src/kernel/engine.ts +25 -5
  51. package/packages/core/src/kernel/forge-health.ts +19 -0
  52. package/packages/core/src/kernel/generators/build-log.ts +18 -0
  53. package/packages/core/src/kernel/generators/node-restack-log.ts +1 -1
  54. package/packages/core/src/kernel/generators/repository-journals.ts +10 -0
  55. package/packages/core/src/kernel/guarded-forge.ts +159 -0
  56. package/packages/core/src/kernel/incremental.ts +4 -2
  57. package/packages/core/src/kernel/integration-completeness.ts +61 -0
  58. package/packages/core/src/kernel/integration-landing.ts +5 -4
  59. package/packages/core/src/kernel/janitor-failure.ts +36 -0
  60. package/packages/core/src/kernel/landing-publication.ts +35 -15
  61. package/packages/core/src/kernel/landing-state.ts +7 -0
  62. package/packages/core/src/kernel/leaf-restack-state.ts +1 -1
  63. package/packages/core/src/kernel/log-index.ts +12 -1
  64. package/packages/core/src/kernel/mixed-version.ts +52 -0
  65. package/packages/core/src/kernel/node-landing.ts +14 -11
  66. package/packages/core/src/kernel/node-restack-demand.ts +29 -0
  67. package/packages/core/src/kernel/node-restack-state.ts +46 -16
  68. package/packages/core/src/kernel/node-restack-transaction.ts +151 -8
  69. package/packages/core/src/kernel/node-restack.ts +34 -10
  70. package/packages/core/src/kernel/publication.ts +22 -0
  71. package/packages/core/src/kernel/read-deferrals.ts +111 -0
  72. package/packages/core/src/kernel/read-facts.ts +27 -6
  73. package/packages/core/src/kernel/reconcile-restack.ts +23 -2
  74. package/packages/core/src/kernel/reducer-registry.ts +15 -2
  75. package/packages/core/src/kernel/reducer.ts +196 -10
  76. package/packages/core/src/kernel/repository-attention.ts +38 -1
  77. package/packages/core/src/kernel/terminal-guard.ts +11 -4
  78. package/packages/core/src/operator/annotations.ts +6 -0
  79. package/packages/core/src/operator/index.ts +2 -0
  80. package/packages/core/src/operator/presentation.ts +5 -0
  81. package/packages/core/src/operator/query.ts +45 -11
  82. package/packages/core/src/operator/registry.ts +17 -1
  83. package/packages/core/src/operator/restack.ts +51 -0
  84. package/packages/core/src/plugin-sdk/index.ts +10 -0
  85. package/packages/core/src/plugins/manifest.ts +1 -1
  86. package/packages/core/src/ports/forge/contract.ts +23 -0
  87. package/packages/core/src/ports/forge/fake.ts +6 -2
  88. package/packages/core/src/ports/forge/git-rewrite.ts +92 -64
  89. package/packages/core/src/ports/forge/github-transport.ts +45 -2
  90. package/packages/core/src/ports/forge/github.ts +56 -17
  91. package/packages/core/src/ports/forge/local-git.ts +7 -2
  92. package/packages/core/src/ports/forge-failure.ts +40 -0
  93. package/packages/core/src/ports/forge-request-context.ts +35 -0
  94. package/packages/core/src/ports/forge-telemetry.ts +16 -0
  95. package/packages/core/src/ports/runner/claude.ts +136 -9
  96. package/packages/core/src/ports/runner/codex.ts +112 -7
  97. package/packages/core/src/ports/runner/contract.ts +78 -0
  98. package/packages/core/src/ports/runner/fake.ts +59 -1
  99. package/packages/core/src/ports/runner/native-cli-fixture.ts +86 -0
  100. package/packages/core/src/ports/runner/native-process-fixture.ts +38 -0
  101. package/packages/core/src/ports/runner/native-session.ts +110 -0
  102. package/packages/core/src/ports/runner/pi-rpc.ts +7 -1
  103. package/packages/core/src/ports/runner/pi.ts +162 -2
  104. package/packages/core/src/ports/types.ts +53 -5
  105. package/packages/core/src/ports/workspace/git-worktree.ts +45 -51
  106. package/packages/core/src/ports/workspace/vercel-sandbox.ts +28 -12
  107. package/packages/core/src/processes/build-child-exit.ts +50 -2
  108. package/packages/core/src/processes/build-child.ts +15 -7
  109. package/packages/core/src/processes/build-runner.ts +909 -213
  110. package/packages/core/src/processes/dispatcher.ts +652 -334
  111. package/packages/core/src/processes/execution-no-progress.ts +15 -0
  112. package/packages/core/src/processes/pause-execution-fixture.ts +37 -0
  113. package/packages/core/src/processes/phase-failure-budget.ts +2 -1
  114. package/packages/core/src/processes/publication-loss.ts +7 -3
  115. package/packages/core/src/processes/repo-view.ts +53 -6
  116. package/packages/core/src/processes/tick-publication.ts +6 -2
  117. package/packages/core/src/runtime-identity.ts +37 -0
  118. package/packages/core/src/store/adapter.ts +4 -2
  119. package/packages/core/src/store/build-scope.ts +9 -0
  120. package/packages/core/src/store/contract.ts +203 -16
  121. package/packages/core/src/store/digest.ts +20 -2
  122. package/packages/core/src/store/local/schema.ts +6 -0
  123. package/packages/core/src/store/local/store.ts +57 -4
  124. package/packages/core/src/store/memory.ts +83 -2
  125. package/packages/core/src/store/new-build.ts +2 -2
  126. package/packages/core/src/store/phase-session.ts +13 -0
  127. package/packages/core/src/store/reduced-reads.ts +43 -4
  128. package/packages/core/src/store/reducer-value-shapes.json +8238 -5764
  129. package/packages/core/src/store/reducer-value-validation.ts +103 -3
  130. package/packages/core/src/store/reducer-values.ts +21 -6
  131. package/packages/core/src/store/remote/client.ts +145 -20
  132. package/packages/core/src/store/remote/index.ts +2 -0
  133. package/packages/core/src/store/remote/protocol.ts +19 -0
  134. package/packages/core/src/store/remote/version.ts +2 -0
  135. package/packages/core/src/store/repo-state-events.ts +3 -1
  136. package/packages/core/src/store/repo-tick.ts +6 -1
  137. package/packages/core/src/store/session-handle.ts +8 -0
  138. package/packages/core/src/store/snapshots.ts +21 -5
  139. package/packages/core/src/store/types.ts +17 -1
  140. package/packages/core/src/testing/dispatch-read-budget.ts +17 -2
  141. package/packages/core/src/testing/index.ts +7 -0
  142. package/packages/core/src/testing/newer-writer.ts +37 -0
  143. package/packages/core/src/testing/reduced-read-budget.ts +3 -0
  144. package/skills/guide/SKILL.md +137 -24
  145. package/skills/guide/references/integration-tree.md +81 -4
  146. package/skills/guide/references/landing-policy.md +11 -0
  147. package/skills/guide/references/migration-1.0.md +9 -0
  148. package/skills/guide/references/operator-api.md +18 -0
  149. package/skills/guide/references/plugin-authoring.md +47 -4
  150. package/skills/guide/references/remote-store-protocol.md +11 -0
  151. package/skills/guide/references/restacking.md +42 -7
  152. package/skills/guide/references/setup.md +21 -0
  153. package/skills/guide/references/ticket-dependencies.md +6 -45
  154. package/skills/implement/SKILL.md +4 -2
  155. package/skills/operate/SKILL.md +63 -6
  156. package/skills/reconcile/SKILL.md +3 -1
  157. package/skills/spec/SKILL.md +49 -39
  158. package/skills/tickets/SKILL.md +15 -43
@@ -291,7 +291,9 @@ export interface WorkspacePublication {
291
291
  * remote branch after an interrupted acknowledgement. `ref` optionally
292
292
  * names the workspace whose git database the probe runs against — used by
293
293
  * the operator-sandbox publication path, whose provider probes from the
294
- * sandbox checkout; the build-path callers omit it. */
294
+ * sandbox checkout; the build-path callers may also supply it. Inspection
295
+ * must not resume a stopped remote guest; publish owns guest cache repair
296
+ * before teardown. */
295
297
  isPublished?(input: { ref?: string; sha: string; branch: string }): Promise<boolean>
296
298
  /** Publish exactly one commit to exactly one branch; no arbitrary command
297
299
  * surface is exposed to the dispatcher or build child. */
@@ -349,6 +351,9 @@ export interface WorkspaceProvider {
349
351
  repo: string
350
352
  baseBranch: string
351
353
  branch: string
354
+ /** Confirmed publication and known stale cache tips, from durable facts.
355
+ * Providers must preserve unknown unpublished work during ordinary resume. */
356
+ publication?: { sha: string; cacheHeads: string[] }
352
357
  /** Immutable recovery checkpoint, never a moved base branch. */
353
358
  revision?: string
354
359
  /** Monotonic environment generation used in provider idempotency keys. */
@@ -506,7 +511,17 @@ export type LandingGateInspection =
506
511
  | { kind: 'gated'; reason: string }
507
512
  | { kind: 'unproven'; reason: string }
508
513
 
514
+ export { ForgeFailure, isForgeFailure } from './forge-failure'
515
+ export type {
516
+ ForgeFailureDetails,
517
+ ForgeRequestContext,
518
+ ForgeRequestObserver,
519
+ } from './forge-failure'
520
+
509
521
  export interface Forge {
522
+ /** Optional API 1.8 capability. Absence means unavailable counts. */
523
+ observeRequests?(observer: import('./forge-failure').ForgeRequestObserver): () => void
524
+
510
525
  inspectReadiness?(input: ForgeReadinessInput): Promise<ForgeReadinessCheck[]>
511
526
  /** Trusted kernel-only Git execution, with forge credentials scoped to its
512
527
  * origin. Never pass this capability or its environment to agent sessions. */
@@ -541,8 +556,11 @@ export interface Forge {
541
556
  readonly name: string
542
557
  /** Optional because another forge may support PRs but not public image assets. */
543
558
  readonly prAttachments?: PrAttachmentHosting
544
- /** Publish the workspace's current HEAD to this remote destination branch. */
545
- pushBranch(workspacePath: string, branch: string): Promise<void>
559
+ /** Publish this exact SHA (HEAD for legacy callers); success requires authoritative readback. */
560
+ /** Exact authoritative observation, refreshing remote-backed caches only on a match.
561
+ * Missing capability refuses kernel publication before attempting a write. */
562
+ confirmPublication?(workspacePath: string, branch: string, sha: string): Promise<boolean>
563
+ pushBranch(workspacePath: string, branch: string, sha?: string): Promise<void>
546
564
  openPr(opts: {
547
565
  workspacePath: string
548
566
  head: string
@@ -618,6 +636,26 @@ export interface Forge {
618
636
  // the front of the tool environment's PATH; CLI availability is a runner
619
637
  // guarantee and does not depend on a global installation or host ordering.
620
638
 
639
+ /** Portable native identity only: never credentials, prompts or process handles. */
640
+ export interface NativeSessionHandle {
641
+ version: 1
642
+ runner: string
643
+ nativeId: string
644
+ host: string
645
+ workspacePath: string
646
+ statePath?: string
647
+ }
648
+
649
+ export type NativeSessionObserver = (handle: NativeSessionHandle) => Promise<void>
650
+ export type AgentResumeOpts = AgentStartOpts
651
+ export type AgentResumeResult =
652
+ | { kind: 'resumed'; session: AgentSessionHandle; result: AgentTurnResult }
653
+ | {
654
+ kind: 'not-resumable'
655
+ reason: 'unsupported' | 'wrong-runner' | 'wrong-host' | 'wrong-workspace' | 'missing-state'
656
+ message: string
657
+ }
658
+
621
659
  export interface AgentSessionHandle {
622
660
  id: string
623
661
  runner: string
@@ -678,6 +716,9 @@ export interface Transcript {
678
716
  }
679
717
 
680
718
  export interface AgentStartOpts {
719
+ /** Await before further native output/prompt processing. Rejections are
720
+ * infrastructure failures and must propagate to the caller. */
721
+ onNativeSession?: NativeSessionObserver
681
722
  /** Installed skill to invoke, e.g. `ab-plan`. */
682
723
  skill: string
683
724
  /** Opaque argument passed to the skill (build slug or harvest run id). */
@@ -714,6 +755,9 @@ export function agentInvocation(opts: AgentStartOpts): string {
714
755
  }
715
756
 
716
757
  export interface AgentContinueOpts {
758
+ /** Await before further native output/prompt processing. Rejections are
759
+ * infrastructure failures and must propagate to the caller. */
760
+ onNativeSession?: NativeSessionObserver
717
761
  env?: Record<string, string>
718
762
  /** Caller-owned cancellation for this continued turn. */
719
763
  signal?: AbortSignal
@@ -724,9 +768,13 @@ export interface AgentContinueOpts {
724
768
 
725
769
  export interface AgentRunner {
726
770
  readonly name: string
771
+ resume?(
772
+ handle: NativeSessionHandle,
773
+ message: string,
774
+ opts: AgentResumeOpts,
775
+ ): Promise<AgentResumeResult>
727
776
  start(opts: AgentStartOpts): Promise<{ session: AgentSessionHandle; result: AgentTurnResult }>
728
- /** Review-loop rounds (§10). Adapters without native resumption implement
729
- * this as start-with-rehydrate-from-store (§9). */
777
+ /** Review-loop rounds (§10), continuing the live native conversation. */
730
778
  continue(
731
779
  session: AgentSessionHandle,
732
780
  message: string,
@@ -1,3 +1,4 @@
1
+ import { publishBranch, remoteBranchHead, refreshBranchCache } from '../forge/git-rewrite'
1
2
  /**
2
3
  * Workspace adapter: git worktrees (SPEC §3.2). The worktree is disposable
3
4
  * scratch (§7); the branch is the build's durable code and travels through
@@ -228,32 +229,6 @@ export class GitWorktreeProvider implements WorkspaceProvider {
228
229
  throw new GitError(['-C', repo, ...args], result)
229
230
  }
230
231
 
231
- /** Reconcile a stale local build ref from the ref updated by a successful
232
- * Forge push. Both ancestry checks and the expected-old update make this a
233
- * normal fast-forward that cannot overwrite divergent or concurrent work. */
234
- private async recoverPublishedBranch(
235
- repo: string,
236
- branch: string,
237
- localSha: string,
238
- ): Promise<string> {
239
- const branchRef = `refs/heads/${branch}`
240
- const publishedRef = `refs/remotes/origin/${branch}`
241
- const publishedSha = await this.resolveOptionalCommit(repo, publishedRef)
242
- if (!publishedSha || publishedSha === localSha) return localSha
243
-
244
- if (await this.isAncestor(repo, localSha, publishedSha)) {
245
- await this.gitOrThrow(repo, ['update-ref', branchRef, publishedSha, localSha])
246
- return publishedSha
247
- }
248
-
249
- if (await this.isAncestor(repo, publishedSha, localSha)) return localSha
250
-
251
- throw new Error(
252
- `cannot recover ${branchRef}: local tip ${localSha} and published ` +
253
- `${publishedRef} tip ${publishedSha} have diverged; refusing to rewrite either ref`,
254
- )
255
- }
256
-
257
232
  /** Attach the one detached registration this provider owns. The published
258
233
  * ref must first have made its HEAD exactly the durable branch tip; an
259
234
  * arbitrary detached commit is never adopted or discarded. */
@@ -346,6 +321,7 @@ export class GitWorktreeProvider implements WorkspaceProvider {
346
321
  repo: string
347
322
  baseBranch: string
348
323
  branch: string
324
+ publication?: { sha: string; cacheHeads: string[] }
349
325
  }): Promise<WorkspaceProvisionResult> {
350
326
  const { repo, baseBranch, branch } = opts
351
327
  // Fails with git's stderr for a missing path or a non-repo directory.
@@ -373,14 +349,41 @@ export class GitWorktreeProvider implements WorkspaceProvider {
373
349
  }
374
350
 
375
351
  const branchRef = `refs/heads/${branch}`
376
- const localSha = await this.resolveOptionalCommit(repo, branchRef)
352
+ let localSha = await this.resolveOptionalCommit(repo, branchRef)
353
+ if (
354
+ !localSha &&
355
+ opts.publication &&
356
+ (await remoteBranchHead(this.exec, repo, branch)) === opts.publication.sha
357
+ ) {
358
+ await refreshBranchCache(this.exec, repo, branch, opts.publication.sha)
359
+ localSha = opts.publication.sha
360
+ }
377
361
  if (localSha) {
378
362
  // A branch attached outside this provider's root is not ours to repair
379
363
  // or reuse. The ordinary worktree-add/checkout error below remains the
380
364
  // non-destructive diagnostic for that unsupported registration.
381
- const sha = worktrees.branchAttached
382
- ? localSha
383
- : await this.recoverPublishedBranch(repo, branch, localSha)
365
+ let sha = localSha
366
+ const proof = opts.publication
367
+ if (
368
+ !worktrees.branchAttached &&
369
+ proof &&
370
+ proof.sha !== localSha &&
371
+ proof.cacheHeads.includes(localSha)
372
+ ) {
373
+ // A detached unknown result is live unpublished work, even if the
374
+ // public branch cache is stale. Refuse before mutating that cache.
375
+ if (worktrees.detached) {
376
+ const detached = await this.resolveCommit(worktrees.detached.path, 'HEAD')
377
+ if (detached !== proof.sha)
378
+ throw new Error(
379
+ `detached HEAD ${detached} does not match durable publication ${proof.sha}; refusing to discard either commit`,
380
+ )
381
+ }
382
+ if ((await remoteBranchHead(this.exec, repo, branch)) === proof.sha) {
383
+ await refreshBranchCache(this.exec, repo, branch, proof.sha)
384
+ sha = proof.sha
385
+ }
386
+ }
384
387
 
385
388
  if (worktrees.detached) {
386
389
  if (worktrees.branchAttached) {
@@ -406,9 +409,8 @@ export class GitWorktreeProvider implements WorkspaceProvider {
406
409
  }
407
410
  }
408
411
 
409
- // Resume (§15.6-C): rematerialize only after the local branch has been
410
- // monotonically reconciled with any push-updated publication evidence.
411
- // This path performs no fetch and no remote write.
412
+ // Resume from retained work. Tracking refs cannot authorize replacing it;
413
+ // only a recorded publication confirmed above can refresh a stale cache.
412
414
  await this.gitOrThrow(repo, ['worktree', 'add', worktreePath, branch])
413
415
  this.repos.set(worktreePath, repo)
414
416
  return {
@@ -1017,13 +1019,9 @@ export class GitWorktreeProvider implements WorkspaceProvider {
1017
1019
  }
1018
1020
  const ref = resolve(input.ref)
1019
1021
  if (await this.hasOriginRemote(ref)) {
1020
- const result = await this.git(ref, ['ls-remote', 'origin', `refs/heads/${input.branch}`])
1021
- if (result.exitCode !== 0) {
1022
- throw new GitError(['-C', ref, 'ls-remote', 'origin', `refs/heads/${input.branch}`], result)
1023
- }
1024
- return result.stdout
1025
- .split('\n')
1026
- .some((line) => line.trim() === `${input.sha}\trefs/heads/${input.branch}`)
1022
+ const head = await remoteBranchHead(this.exec, ref, input.branch)
1023
+ if (head === input.sha) await refreshBranchCache(this.exec, ref, input.branch, input.sha)
1024
+ return head === input.sha
1027
1025
  }
1028
1026
  // No origin remote (local-git-forge deployments, where a local finalize
1029
1027
  // performs no network push): compare the branch locally. Linked
@@ -1037,16 +1035,7 @@ export class GitWorktreeProvider implements WorkspaceProvider {
1037
1035
  GitWorktreeProvider.assertPublicationInput(input)
1038
1036
  const ref = resolve(input.ref)
1039
1037
  if (await this.hasOriginRemote(ref)) {
1040
- const args = [
1041
- '-C',
1042
- ref,
1043
- 'push',
1044
- '--no-verify',
1045
- 'origin',
1046
- `${input.sha}:refs/heads/${input.branch}`,
1047
- ]
1048
- const result = await this.exec(['git', ...args], {})
1049
- if (result.exitCode !== 0) throw new GitError(args, result)
1038
+ await publishBranch(this.exec, ref, input.branch, input.sha)
1050
1039
  return
1051
1040
  }
1052
1041
  // Local equivalent of the finalize push for deployments without an
@@ -1063,7 +1052,12 @@ export class GitWorktreeProvider implements WorkspaceProvider {
1063
1052
  }
1064
1053
  }
1065
1054
  const args = ['-C', ref, 'update-ref', `refs/heads/${input.branch}`, input.sha]
1066
- const result = await this.git(ref, ['update-ref', `refs/heads/${input.branch}`, input.sha])
1055
+ const result = await this.git(ref, [
1056
+ 'update-ref',
1057
+ `refs/heads/${input.branch}`,
1058
+ input.sha,
1059
+ existing ?? '0'.repeat(input.sha.length),
1060
+ ])
1067
1061
  if (result.exitCode !== 0) throw new GitError(args, result)
1068
1062
  }
1069
1063
  }
@@ -1,4 +1,4 @@
1
- import { gitRewrite } from '../forge/git-rewrite'
1
+ import { gitRewrite, parseRemoteHead } from '../forge/git-rewrite'
2
2
  import { delegateCredential } from '../../store/remote/credentials'
3
3
  import type { ExecutionLaunchAuth } from './build-execution'
4
4
  import { createHash } from 'node:crypto'
@@ -2515,21 +2515,26 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2515
2515
  return execOrThrow(this.exec, ['git', 'remote', 'get-url', 'origin'], this.options.repo)
2516
2516
  }
2517
2517
 
2518
- private async remoteBranchHead(branch: string, label: string): Promise<string | null> {
2518
+ private async remoteBranchHead(branch: string, _label: string): Promise<string | null> {
2519
2519
  if (this.options.remoteBranchHead !== undefined) {
2520
- return (await this.options.remoteBranchHead(branch)) ?? null
2520
+ const head = (await this.options.remoteBranchHead(branch)) ?? null
2521
+ if (head !== null && !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(head))
2522
+ throw new Error('invalid authoritative remote branch head')
2523
+ return head
2521
2524
  }
2522
- return oneSha(
2525
+ return parseRemoteHead(
2523
2526
  await execOrThrow(
2524
2527
  this.exec,
2525
- ['git', 'ls-remote', '--heads', 'origin', `refs/heads/${branch}`],
2528
+ ['git', 'ls-remote', '--refs', 'origin', `refs/heads/${branch}`],
2526
2529
  this.options.repo,
2527
2530
  ),
2528
- label,
2531
+ `refs/heads/${branch}`,
2529
2532
  )
2530
2533
  }
2531
2534
 
2532
2535
  private async isPublished(input: { sha: string; branch: string }): Promise<boolean> {
2536
+ // Inspection must not resume a stopped persistent guest. Publication owns
2537
+ // its cache refresh before teardown; recovery needs only forge readback.
2533
2538
  const head = await this.remoteBranchHead(input.branch, `published branch ${input.branch}`)
2534
2539
  return head === input.sha
2535
2540
  }
@@ -2636,17 +2641,28 @@ export class VercelSandboxProvider implements WorkspaceProvider {
2636
2641
  sha: input.sha,
2637
2642
  })
2638
2643
  }
2639
- await commandOrThrow(sandbox, {
2640
- cmd: 'git',
2641
- args: ['push', '--no-verify', 'origin', `${input.sha}:refs/heads/${input.branch}`],
2642
- cwd: VERCEL_WORKSPACE_PATH,
2643
- })
2644
- await sandbox.stop({ signal: this.operationSignal() })
2644
+ if (!(await this.isPublished(input))) {
2645
+ try {
2646
+ await commandOrThrow(sandbox, {
2647
+ cmd: 'git',
2648
+ args: ['push', '--no-verify', 'origin', `${input.sha}:refs/heads/${input.branch}`],
2649
+ cwd: VERCEL_WORKSPACE_PATH,
2650
+ })
2651
+ } catch (error) {
2652
+ if (!(await this.isPublished(input))) throw error
2653
+ }
2654
+ }
2645
2655
  // Post-push verification without host git: the injected branch-head
2646
2656
  // reader (origin mode) or the host ls-remote fallback answers.
2647
2657
  const published = await this.remoteBranchHead(input.branch, 'published branch')
2648
2658
  if (published !== input.sha)
2649
2659
  throw new Error(`published head ${published ?? '(missing)'} did not match ${input.sha}`)
2660
+ await commandOrThrow(sandbox, {
2661
+ cmd: 'git',
2662
+ args: ['update-ref', `refs/heads/${input.branch}`, input.sha],
2663
+ cwd: VERCEL_WORKSPACE_PATH,
2664
+ })
2665
+ await sandbox.stop({ signal: this.operationSignal() })
2650
2666
  } finally {
2651
2667
  try {
2652
2668
  await sandbox.update({ networkPolicy: normal }, { signal: this.operationSignal() })
@@ -1,3 +1,4 @@
1
+ import { DEFAULT_PROCESS_GROUP_STOP_TIMEOUT_MS } from './process-group'
1
2
  import type { ProcessGroupReaperOptions } from './process-group-reaper'
2
3
  import { launchProcessGroupReaper, processGroupReaperOptions } from './process-group-reaper'
3
4
 
@@ -44,8 +45,15 @@ export class BuildChildExitCoordinator {
44
45
  if (this.intendedExitCode !== undefined) this.closeParentWatch()
45
46
  }
46
47
 
47
- terminate(exitCode: number): void {
48
- if (this.intendedExitCode === undefined) this.intendedExitCode = exitCode
48
+ terminate(exitCode: number, remainingStopMs?: number): void {
49
+ if (this.intendedExitCode === undefined) {
50
+ this.intendedExitCode = exitCode
51
+ if (remainingStopMs !== undefined)
52
+ this.reaperOptions.stopTimeoutMs = Math.min(
53
+ this.reaperOptions.stopTimeoutMs,
54
+ Math.max(0, remainingStopMs),
55
+ )
56
+ }
49
57
  if (this.handedOff) return
50
58
 
51
59
  this.closeParentWatch()
@@ -76,3 +84,43 @@ export class BuildChildExitCoordinator {
76
84
  this.exit(this.intendedExitCode!)
77
85
  }
78
86
  }
87
+
88
+ /** Shares the original process-group stop deadline with agent persistence.
89
+ * A repeated signal never restarts the deadline or bypasses the first intent. */
90
+ export class BuildChildShutdown {
91
+ private readonly controller = new AbortController()
92
+ private deadline: number | undefined
93
+ private exitCode: number | undefined
94
+ private cancel: (() => void) | undefined
95
+ constructor(
96
+ private readonly terminal: BuildChildExitCoordinator,
97
+ private readonly now: () => number = Date.now,
98
+ private readonly schedule: (callback: () => void, delay: number) => () => void = (
99
+ callback,
100
+ delay,
101
+ ) => {
102
+ const timer = setTimeout(callback, delay)
103
+ return () => clearTimeout(timer)
104
+ },
105
+ ) {}
106
+ get signal(): AbortSignal {
107
+ return this.controller.signal
108
+ }
109
+ request(exitCode: number): void {
110
+ if (this.controller.signal.aborted) return
111
+ this.exitCode = exitCode
112
+ this.deadline = this.now() + DEFAULT_PROCESS_GROUP_STOP_TIMEOUT_MS
113
+ this.cancel = this.schedule(
114
+ () => this.finish(exitCode),
115
+ DEFAULT_PROCESS_GROUP_STOP_TIMEOUT_MS - 1_000,
116
+ )
117
+ this.controller.abort(new Error('dispatcher shutdown'))
118
+ }
119
+ finish(exitCode: number): void {
120
+ this.cancel?.()
121
+ this.terminal.terminate(
122
+ this.exitCode ?? exitCode,
123
+ this.deadline === undefined ? undefined : Math.max(0, this.deadline - this.now()),
124
+ )
125
+ }
126
+ }
@@ -1,3 +1,5 @@
1
+ import { guardForge } from '../kernel/guarded-forge'
2
+ import { isRemoteWorkspace } from '../events/workspace-remote'
1
3
  import { readBuildFacts } from '../store/reduced-reads'
2
4
  import { hostname } from 'node:os'
3
5
  import { createForge } from '../ports/forge/create'
@@ -33,7 +35,7 @@ export async function runBuildChild(
33
35
  input: BuildExecutionStart,
34
36
  env: Record<string, string | undefined> = process.env,
35
37
  openStore: (ref: string, token?: string) => BuildStore = openProductionStore,
36
- opts: { guest?: boolean } = {},
38
+ opts: { guest?: boolean; shutdownSignal?: AbortSignal } = {},
37
39
  ): Promise<void> {
38
40
  const fullStore = openStore(input.storeRef, env.AB_TOKEN)
39
41
  const store = fullStore.scopeBuild(input.slug)
@@ -64,12 +66,15 @@ export async function runBuildChild(
64
66
  repoRoot: workspace.path ?? workspace.ref,
65
67
  env,
66
68
  })
67
- const forge = await createForge({
68
- name: currentConfig.forge,
69
- registry: plugins,
70
- env,
71
- repoRoot: workspace.path ?? workspace.ref,
72
- })
69
+ const forge = guardForge(
70
+ await createForge({
71
+ name: currentConfig.forge,
72
+ registry: plugins,
73
+ env,
74
+ repoRoot: workspace.path ?? workspace.ref,
75
+ }),
76
+ { store: fullStore, repo: record.repo, name: currentConfig.forge, wait: true },
77
+ )
73
78
  const getConfig = async () => {
74
79
  const latest = await store.getArtifact(input.slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
75
80
  if (latest === null) return currentConfig
@@ -95,6 +100,9 @@ export async function runBuildChild(
95
100
  getConfig,
96
101
  runtimes,
97
102
  workspacePath: workspace.path ?? workspace.ref,
103
+ workspaceProvider: workspace.provider,
104
+ workspaceRemote: opts.guest === true || isRemoteWorkspace(workspace),
105
+ shutdownSignal: opts.shutdownSignal,
98
106
  branch: workspace.branch,
99
107
  slug: input.slug,
100
108
  exec: spawnExec,