@defrex/autobuild 1.4.1 → 1.4.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.
package/README.md CHANGED
@@ -26,7 +26,7 @@ From the repository you want built, install Autobuild as a development dependenc
26
26
  <!-- release-install:start -->
27
27
 
28
28
  ```sh
29
- bun add -d --exact @defrex/autobuild@1.4.1
29
+ bun add -d --exact @defrex/autobuild@1.4.2
30
30
  ```
31
31
 
32
32
  <!-- release-install:end -->
package/SPEC.md CHANGED
@@ -3374,10 +3374,15 @@ It preserves unpublished branch commits and distinct detached producer candidate
3374
3374
  under immutable `refs/autobuild/archive/<build>/<sha>` refs, verifies their exact
3375
3375
  readback, and records `workspace.commits-preserved` before cleanup. Replacement
3376
3376
  provisioning restores those exact refs before starting an agent. Preservation
3377
- never advances the public build branch. A confirmed absent environment records
3378
- `workspace.commits-lost`, naming known candidates and explicitly noting that any
3379
- additional unpublished SHAs could not be inspected. Unknown fencing, inspection,
3380
- transport, or receipt-write outcomes leave the workspace and snapshots intact.
3377
+ never advances the public build branch. A confirmed absent environment, or one
3378
+ that exists without a provisioned checkout, records `workspace.commits-lost`,
3379
+ naming known candidates and explicitly noting that any additional unpublished
3380
+ SHAs could not be inspected. Unknown fencing, inspection, transport, or
3381
+ receipt-write outcomes leave the workspace and snapshots intact. A workspace
3382
+ flagged by `workspace.cleanup-required` is never launched into: the dispatcher
3383
+ releases it and provisions the next generation. A preservation or release
3384
+ failure is recorded against its build, as an infrastructure failure or janitor
3385
+ attention, and never stops the dispatcher from advancing other builds.
3381
3386
  Fencing is revalidated after restart; a saved receipt alone never authorizes
3382
3387
  cleanup of a newer execution. Current recovery notes are linked by the session
3383
3388
  manifest's `workspaceRecovery` field. Recovery notes apply to the next session
@@ -630,10 +630,15 @@ It preserves unpublished branch commits and distinct detached producer candidate
630
630
  under immutable `refs/autobuild/archive/<build>/<sha>` refs, verifies their exact
631
631
  readback, and records `workspace.commits-preserved` before cleanup. Replacement
632
632
  provisioning restores those exact refs before starting an agent. Preservation
633
- never advances the public build branch. A confirmed absent environment records
634
- `workspace.commits-lost`, naming known candidates and explicitly noting that any
635
- additional unpublished SHAs could not be inspected. Unknown fencing, inspection,
636
- transport, or receipt-write outcomes leave the workspace and snapshots intact.
633
+ never advances the public build branch. A confirmed absent environment, or one
634
+ that exists without a provisioned checkout, records `workspace.commits-lost`,
635
+ naming known candidates and explicitly noting that any additional unpublished
636
+ SHAs could not be inspected. Unknown fencing, inspection, transport, or
637
+ receipt-write outcomes leave the workspace and snapshots intact. A workspace
638
+ flagged by `workspace.cleanup-required` is never launched into: the dispatcher
639
+ releases it and provisions the next generation. A preservation or release
640
+ failure is recorded against its build, as an infrastructure failure or janitor
641
+ attention, and never stops the dispatcher from advancing other builds.
637
642
  Fencing is revalidated after restart; a saved receipt alone never authorizes
638
643
  cleanup of a newer execution. Current recovery notes are linked by the session
639
644
  manifest's `workspaceRecovery` field. Recovery notes apply to the next session
@@ -1372,7 +1372,11 @@ status` and both dashboards, consumes `maxInfrastructureAttempts`, and raises
1372
1372
  one setup-targeted escalation when exhausted. If cleanup also fails, both the
1373
1373
  step output and cleanup uncertainty remain durable instead of hiding the root
1374
1374
  cause. A marked sandbox does not repeat provisioning; every replacement/new
1375
- generation does.
1375
+ generation does. A named sandbox left without the completion marker, for example
1376
+ after a provision timeout, is flagged `cleanup-required` and never launched into.
1377
+ The dispatcher releases it automatically, recording an empty
1378
+ `workspace.commits-lost` when no checkout exists, and provisions the next
1379
+ generation.
1376
1380
 
1377
1381
  The representative actual-provider check is opt-in and must point at an
1378
1382
  independent consuming repository whose `autobuild.toml` selects the universal
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defrex/autobuild",
3
- "version": "1.4.1",
3
+ "version": "1.4.2",
4
4
  "description": "Agent-driven software delivery from groomed ticket to merged PR",
5
5
  "repository": {
6
6
  "type": "git",
@@ -135,7 +135,7 @@
135
135
  "release": "bun tools/release.ts",
136
136
  "postgres:migrate": "bun packages/postgres-store/src/bin.ts migrate",
137
137
  "docs:configuration": "bun tools/configuration-reference.ts --write",
138
- "check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/reducer-value-shapes.ts --check && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/package-boundary-check.ts",
138
+ "check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/reducer-value-shapes.ts --check && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/package-boundary-check.ts && bun tools/publish-dependencies-check.ts",
139
139
  "check:build": "bun tools/workspace-manifest-check.ts && bun tools/bin-mode-check.ts && bun tools/publish-contents-check.ts && bun tools/publish-imports-check.ts",
140
140
  "format:staged": "git-format-staged --formatter './node_modules/.bin/biome format --stdin-file-path {}' '*.js' '*.jsx' '*.ts' '*.tsx' '*.json' '*.jsonc' '*.css' '*.graphql' '*.gql'",
141
141
  "prepare": "husky",
@@ -156,8 +156,8 @@
156
156
  },
157
157
  "devDependencies": {
158
158
  "@biomejs/biome": "2.5.5",
159
- "@defrex/autobuild-postgres-store": "1.4.1",
160
- "@defrex/autobuild-vercel-sandbox": "1.4.1",
159
+ "@defrex/autobuild-postgres-store": "1.4.2",
160
+ "@defrex/autobuild-vercel-sandbox": "1.4.2",
161
161
  "@resvg/resvg-js": "2.6.2",
162
162
  "@types/bun": "^1.3.14",
163
163
  "@types/node": "^24.0.0",
@@ -338,8 +338,10 @@ export interface WorkspacePublication {
338
338
  replayPack?: string
339
339
  }): Promise<boolean>
340
340
 
341
- /** Dispatcher-only, after a durable non-destructive fence. Errors never
342
- * constitute proof that an environment or its unpublished work is absent. */
341
+ /** Dispatcher-only, after a durable non-destructive fence. `absent` means
342
+ * the environment is gone or exists without a provisioned checkout. Errors
343
+ * never constitute proof that an environment or its unpublished work is
344
+ * absent. */
343
345
  preserve?(input: {
344
346
  ref: string
345
347
  slug: string
@@ -1365,6 +1365,19 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1365
1365
  const sandbox = await this.facade.get(input.ref, this.operationSignal())
1366
1366
  if (sandbox === null) return { outcome: 'absent' }
1367
1367
  const heads = await this.withTrustedGit(sandbox, input.ref, async (exec) => {
1368
+ // A VM whose provisioning stopped before the checkout was moved
1369
+ // into place has nothing to preserve. The probe runs without the
1370
+ // checkout as cwd, and only a definite "missing" proves absence.
1371
+ const checkout = await sandbox.runCommand({
1372
+ cmd: 'test',
1373
+ args: ['-e', `${VERCEL_WORKSPACE_PATH}/.git`],
1374
+ signal: this.operationSignal(),
1375
+ })
1376
+ if (checkout.exitCode === 1) return null
1377
+ if (checkout.exitCode !== 0)
1378
+ throw new Error(
1379
+ `preservation could not confirm the checkout at ${VERCEL_WORKSPACE_PATH} (exit ${checkout.exitCode})`,
1380
+ )
1368
1381
  const capability = gitRewrite(exec, false)
1369
1382
  const remote = await this.remoteBranchHead(input.branch, 'preservation branch')
1370
1383
  const base =
@@ -1383,6 +1396,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1383
1396
  archive: capability.archive,
1384
1397
  })
1385
1398
  })
1399
+ if (heads === null) return { outcome: 'absent' }
1386
1400
  return { outcome: 'preserved', heads }
1387
1401
  }),
1388
1402
  rewrite: (input: Parameters<NonNullable<WorkspacePublication['rewrite']>>[0]) =>
@@ -7,7 +7,7 @@ import {
7
7
  type MissingAccountCredential,
8
8
  } from '../accounts/availability'
9
9
 
10
- import { WorkspaceFenceUnknown, preserveWorkspaceBeforeRelease } from './workspace-preservation'
10
+ import { preserveWorkspaceBeforeRelease } from './workspace-preservation'
11
11
  import { WorkspaceCleanupRequired } from '../ports/types'
12
12
  import { ArtifactMetaUnsupportedError } from '../store/artifact-meta'
13
13
  import type { TicketPreparation } from '../kernel/ticket-preparation'
@@ -683,6 +683,12 @@ function openWorkspace(events: CurrentBuildFacts): OpenBuildWorkspace | null {
683
683
  return events.workspace
684
684
  }
685
685
 
686
+ /** The open workspace is the one a provider flagged `cleanup-required`: it
687
+ * must be reaped and replaced, never launched into. */
688
+ function cleanupRequiredWorkspace(events: CurrentBuildFacts): boolean {
689
+ return events.workspace !== null && events.latestWorkspace?.type === 'workspace.cleanup-required'
690
+ }
691
+
686
692
  /** The build's base branch, from its own `build.created` fact (§15.3);
687
693
  * falls back to the repo config for logs missing one. */
688
694
  function baseBranchOf(events: CurrentBuildFacts, config: Config): string {
@@ -1519,6 +1525,14 @@ export class Dispatcher {
1519
1525
  if (launched.has(slug)) return 'already-active'
1520
1526
  launched.add(slug)
1521
1527
  const facts = (await readBuildFacts(this.store, slug)).value
1528
+ // Callers reap and reprovision a flagged workspace; an agent never starts
1529
+ // in an environment a provider flagged `cleanup-required`.
1530
+ if (
1531
+ facts.workspace !== null &&
1532
+ cleanupRequiredWorkspace(facts) &&
1533
+ this.workspaceOwner(facts.workspace)?.recovery !== undefined
1534
+ )
1535
+ return 'already-active'
1522
1536
  if (facts.log.restack.target === undefined && facts.lastCreated !== undefined) {
1523
1537
  const branch = facts.lastCreated.payload.baseBranch
1524
1538
  await this.observeTarget(slug, branch, undefined, report)
@@ -4045,9 +4059,9 @@ export class Dispatcher {
4045
4059
  const recovery = this.workspaceOwner(open)?.recovery
4046
4060
  if (recovery === undefined) return false
4047
4061
  // Last-chance settlement boundary (AUT-328): record the pending
4048
- // publication's fate BEFORE the destructive reap. The guard's append
4049
- // failure propagates — a stale workspace with an unrecorded pending
4050
- // request is never reaped (the next tick retries).
4062
+ // publication's fate BEFORE the destructive reap. A guard failure is
4063
+ // recorded against the build — a stale workspace with an unrecorded
4064
+ // pending request is never reaped (the next tick retries).
4051
4065
  try {
4052
4066
  await preserveWorkspaceBeforeRelease({
4053
4067
  store: this.store,
@@ -4069,7 +4083,12 @@ export class Dispatcher {
4069
4083
  // Keep this generation and its pending work until forge recovery,
4070
4084
  // while allowing the sweep to supervise the remaining builds.
4071
4085
  if (error instanceof ForgeRequestDeferred) return false
4072
- if (!(error instanceof WorkspaceFenceUnknown)) throw error
4086
+ // A repository-wide forge cooldown or version deferral is not this
4087
+ // build's failure; the tick-level handlers own it.
4088
+ if (error instanceof ForgeCooldown || error instanceof MixedVersionDeferral) throw error
4089
+ // Any other preservation or settlement failure (an unknown fence, a
4090
+ // checkout that could not be inspected) retains the workspace and its
4091
+ // pending work and is attributed to this build, never to the tick.
4073
4092
  await this.recordInfrastructureFailure(slug, events, {
4074
4093
  provider: open.provider,
4075
4094
  workspaceRef: open.ref,
@@ -4353,6 +4372,23 @@ export class Dispatcher {
4353
4372
  return this.completeDispatchBoundaries(record, seed, report, launched)
4354
4373
 
4355
4374
  stage = 'workspace'
4375
+ const flagged = openWorkspace(events)
4376
+ if (
4377
+ flagged !== null &&
4378
+ cleanupRequiredWorkspace(events) &&
4379
+ this.workspaceOwner(flagged)?.recovery !== undefined
4380
+ ) {
4381
+ // A retry never launches into a flagged environment: release it, then
4382
+ // provision the next generation below. A live lease means a foreign
4383
+ // continuation still owns the build.
4384
+ if (this.hasLiveExecutionLease(record)) return 'parked'
4385
+ if (!(await this.reapStaleWorkspace(record.slug, events, 'replacement'))) {
4386
+ // The failure is already durable against this build.
4387
+ launched.add(record.slug)
4388
+ return 'parked'
4389
+ }
4390
+ events = (await readBuildFacts(store, record.slug)).value
4391
+ }
4356
4392
  if (openWorkspace(events) === null) {
4357
4393
  if (this.deps.workspaces.recovery !== undefined) {
4358
4394
  // Recovery-capable provider: durable marker + tracked background
@@ -4704,209 +4740,236 @@ export class Dispatcher {
4704
4740
  if (launched.has(record.slug)) continue
4705
4741
  // Budget gate: the sweep re-attaches runners per expired build.
4706
4742
  if (this.outOfBudget(opts)) break
4707
- if (record.lease) {
4708
- if (new Date(record.lease.expiresAt).getTime() > now) continue // healthy
4709
- }
4710
- const facts = await this.store.buildFacts(record.slug)
4711
- const state = facts.state
4712
- if (mixedVersionDeferred(state)) {
4713
- await deferMixedVersion(this.store, record.slug)
4714
- continue
4715
- }
4716
- if (
4717
- (state.status === 'queued' && state.discardRequest !== undefined) ||
4718
- heldByRepositoryPause(state, paused)
4719
- ) {
4720
- continue
4721
- }
4722
- if (
4723
- state.status === 'queued' &&
4724
- !state.pendingCommands.some((command) => command.command === 'abort') &&
4725
- !(await this.dispatchBudget(record.slug))
4726
- )
4727
- continue
4728
- const pendingRewrite = facts.publication.latestUncompletedRequest()?.payload
4729
- const retryIntent =
4730
- pendingRewrite?.operation === 'reconcile' && pendingRewrite.rewrite
4731
- ? { operation: 'reconcile' as const, id: pendingRewrite.rewrite.id }
4732
- : facts.log.restack.intent
4733
- ? { operation: 'restack' as const, id: facts.log.restack.intent.id }
4734
- : undefined
4735
- // Publication waits must not prevent a replacement runner from
4736
- // acknowledging controls, including abort on an exhausted episode.
4737
- if (retryIntent && state.pendingCommands.length === 0) {
4738
- try {
4739
- await publicationRetryGate(
4740
- { store: this.store, slug: record.slug, clock: this.deps.clock, actor: DISPATCHER },
4741
- retryIntent.operation,
4742
- retryIntent.id,
4743
- )
4744
- } catch (error) {
4745
- if (error instanceof ForgeRequestDeferred) continue
4746
- throw error
4747
- }
4743
+ try {
4744
+ await this.sweepBuild(record, report, launched, paused, now)
4745
+ } catch (error) {
4746
+ // Per-build containment: one build's failure never stops the sweep
4747
+ // from advancing the others. Workspace failures are already durable
4748
+ // against the build; a repository-wide cooldown still ends the tick.
4749
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
4750
+ if (error instanceof ForgeCooldown) throw error
4751
+ const message =
4752
+ error instanceof Error || isForgeFailure(error) ? error.message : String(error)
4753
+ report.janitorFailed += 1
4754
+ report.janitorDiagnostics.push(`build ${record.slug}: lease sweep failed — ${message}`)
4748
4755
  }
4749
- const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
4750
- if (decision === undefined) continue
4751
- if (state.status === 'done' || state.status === 'aborted') continue
4752
- const orphanEligible = (state: BuildState) =>
4753
- !paused &&
4754
- state.status === 'running' &&
4755
- (state.kind !== 'node' || integrationCurrent(state)) &&
4756
- state.sessions.open.some((session) => session.suspensionCause === undefined)
4757
- const provedEnded =
4758
- facts.open === null &&
4759
- (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch')
4760
- const cleanup = state.verifyStage.cleanupExecutionSeq
4761
- if (
4762
- !record.lease &&
4763
- now - new Date(record.updatedAt).getTime() < this.leaseTtlMs &&
4764
- facts.lastExecution !== 'relaunch' &&
4765
- !(cleanup !== undefined && state.verifyStage.executionSeq <= cleanup) &&
4766
- !(provedEnded && (decision.kind !== 'wait' || orphanEligible(state)))
4767
- )
4768
- continue // preserve first-claim grace, but never postpone proved-ended work
4756
+ }
4757
+ }
4769
4758
 
4770
- if (
4771
- state.kind === 'node' &&
4772
- (!integrationCurrent(state) || facts.workspace === null) &&
4773
- decision.kind !== 'wait'
4774
- )
4775
- continue // cascade owns node runner admission
4776
- // Raw history, read at most once and only by a branch that acts on it.
4777
- let loaded: CurrentBuildFacts | undefined
4778
- const history = async (): Promise<CurrentBuildFacts> => {
4779
- loaded ??= (await readBuildFacts(this.store, record.slug)).value
4780
- return loaded
4781
- }
4782
- // Liveness gate (durable supervision): a recorded execution the provider
4783
- // observes as RUNNING is left completely alone — no settle, no reap, no
4784
- // replacement, no re-attach. This is the change that stops a supervisor
4785
- // restart from replacing a healthy environment generation. A provider-
4786
- // proved end settles first (completion facts, lease release, publication)
4787
- // and then falls through to the normal decision; a provider-proved loss
4788
- // falls through to the existing stale path below.
4789
- let orphanRecoveryDue = orphanEligible(state) && facts.open === null
4790
- const foreignExecution = facts.open
4791
- // A provider- or log-proved end in the same generation re-attaches in
4792
- // place: the guest finished its work, the workspace is still the
4793
- // build's, and replacing the environment would discard a healthy
4794
- // generation. Only an unproven stale lease or a proved loss reaps.
4795
- // A start that later found the open workspace missing is a proved loss
4796
- // too: the recorded end no longer vouches for an environment that is
4797
- // gone, and re-attaching would fail against the same ref forever.
4798
- const failure = state.infrastructureFailure
4799
- const workspaceMissing =
4800
- failure?.cause === 'missing' &&
4801
- failure.operation === 'start' &&
4802
- failure.workspaceRef === facts.workspace?.ref
4803
- let endedInPlace =
4804
- (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch') &&
4805
- !workspaceMissing
4806
- if (
4807
- foreignExecution !== null &&
4808
- foreignExecution.commandId !== undefined &&
4809
- !launched.has(record.slug)
4810
- ) {
4811
- const owner = this.executionOwner(foreignExecution.provider)
4812
- const execution = owner?.buildExecution
4813
- if (execution?.observe !== undefined) {
4814
- const settlement = await settleOpenExecution(
4815
- {
4816
- store: this.store,
4817
- execution,
4818
- ...(this.settlePublication !== undefined
4819
- ? { settlePublication: this.settlePublication }
4820
- : {}),
4821
- },
4822
- record.slug,
4823
- foreignExecution,
4824
- )
4825
- if (settlement === 'running') continue
4826
- // Unknown liveness is never proof that an open execution is dead.
4827
- // Settlement may itself raise provider attention. Revalidate cleanup
4828
- // eligibility from the advanced canonical state before admission.
4829
- orphanRecoveryDue = orphanEligible((await this.store.buildFacts(record.slug)).state)
4830
- if (settlement === 'settled') {
4831
- report.settled += 1
4832
- endedInPlace = true
4833
- }
4834
- }
4759
+ /** One build's lease-sweep pass; `leaseSweep` contains its failures. */
4760
+ private async sweepBuild(
4761
+ record: BuildRecord,
4762
+ report: TickReport,
4763
+ launched: Set<string>,
4764
+ paused: boolean,
4765
+ now: number,
4766
+ ): Promise<void> {
4767
+ if (record.lease) {
4768
+ if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
4769
+ }
4770
+ const facts = await this.store.buildFacts(record.slug)
4771
+ const state = facts.state
4772
+ if (mixedVersionDeferred(state)) {
4773
+ await deferMixedVersion(this.store, record.slug)
4774
+ return
4775
+ }
4776
+ if (
4777
+ (state.status === 'queued' && state.discardRequest !== undefined) ||
4778
+ heldByRepositoryPause(state, paused)
4779
+ ) {
4780
+ return
4781
+ }
4782
+ if (
4783
+ state.status === 'queued' &&
4784
+ !state.pendingCommands.some((command) => command.command === 'abort') &&
4785
+ !(await this.dispatchBudget(record.slug))
4786
+ )
4787
+ return
4788
+ const pendingRewrite = facts.publication.latestUncompletedRequest()?.payload
4789
+ const retryIntent =
4790
+ pendingRewrite?.operation === 'reconcile' && pendingRewrite.rewrite
4791
+ ? { operation: 'reconcile' as const, id: pendingRewrite.rewrite.id }
4792
+ : facts.log.restack.intent
4793
+ ? { operation: 'restack' as const, id: facts.log.restack.intent.id }
4794
+ : undefined
4795
+ // Publication waits must not prevent a replacement runner from
4796
+ // acknowledging controls, including abort on an exhausted episode.
4797
+ if (retryIntent && state.pendingCommands.length === 0) {
4798
+ try {
4799
+ await publicationRetryGate(
4800
+ { store: this.store, slug: record.slug, clock: this.deps.clock, actor: DISPATCHER },
4801
+ retryIntent.operation,
4802
+ retryIntent.id,
4803
+ )
4804
+ } catch (error) {
4805
+ if (error instanceof ForgeRequestDeferred) return
4806
+ throw error
4835
4807
  }
4836
- const publicationRecoveryDue =
4837
- state.status !== 'paused' &&
4838
- state.status !== 'blocked' &&
4839
- (facts.publication.pending() || facts.publication.abandonedPending())
4840
- const open = facts.workspace
4841
- // A provider- or log-proved END in the same generation re-attaches in
4842
- // place: the guest finished its work, the workspace is still the
4843
- // build's, and replacing the environment would discard a healthy
4844
- // generation. Only an unproven stale lease or a proved loss reaps.
4845
- if (open !== null && this.workspaceOwner(open)?.recovery !== undefined && !endedInPlace) {
4846
- const parked = decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue
4847
- const reason =
4848
- state.status === 'paused'
4849
- ? ('pause' as const)
4850
- : state.status === 'blocked'
4851
- ? ('blocked' as const)
4852
- : ('replacement' as const)
4853
- const reaped = await this.reapStaleWorkspace(record.slug, await history(), reason)
4854
- if (!reaped) continue
4855
- if (!parked) {
4856
- // Recovery-capable provider: reap inline (bounded), then kick the
4857
- // same background continuation — it provisions and launches without
4858
- // blocking this tick. Local providers never enter this branch.
4859
- const kicked = await this.ensureProvisionContinuation(record, await history(), 'launch')
4860
- if (kicked === 'kicked') {
4861
- report.provisioning += 1
4862
- report.swept += 1
4863
- }
4864
- continue
4808
+ }
4809
+ const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
4810
+ if (decision === undefined) return
4811
+ if (state.status === 'done' || state.status === 'aborted') return
4812
+ const orphanEligible = (state: BuildState) =>
4813
+ !paused &&
4814
+ state.status === 'running' &&
4815
+ (state.kind !== 'node' || integrationCurrent(state)) &&
4816
+ state.sessions.open.some((session) => session.suspensionCause === undefined)
4817
+ const provedEnded =
4818
+ facts.open === null &&
4819
+ (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch')
4820
+ const cleanup = state.verifyStage.cleanupExecutionSeq
4821
+ if (
4822
+ !record.lease &&
4823
+ now - new Date(record.updatedAt).getTime() < this.leaseTtlMs &&
4824
+ facts.lastExecution !== 'relaunch' &&
4825
+ !(cleanup !== undefined && state.verifyStage.executionSeq <= cleanup) &&
4826
+ !(provedEnded && (decision.kind !== 'wait' || orphanEligible(state)))
4827
+ )
4828
+ return // preserve first-claim grace, but never postpone proved-ended work
4829
+
4830
+ if (
4831
+ state.kind === 'node' &&
4832
+ (!integrationCurrent(state) || facts.workspace === null) &&
4833
+ decision.kind !== 'wait'
4834
+ )
4835
+ return // cascade owns node runner admission
4836
+ // Raw history, read at most once and only by a branch that acts on it.
4837
+ let loaded: CurrentBuildFacts | undefined
4838
+ const history = async (): Promise<CurrentBuildFacts> => {
4839
+ loaded ??= (await readBuildFacts(this.store, record.slug)).value
4840
+ return loaded
4841
+ }
4842
+ // Liveness gate (durable supervision): a recorded execution the provider
4843
+ // observes as RUNNING is left completely alone — no settle, no reap, no
4844
+ // replacement, no re-attach. This is the change that stops a supervisor
4845
+ // restart from replacing a healthy environment generation. A provider-
4846
+ // proved end settles first (completion facts, lease release, publication)
4847
+ // and then falls through to the normal decision; a provider-proved loss
4848
+ // falls through to the existing stale path below.
4849
+ let orphanRecoveryDue = orphanEligible(state) && facts.open === null
4850
+ const foreignExecution = facts.open
4851
+ // A provider- or log-proved end in the same generation re-attaches in
4852
+ // place: the guest finished its work, the workspace is still the
4853
+ // build's, and replacing the environment would discard a healthy
4854
+ // generation. Only an unproven stale lease or a proved loss reaps.
4855
+ // A start that later found the open workspace missing is a proved loss
4856
+ // too: the recorded end no longer vouches for an environment that is
4857
+ // gone, and re-attaching would fail against the same ref forever.
4858
+ const failure = state.infrastructureFailure
4859
+ const workspaceMissing =
4860
+ failure?.cause === 'missing' &&
4861
+ failure.operation === 'start' &&
4862
+ failure.workspaceRef === facts.workspace?.ref
4863
+ let endedInPlace =
4864
+ (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch') &&
4865
+ !workspaceMissing
4866
+ if (
4867
+ foreignExecution !== null &&
4868
+ foreignExecution.commandId !== undefined &&
4869
+ !launched.has(record.slug)
4870
+ ) {
4871
+ const owner = this.executionOwner(foreignExecution.provider)
4872
+ const execution = owner?.buildExecution
4873
+ if (execution?.observe !== undefined) {
4874
+ const settlement = await settleOpenExecution(
4875
+ {
4876
+ store: this.store,
4877
+ execution,
4878
+ ...(this.settlePublication !== undefined
4879
+ ? { settlePublication: this.settlePublication }
4880
+ : {}),
4881
+ },
4882
+ record.slug,
4883
+ foreignExecution,
4884
+ )
4885
+ if (settlement === 'running') return
4886
+ // Unknown liveness is never proof that an open execution is dead.
4887
+ // Settlement may itself raise provider attention. Revalidate cleanup
4888
+ // eligibility from the advanced canonical state before admission.
4889
+ orphanRecoveryDue = orphanEligible((await this.store.buildFacts(record.slug)).state)
4890
+ if (settlement === 'settled') {
4891
+ report.settled += 1
4892
+ endedInPlace = true
4865
4893
  }
4866
4894
  }
4867
- // Reachable via the reap block above: when the wait decision is parked
4868
- // (no publication recovery due) the `if (!parked)` arm continues, but the
4869
- // parked arm falls through here after a successful reap. Without this
4870
- // guard the tick would reach the unconditional `launch` below and start a
4871
- // fresh runner for a paused or blocked build whose workspace was just
4872
- // reaped. Every other path that reaches this line with a wait decision
4873
- // already continued earlier.
4874
- if (decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue) continue
4875
- if (
4876
- facts.workspace === null &&
4877
- this.deps.workspaces.recovery !== undefined &&
4878
- (await history()).workspaceGenerations > 0
4879
- ) {
4895
+ }
4896
+ const publicationRecoveryDue =
4897
+ state.status !== 'paused' &&
4898
+ state.status !== 'blocked' &&
4899
+ (facts.publication.pending() || facts.publication.abandonedPending())
4900
+ const open = facts.workspace
4901
+ // A flagged `cleanup-required` workspace never re-attaches in place: it
4902
+ // is reaped and replaced by the next generation.
4903
+ if (endedInPlace && open !== null && cleanupRequiredWorkspace(await history()))
4904
+ endedInPlace = false
4905
+ // A provider- or log-proved END in the same generation re-attaches in
4906
+ // place: the guest finished its work, the workspace is still the
4907
+ // build's, and replacing the environment would discard a healthy
4908
+ // generation. Only an unproven stale lease or a proved loss reaps.
4909
+ if (open !== null && this.workspaceOwner(open)?.recovery !== undefined && !endedInPlace) {
4910
+ const parked = decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue
4911
+ const reason =
4912
+ state.status === 'paused'
4913
+ ? ('pause' as const)
4914
+ : state.status === 'blocked'
4915
+ ? ('blocked' as const)
4916
+ : ('replacement' as const)
4917
+ const reaped = await this.reapStaleWorkspace(record.slug, await history(), reason)
4918
+ if (!reaped) return
4919
+ if (!parked) {
4920
+ // Recovery-capable provider: reap inline (bounded), then kick the
4921
+ // same background continuation — it provisions and launches without
4922
+ // blocking this tick. Local providers never enter this branch.
4880
4923
  const kicked = await this.ensureProvisionContinuation(record, await history(), 'launch')
4881
4924
  if (kicked === 'kicked') {
4882
4925
  report.provisioning += 1
4883
4926
  report.swept += 1
4884
- continue
4885
4927
  }
4886
- // In-flight or foreign-live: whoever owns the marker completes the
4887
- // boundaries and the launch; this tick performs neither.
4888
- continue
4928
+ return
4889
4929
  }
4890
- try {
4891
- const result = await this.launch(record.slug, launched, report)
4892
- if (result === 'scheduled') report.swept += 1
4893
- } catch (error) {
4894
- // Launchers normally record provider failures themselves. Preserve
4895
- // durable attention if orphan cleanup fails before that boundary,
4896
- // without counting an already-recorded failure twice.
4897
- if (orphanRecoveryDue && open !== null) {
4898
- const current = (await readBuildFacts(this.store, record.slug)).value
4899
- if (current.infrastructureCount === facts.infrastructureCount)
4900
- await this.recordInfrastructureFailure(record.slug, current, {
4901
- provider: open.provider,
4902
- workspaceRef: open.ref,
4903
- operation: 'start',
4904
- error,
4905
- cleanupPending: false,
4906
- })
4907
- }
4908
- throw error
4930
+ }
4931
+ // Reachable via the reap block above: when the wait decision is parked
4932
+ // (no publication recovery due) the `if (!parked)` arm continues, but the
4933
+ // parked arm falls through here after a successful reap. Without this
4934
+ // guard the tick would reach the unconditional `launch` below and start a
4935
+ // fresh runner for a paused or blocked build whose workspace was just
4936
+ // reaped. Every other path that reaches this line with a wait decision
4937
+ // already continued earlier.
4938
+ if (decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue) return
4939
+ if (
4940
+ facts.workspace === null &&
4941
+ this.deps.workspaces.recovery !== undefined &&
4942
+ (await history()).workspaceGenerations > 0
4943
+ ) {
4944
+ const kicked = await this.ensureProvisionContinuation(record, await history(), 'launch')
4945
+ if (kicked === 'kicked') {
4946
+ report.provisioning += 1
4947
+ report.swept += 1
4948
+ return
4909
4949
  }
4950
+ // In-flight or foreign-live: whoever owns the marker completes the
4951
+ // boundaries and the launch; this tick performs neither.
4952
+ return
4953
+ }
4954
+ try {
4955
+ const result = await this.launch(record.slug, launched, report)
4956
+ if (result === 'scheduled') report.swept += 1
4957
+ } catch (error) {
4958
+ // Launchers normally record provider failures themselves. Preserve
4959
+ // durable attention if orphan cleanup fails before that boundary,
4960
+ // without counting an already-recorded failure twice.
4961
+ if (orphanRecoveryDue && open !== null) {
4962
+ const current = (await readBuildFacts(this.store, record.slug)).value
4963
+ if (current.infrastructureCount === facts.infrastructureCount)
4964
+ await this.recordInfrastructureFailure(record.slug, current, {
4965
+ provider: open.provider,
4966
+ workspaceRef: open.ref,
4967
+ operation: 'start',
4968
+ error,
4969
+ cleanupPending: false,
4970
+ })
4971
+ }
4972
+ throw error
4910
4973
  }
4911
4974
  }
4912
4975
 
@@ -156,7 +156,7 @@ export async function preserveWorkspaceBeforeRelease(deps: {
156
156
  (sha) => !prior?.heads.some((head) => head.sha === sha),
157
157
  ),
158
158
  inventory: 'additional-shas-unavailable' as const,
159
- reason: `${deps.reason}: source environment is absent; additional unpublished SHAs could not be inspected`,
159
+ reason: `${deps.reason}: source environment or checkout is absent; additional unpublished SHAs could not be inspected`,
160
160
  },
161
161
  }
162
162
  if (!(await deps.store.appendIfCurrent(deps.slug, current.cursor, write)))
@@ -44,5 +44,16 @@
44
44
  "provenance": {
45
45
  "tag": "v1.4.1"
46
46
  }
47
+ },
48
+ {
49
+ "version": "1.4.2",
50
+ "publishedAt": "2026-11-03T20:12:21.908Z",
51
+ "protocol": "7",
52
+ "contract": "1.4.0.json",
53
+ "projects": true,
54
+ "catalogIdentity": "f9289449e0df64c1de972d7456cd4d50f179f06b36a20bed05ba91411573b194",
55
+ "provenance": {
56
+ "tag": "v1.4.2"
57
+ }
47
58
  }
48
59
  ]
@@ -1160,6 +1160,118 @@ export async function parkedSweepReadBudget(opts: {
1160
1160
  }
1161
1161
  }
1162
1162
 
1163
+ /** Append filler facts to one build until its log holds `length` events. */
1164
+ async function seedBuildFiller(
1165
+ store: import('../store/memory').MemoryBuildStore,
1166
+ slug: string,
1167
+ length: number,
1168
+ ): Promise<void> {
1169
+ const events = buildEventRows(store, slug)
1170
+ while (events.length < length)
1171
+ await store.append(slug, {
1172
+ actor: humanActor('budget'),
1173
+ type: 'build.auto-merge-cancelled',
1174
+ payload: {},
1175
+ })
1176
+ }
1177
+
1178
+ function buildEventRows(
1179
+ store: import('../store/memory').MemoryBuildStore,
1180
+ slug: string,
1181
+ ): import('../events/catalog').AbEvent[] {
1182
+ return Reflect.get(store, 'builds').get(slug).events
1183
+ }
1184
+
1185
+ /** Count every event row MemoryBuildStore returns for one build, including
1186
+ * getReducerValue's private snapshot-tail reads, split at `boundary`. */
1187
+ function instrumentBuildRows(
1188
+ store: import('../store/memory').MemoryBuildStore,
1189
+ slug: string,
1190
+ boundary: () => number,
1191
+ metrics: { historicalRows: number; tailRows: number },
1192
+ ): () => void {
1193
+ const events = buildEventRows(store, slug)
1194
+ const slice = Array.prototype.slice
1195
+ events.slice = function (start?: number, end?: number) {
1196
+ const result = slice.call(this, start, end) as typeof events
1197
+ const limit = boundary()
1198
+ for (const event of result) {
1199
+ if (event.seq <= limit) metrics.historicalRows++
1200
+ else metrics.tailRows++
1201
+ }
1202
+ return result
1203
+ }
1204
+ return () => Reflect.deleteProperty(events, 'slice')
1205
+ }
1206
+
1207
+ /** A stale build whose open workspace is flagged `cleanup-required` and whose
1208
+ * preservation keeps failing re-enters the sweep's reap branch on every pass.
1209
+ * Each pass must read only the tail it appended itself, the same number of
1210
+ * reduced reads at 100 and 100,000 events, and nothing at all once the build
1211
+ * is healthy again. Fresh dispatchers retain no per-process cache. */
1212
+ export async function flaggedWorkspaceSweepReadBudget(opts: {
1213
+ store: import('../store/memory').MemoryBuildStore
1214
+ slug: string
1215
+ dispatcher: () => Dispatcher
1216
+ advance: () => void
1217
+ effects: () => { reaps: number; launches: number }
1218
+ }) {
1219
+ const { store, slug } = opts
1220
+ const sweeps = 4
1221
+ const metrics = { historicalRows: 0, tailRows: 0 }
1222
+ let reducerReads = 0
1223
+ const getReducerValue = store.getReducerValue.bind(store)
1224
+ store.getReducerValue = async (...args) => {
1225
+ reducerReads++
1226
+ return getReducerValue(...args)
1227
+ }
1228
+ const infrastructureFailures = async () =>
1229
+ (await readBuildFacts(store, slug)).value.infrastructureCount
1230
+ const perTick: Record<number, number[]> = {}
1231
+ for (const length of [100, 100_000]) {
1232
+ await seedBuildFiller(store, slug, length)
1233
+ opts.advance()
1234
+ // Rows the previous pass appended are the only tail a pass may read.
1235
+ let boundary = buildEventRows(store, slug).at(-1)!.seq
1236
+ await opts.dispatcher().tick({ acceptNewWork: false }) // warm durable projections
1237
+ const restore = instrumentBuildRows(store, slug, () => boundary, metrics)
1238
+ const before = opts.effects()
1239
+ perTick[length] = []
1240
+ for (let tick = 0; tick < sweeps; tick++) {
1241
+ const failures = await infrastructureFailures()
1242
+ const appendedBefore = buildEventRows(store, slug).at(-1)!.seq
1243
+ opts.advance()
1244
+ metrics.historicalRows = metrics.tailRows = reducerReads = 0
1245
+ await opts.dispatcher().tick({ acceptNewWork: false })
1246
+ perTick[length]!.push(reducerReads)
1247
+ expect(metrics.historicalRows).toBe(0)
1248
+ expect(await infrastructureFailures()).toBe(failures + 1)
1249
+ boundary = appendedBefore
1250
+ }
1251
+ expect(new Set(perTick[length]).size).toBe(1)
1252
+ expect(opts.effects()).toEqual(before)
1253
+ restore()
1254
+ }
1255
+ expect(perTick[100]).toEqual(perTick[100_000])
1256
+ // Unchanged path: a live lease makes the build healthy, so the sweep skips
1257
+ // it. After one settling pass, nothing changes and nothing is read.
1258
+ await store.claimLease(slug, 'budget-runner', 3_600_000)
1259
+ await opts.dispatcher().tick({ acceptNewWork: false })
1260
+ const restore = instrumentBuildRows(store, slug, () => Number.POSITIVE_INFINITY, metrics)
1261
+ metrics.historicalRows = metrics.tailRows = 0
1262
+ for (let tick = 0; tick < 2; tick++) await opts.dispatcher().tick({ acceptNewWork: false })
1263
+ expect(metrics).toEqual({ historicalRows: 0, tailRows: 0 })
1264
+ restore()
1265
+ Reflect.deleteProperty(store, 'getReducerValue')
1266
+ console.log('flagged workspace sweep read budget', {
1267
+ histories: [100, 100_000],
1268
+ sweeps,
1269
+ reducedReadsPerSweep: perTick[100_000]![0],
1270
+ historicalRows: 0,
1271
+ idleRows: 0,
1272
+ })
1273
+ }
1274
+
1163
1275
  /** In-memory history seeding for preparation budgets; never used as a recurring read. */
1164
1276
  export async function seedPreparationHistory(store: BuildStore, repo: string, facts: number) {
1165
1277
  await store.ensureRepo(repo)
@@ -903,10 +903,15 @@ It preserves unpublished branch commits and distinct detached producer candidate
903
903
  under immutable `refs/autobuild/archive/<build>/<sha>` refs, verifies their exact
904
904
  readback, and records `workspace.commits-preserved` before cleanup. Replacement
905
905
  provisioning restores those exact refs before starting an agent. Preservation
906
- never advances the public build branch. A confirmed absent environment records
907
- `workspace.commits-lost`, naming known candidates and explicitly noting that any
908
- additional unpublished SHAs could not be inspected. Unknown fencing, inspection,
909
- transport, or receipt-write outcomes leave the workspace and snapshots intact.
906
+ never advances the public build branch. A confirmed absent environment, or one
907
+ that exists without a provisioned checkout, records `workspace.commits-lost`,
908
+ naming known candidates and explicitly noting that any additional unpublished
909
+ SHAs could not be inspected. Unknown fencing, inspection, transport, or
910
+ receipt-write outcomes leave the workspace and snapshots intact. A workspace
911
+ flagged by `workspace.cleanup-required` is never launched into: the dispatcher
912
+ releases it and provisions the next generation. A preservation or release
913
+ failure is recorded against its build, as an infrastructure failure or janitor
914
+ attention, and never stops the dispatcher from advancing other builds.
910
915
  Fencing is revalidated after restart; a saved receipt alone never authorizes
911
916
  cleanup of a newer execution. Current recovery notes are linked by the session
912
917
  manifest's `workspaceRecovery` field. Recovery notes apply to the next session
@@ -4,8 +4,8 @@
4
4
  "build": "ab-hosted-service-build"
5
5
  },
6
6
  "dependencies": {
7
- "@defrex/autobuild-hosted-store-service": "1.4.1",
8
- "@defrex/autobuild": "1.4.1",
7
+ "@defrex/autobuild-hosted-store-service": "1.4.2",
8
+ "@defrex/autobuild": "1.4.2",
9
9
  "next": "16.1.6",
10
10
  "react": "19.2.4",
11
11
  "react-dom": "19.2.4"