@defrex/autobuild 1.13.0 → 1.14.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 (42) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +38 -11
  3. package/docs/answering-blocked-builds.md +5 -3
  4. package/docs/architecture.md +12 -0
  5. package/docs/configuration.md +16 -8
  6. package/docs/operating.md +8 -0
  7. package/docs/operator-api.md +1 -1
  8. package/docs/operator-surfaces.md +1 -1
  9. package/docs/remote-store-protocol.md +1 -1
  10. package/docs/troubleshooting.md +16 -1
  11. package/package.json +3 -3
  12. package/packages/core/src/cli/dispatch.ts +21 -2
  13. package/packages/core/src/config/schema.ts +2 -2
  14. package/packages/core/src/events/policy.ts +1 -0
  15. package/packages/core/src/events/repository.ts +19 -0
  16. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +4 -0
  17. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/be211f0e31a65006.json.gz +0 -0
  18. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/312cc4090820a612.json +1078 -0
  19. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a2780567b4989fb6.json +105 -0
  20. package/packages/core/src/kernel/done-escalations.ts +8 -4
  21. package/packages/core/src/kernel/reducer-revisions.ts +4 -0
  22. package/packages/core/src/kernel/reducer.ts +15 -1
  23. package/packages/core/src/kernel/repository-read-facts.ts +9 -0
  24. package/packages/core/src/ports/workspace/build-execution.ts +9 -1
  25. package/packages/core/src/ports/workspace/vercel-sandbox.ts +99 -12
  26. package/packages/core/src/processes/dispatcher.ts +312 -33
  27. package/packages/core/src/processes/execution-settlement.ts +24 -3
  28. package/packages/core/src/processes/tick-publication.ts +1 -0
  29. package/packages/core/src/store/contract.ts +7 -0
  30. package/packages/core/src/store/reducer-value-shapes.json +5320 -5210
  31. package/packages/core/src/store/reducer-value-validation.ts +7 -0
  32. package/packages/core/src/store/remote/released-clients.json +11 -0
  33. package/packages/core/src/store/remote/released-reducer-values/1.14.0.json +36076 -0
  34. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  35. package/packages/core/src/store/repo-state-events.ts +1 -0
  36. package/packages/core/src/testing/dispatch-read-budget.ts +12 -2
  37. package/packages/core/src/testing/reduced-read-budget.ts +208 -1
  38. package/skills/guide/SKILL.md +18 -9
  39. package/skills/guide/references/operator-api.md +1 -1
  40. package/skills/guide/references/remote-store-protocol.md +1 -1
  41. package/skills/operate/SKILL.md +55 -5
  42. package/templates/hosted-service/package.json +2 -2
@@ -345,6 +345,7 @@ import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution
345
345
  import {
346
346
  attributeRecoveryStep,
347
347
  isRecoveryDeferred,
348
+ recoveryStepOf,
348
349
  type WorkspaceRecoveryStep,
349
350
  } from '../ports/workspace/recovery-step'
350
351
  import type {
@@ -675,6 +676,13 @@ export interface TickReport {
675
676
  * invocation's remaining budget was shorter than the provider's
676
677
  * provisioning estimate. Nothing is written; a later invocation starts it. */
677
678
  provisioningDeferred: number
679
+ /** Builds whose stopped-sandbox recovery, or a launch waiting on one, the
680
+ * invocation budget deferred this tick. Nothing is charged; the build is
681
+ * recorded in `dispatcher.work-deferred` and the next tick runs it first. */
682
+ recoveryDeferred: number
683
+ /** One line per build whose deadline-gated work (a provision or a recovery
684
+ * step) this tick deferred for budget, naming the step. */
685
+ deferredDiagnostics: string[]
678
686
  /** Dispatch (§12): builds created and launched. With durable supervision
679
687
  * this counts ACCEPTED dispatches — durable boundaries recorded — not
680
688
  * awaited launches: a dispatch whose remote provisioning continues in the
@@ -742,6 +750,8 @@ export function emptyTickReport(): TickReport {
742
750
  settled: 0,
743
751
  provisioning: 0,
744
752
  provisioningDeferred: 0,
753
+ recoveryDeferred: 0,
754
+ deferredDiagnostics: [],
745
755
  dispatched: 0,
746
756
  authored: 0,
747
757
  bounced: 0,
@@ -928,8 +938,22 @@ export interface TickOpts {
928
938
  * requests made through the budgeted adapters are cancelled by the same
929
939
  * signal. Absent ⇒ only `deadlineAt` bounds the tick. */
930
940
  workSignal?: AbortSignal
941
+ /** Bounded invocation's teardown write scope: runs one write under the
942
+ * cleanup phase's signal. A budget deferral noted after `workSignal`
943
+ * aborted (a recovery whose cleanup stop ran into the work deadline) still
944
+ * records its `dispatcher.work-deferred` hint through it, while the
945
+ * repository lease is held, so the next invocation serves it first. Absent
946
+ * ⇒ such a late hint write is skipped. */
947
+ teardownWrite?: <T>(write: () => Promise<T>) => Promise<T>
931
948
  }
932
949
 
950
+ /** Deadline-gated work a bounded invocation can defer for budget: a
951
+ * provision, or a stopped-sandbox recovery step. */
952
+ export type DeferredWorkStep = 'provision' | WorkspaceRecoveryStep
953
+
954
+ /** Most entries one `dispatcher.work-deferred` hint carries. */
955
+ const MAX_DEFERRED_WORK = 64
956
+
933
957
  /** Process-local launch coordination result. Durable lease acquisition remains
934
958
  * the BuildRunner's responsibility; "scheduled" means only that this process
935
959
  * accepted a runner launch rather than suppressing a known in-flight slug. */
@@ -1083,6 +1107,10 @@ export const SWEEP_PIN_CACHE_CAPACITY = 128
1083
1107
  /** Name the recovery step a workspace failure happened in. Missing account
1084
1108
  * credentials stay unwrapped: the dispatcher holds for them by type instead
1085
1109
  * of recording a failure. */
1110
+ function errorText(error: unknown): string {
1111
+ return error instanceof Error ? error.message : String(error)
1112
+ }
1113
+
1086
1114
  function stepAttributed(step: WorkspaceRecoveryStep, error: unknown): unknown {
1087
1115
  return error instanceof MissingAccountCredentialsError
1088
1116
  ? error
@@ -1338,6 +1366,25 @@ export class Dispatcher {
1338
1366
  /** Per tick, rebuilt from durable state: builds launched so far, which
1339
1367
  * occupy a slot before their runner claims a lease. */
1340
1368
  private tickLaunched: ReadonlySet<string> = new Set()
1369
+ /** Per tick, in insertion order: builds whose deadline-gated work this tick
1370
+ * deferred for budget, with the first step seen and an optional detail. */
1371
+ private readonly tickDeferrals = new Map<string, { step: DeferredWorkStep; detail?: string }>()
1372
+ /** Per tick: carried builds the early stage took up, which the lease sweep
1373
+ * then skips so no build is swept twice in one tick. */
1374
+ private readonly tickPrioritized = new Set<string>()
1375
+ /** Per tick, in carried order: the durable `dispatcher.work-deferred` hint
1376
+ * entries not yet retired. An entry leaves only through `retireCarried`,
1377
+ * after its own early-stage pass showed it no longer needs priority. */
1378
+ private readonly carriedOutstanding = new Map<
1379
+ string,
1380
+ { step: DeferredWorkStep; visited: boolean }
1381
+ >()
1382
+ /** The durable hint as last read or written. */
1383
+ private recordedDeferrals: { slug: string; step: DeferredWorkStep }[] = []
1384
+ /** The current tick's options, for writes made from deferral sites. */
1385
+ private tickOpts: TickOpts = {}
1386
+ /** Serializes hint writes so concurrent deferral notes never race. */
1387
+ private deferralWrites: Promise<void> = Promise.resolve()
1341
1388
  /** Per tick: finished leaves the admission gate turned away or deferred,
1342
1389
  * with their priority. Intake reserves their slots. */
1343
1390
  private readonly slotWaiters = new Map<string, BuildPriority>()
@@ -1443,8 +1490,9 @@ export class Dispatcher {
1443
1490
  }
1444
1491
 
1445
1492
  /**
1446
- * One cron-friendly pass (§3.3): janitor → interrupted dispatch recovery →
1447
- * optional startup resume → lease sweep → dispatch. Startup resume is opt-in
1493
+ * One cron-friendly pass (§3.3): deferred deadline-gated work → settlement →
1494
+ * janitor → interrupted dispatch recovery → optional startup resume →
1495
+ * lease sweep → dispatch. Startup resume is opt-in
1448
1496
  * because the CLI invokes it
1449
1497
  * once per command, while ordinary watch ticks must preserve policy parks.
1450
1498
  */
@@ -1579,6 +1627,7 @@ export class Dispatcher {
1579
1627
  ? this.deps.forge.withReadScope(() => this.runTick(opts))
1580
1628
  : this.runTick(opts))
1581
1629
  if (stop || this.deps.config.forge === 'local-git') report.forgeRequests = counts()
1630
+ this.finishDeferrals(report)
1582
1631
  report.janitorDiagnostics.push(...this.tickAbandonments)
1583
1632
  return report
1584
1633
  } catch (error) {
@@ -1627,6 +1676,11 @@ export class Dispatcher {
1627
1676
  this.startBarrier = undefined
1628
1677
  this.parkedSettled.clear()
1629
1678
  this.deferredAdmissions.clear()
1679
+ this.tickDeferrals.clear()
1680
+ this.tickPrioritized.clear()
1681
+ this.carriedOutstanding.clear()
1682
+ this.deferralWriteFailure = undefined
1683
+ this.tickOpts = opts
1630
1684
  this.admissionBoundary = false
1631
1685
  this.claimsEvaluated = false
1632
1686
  this.forcedDeferralKey = undefined
@@ -1634,6 +1688,14 @@ export class Dispatcher {
1634
1688
  // tick is observed by the next tick, never half-way through this one.
1635
1689
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
1636
1690
  if (opts.viewRefreshed !== true) await this.store.refresh()
1691
+ // The durable deferral hint from the previous invocation: zero extra
1692
+ // reads, it is part of the repository facts the refresh reduced.
1693
+ this.recordedDeferrals = (this.store.repositoryFacts().deferredWork?.builds ?? []).map(
1694
+ ({ slug, step }) => ({ slug, step }),
1695
+ )
1696
+ for (const { slug, step } of this.recordedDeferrals)
1697
+ if (!this.carriedOutstanding.has(slug))
1698
+ this.carriedOutstanding.set(slug, { step, visited: false })
1637
1699
  // A pending start request measures capacity from the facts this tick's
1638
1700
  // fleet-wide stages read anyway; keep them only then.
1639
1701
  this.store.retainBuildFacts(
@@ -1675,6 +1737,11 @@ export class Dispatcher {
1675
1737
  // open the first record listing of the next stage; each stage's own
1676
1738
  // per-iteration gate (below) covers a deadline that passes mid-stage.
1677
1739
  if (this.outOfBudget(opts)) return report
1740
+ // Stage −1 — DEFERRED WORK: builds whose provision or stopped-sandbox
1741
+ // recovery an earlier invocation deferred for budget are swept first,
1742
+ // while nearly the whole work window remains.
1743
+ if (!opts.observationOnly) await this.serviceDeferredWork(report, launched, paused, opts)
1744
+ if (this.outOfBudget(opts)) return report
1678
1745
  await this.settleForeignExecutions(report, opts)
1679
1746
  if (this.outOfBudget(opts)) return report
1680
1747
  await this.settleHarvestExecutions(opts)
@@ -2684,7 +2751,16 @@ export class Dispatcher {
2684
2751
  ) {
2685
2752
  return 'already-active'
2686
2753
  }
2687
- return this.deps.launchRunner(slug)
2754
+ try {
2755
+ return await this.deps.launchRunner(slug)
2756
+ } catch (error) {
2757
+ // A launch waiting on a stopped-sandbox recovery the budget deferred:
2758
+ // nothing started and nothing is charged. Record it so the next
2759
+ // invocation runs it first; callers see the same result as before.
2760
+ if (!isRecoveryDeferred(error)) throw error
2761
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? 'resume', errorText(error))
2762
+ return 'already-active'
2763
+ }
2688
2764
  }
2689
2765
 
2690
2766
  // ── 0. Settlement stage (durable supervision) ──────────────────────────────
@@ -2706,6 +2782,8 @@ export class Dispatcher {
2706
2782
  const active = this.deps.activeExecutions?.() ?? new Set<string>()
2707
2783
  for (const record of await this.workBuilds()) {
2708
2784
  if (active.has(record.slug)) continue
2785
+ // The early stage already observed and settled it this tick.
2786
+ if (this.tickPrioritized.has(record.slug)) continue
2709
2787
  // Budget gate: once spent, stop settling further foreign executions.
2710
2788
  if (this.outOfBudget(opts)) break
2711
2789
  try {
@@ -2722,14 +2800,18 @@ export class Dispatcher {
2722
2800
  ...(this.settlePublication !== undefined
2723
2801
  ? { settlePublication: this.settlePublication }
2724
2802
  : {}),
2803
+ onDeferred: (slug, step, detail) => this.noteDeferral(slug, step, detail),
2725
2804
  },
2726
2805
  record.slug,
2727
2806
  open,
2728
2807
  )
2729
2808
  if (settlement === 'settled') report.settled += 1
2730
- } catch {
2809
+ } catch (error) {
2731
2810
  // An unobservable build must not stall settlement of the rest; the
2732
- // next tick retries it.
2811
+ // next tick retries it. A budget deferral is recorded so the next
2812
+ // invocation observes it first.
2813
+ if (isRecoveryDeferred(error))
2814
+ await this.noteDeferral(record.slug, recoveryStepOf(error) ?? 'resume', errorText(error))
2733
2815
  }
2734
2816
  }
2735
2817
  }
@@ -3049,8 +3131,14 @@ export class Dispatcher {
3049
3131
  estimate !== undefined &&
3050
3132
  this.tickDeadlineAt !== undefined &&
3051
3133
  this.tickDeadlineAt - this.deps.clock().getTime() < estimate
3052
- )
3134
+ ) {
3135
+ await this.noteDeferral(
3136
+ slug,
3137
+ 'provision',
3138
+ `${Math.max(0, this.tickDeadlineAt - this.deps.clock().getTime())} ms remain but a provision needs about ${estimate} ms`,
3139
+ )
3053
3140
  return 'budget-wait'
3141
+ }
3054
3142
  // A finished leaf waits for a slot before its continuation reserves one.
3055
3143
  // Nothing is written: the wait costs no attempt and raises no attention.
3056
3144
  if (tail === 'launch' && (await this.leafAdmission(slug)) !== 'admit') return 'slot-wait'
@@ -3644,6 +3732,8 @@ export class Dispatcher {
3644
3732
  payload: {},
3645
3733
  })
3646
3734
  if (command.command === 'abort') {
3735
+ // The abort ended the janitor episode (§15.5).
3736
+ previous = undefined
3647
3737
  operation = 'abort cleanup'
3648
3738
  await this.cleanupAborted(record, await history(), report)
3649
3739
  }
@@ -3754,6 +3844,8 @@ export class Dispatcher {
3754
3844
  type: 'build.aborted',
3755
3845
  payload: {},
3756
3846
  } satisfies EventWrite<'build.aborted'>)
3847
+ // The abort ended the janitor episode (§15.5).
3848
+ previous = undefined
3757
3849
  // The view folded the acknowledgement it just appended.
3758
3850
  loaded = undefined
3759
3851
  operation = 'abort cleanup'
@@ -3887,6 +3979,12 @@ export class Dispatcher {
3887
3979
  // this build's janitor episode.
3888
3980
  if (janitorDeferral(error)) {
3889
3981
  attempted = false
3982
+ if (isRecoveryDeferred(error))
3983
+ await this.noteDeferral(
3984
+ record.slug,
3985
+ recoveryStepOf(error) ?? 'cleanup',
3986
+ errorText(error),
3987
+ )
3890
3988
  return
3891
3989
  }
3892
3990
  if (error instanceof MixedVersionDeferral) {
@@ -4479,12 +4577,11 @@ export class Dispatcher {
4479
4577
  }
4480
4578
  } catch (error) {
4481
4579
  rethrowAuthorityLapse(error)
4482
- if (
4483
- error instanceof ForgeRequestDeferred ||
4484
- error instanceof MixedVersionDeferral ||
4485
- isRecoveryDeferred(error)
4486
- )
4580
+ if (isRecoveryDeferred(error)) {
4581
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? 'resume', errorText(error))
4487
4582
  continue
4583
+ }
4584
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
4488
4585
  if (error instanceof ForgeCooldown) throw error
4489
4586
  const message =
4490
4587
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
@@ -7396,8 +7493,11 @@ export class Dispatcher {
7396
7493
  // build's failure; the tick-level handlers own it.
7397
7494
  if (error instanceof ForgeCooldown || error instanceof MixedVersionDeferral) throw error
7398
7495
  // The invocation deadline cut recovery short: nothing failed, so keep
7399
- // the workspace and record nothing; the next invocation retries.
7400
- if (isRecoveryDeferred(error)) return false
7496
+ // the workspace and charge nothing; the next invocation runs it first.
7497
+ if (isRecoveryDeferred(error)) {
7498
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? step, errorText(error))
7499
+ return false
7500
+ }
7401
7501
  // Any other preservation or settlement failure (an unknown fence, a
7402
7502
  // checkout that could not be inspected) retains the workspace and its
7403
7503
  // pending work and is attributed to this build, never to the tick.
@@ -7444,7 +7544,10 @@ export class Dispatcher {
7444
7544
  rethrowAuthorityLapse(error)
7445
7545
  // A cleanup the invocation deadline cut short is retried next time; it
7446
7546
  // is neither a cleanup attempt nor a failure.
7447
- if (isRecoveryDeferred(error)) return false
7547
+ if (isRecoveryDeferred(error)) {
7548
+ await this.noteDeferral(slug, recoveryStepOf(error) ?? 'cleanup', errorText(error))
7549
+ return false
7550
+ }
7448
7551
  const failure = stepAttributed('cleanup', error)
7449
7552
  const message =
7450
7553
  failure instanceof Error || isForgeFailure(failure) ? failure.message : String(failure)
@@ -8417,26 +8520,190 @@ export class Dispatcher {
8417
8520
  if (digest.waitPending && digest.kind !== 'node')
8418
8521
  await this.serviceWaitRequests(record, report)
8419
8522
  if (launched.has(record.slug)) continue
8523
+ // The early stage already swept it this tick.
8524
+ if (this.tickPrioritized.has(record.slug)) continue
8525
+ await this.sweepContained(record, report, launched, paused, now)
8526
+ }
8527
+ }
8528
+
8529
+ /** One build's lease-sweep pass under the sweep's per-build containment:
8530
+ * one build's failure never stops the caller from advancing the others.
8531
+ * Workspace failures are already durable against the build; a
8532
+ * repository-wide cooldown or an authority lapse still ends the tick.
8533
+ * `waiting` is a try-again-later outcome (a forge, mixed-version or budget
8534
+ * deferral); `failed` is a contained failure reported in diagnostics. */
8535
+ private async sweepContained(
8536
+ record: BuildRecord,
8537
+ report: TickReport,
8538
+ launched: Set<string>,
8539
+ paused: boolean,
8540
+ now: number,
8541
+ ): Promise<'done' | 'waiting' | 'failed'> {
8542
+ try {
8543
+ return await this.sweepBuild(record, report, launched, paused, now)
8544
+ } catch (error) {
8545
+ rethrowAuthorityLapse(error)
8546
+ if (isRecoveryDeferred(error)) {
8547
+ await this.noteDeferral(record.slug, recoveryStepOf(error) ?? 'resume', errorText(error))
8548
+ return 'waiting'
8549
+ }
8550
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral)
8551
+ return 'waiting'
8552
+ if (error instanceof ForgeCooldown) throw error
8553
+ const message =
8554
+ error instanceof Error || isForgeFailure(error) ? error.message : String(error)
8555
+ report.janitorFailed += 1
8556
+ report.janitorDiagnostics.push(`build ${record.slug}: lease sweep failed — ${message}`)
8557
+ return 'failed'
8558
+ }
8559
+ }
8560
+
8561
+ /**
8562
+ * Stage −1 — deferred deadline-gated work. Builds the previous invocation
8563
+ * recorded in `dispatcher.work-deferred` (a provision or a stopped-sandbox
8564
+ * recovery the budget deferred) get the ordinary `sweepBuild` pass first,
8565
+ * before settlement and the janitor spend the window. The hint is never
8566
+ * authority: each pass re-derives every decision from fresh build state,
8567
+ * and a stale entry does nothing and is retired.
8568
+ *
8569
+ * Per-tick cost: zero reads when nothing is carried (the hint comes from
8570
+ * the repository facts the tick already reduced). Otherwise the record
8571
+ * listing and digests from this tick's epoch cache, with no fleet-wide
8572
+ * compatibility pass, plus one reduced `buildFacts` read per carried build
8573
+ * visited — a read the lease sweep would otherwise make later, and which
8574
+ * it now skips. Writes: at most one hint append when the list changes.
8575
+ */
8576
+ private async serviceDeferredWork(
8577
+ report: TickReport,
8578
+ launched: Set<string>,
8579
+ paused: boolean,
8580
+ opts: TickOpts,
8581
+ ): Promise<void> {
8582
+ if (this.carriedOutstanding.size === 0) return
8583
+ // Never the default form: it would run the mixed-version check for every
8584
+ // compatibility-bearing build. `sweepBuild` checks each carried build.
8585
+ const entries = new Map(
8586
+ (await this.repoBuildDigests(true)).map((entry) => [entry.record.slug, entry]),
8587
+ )
8588
+ for (const slug of [...this.carriedOutstanding.keys()]) {
8589
+ if (this.outOfBudget(opts)) break
8590
+ const entry = this.carriedOutstanding.get(slug)!
8591
+ const found = entries.get(slug)
8592
+ if (found === undefined || found.digest.terminal !== undefined) {
8593
+ this.retireCarried(slug)
8594
+ continue
8595
+ }
8596
+ entry.visited = true
8597
+ this.tickPrioritized.add(slug)
8598
+ if (launched.has(slug)) {
8599
+ this.retireCarried(slug)
8600
+ continue
8601
+ }
8602
+ const outcome = await this.sweepContained(
8603
+ found.record,
8604
+ report,
8605
+ launched,
8606
+ paused,
8607
+ this.deps.clock().getTime(),
8608
+ )
8609
+ const interrupted = this.budgetSpent(opts)
8610
+ if (outcome !== 'waiting' && !interrupted && !this.tickDeferrals.has(slug))
8611
+ this.retireCarried(slug)
8612
+ }
8613
+ await this.persistDeferrals()
8614
+ }
8615
+
8616
+ /** A carried hint entry whose own pass showed it no longer needs priority.
8617
+ * Never writes: the next hint write simply omits it. */
8618
+ private retireCarried(slug: string): void {
8619
+ this.carriedOutstanding.delete(slug)
8620
+ }
8621
+
8622
+ /** Record that this tick deferred `slug`'s deadline-gated `step` for
8623
+ * budget, and keep the durable hint current. */
8624
+ private async noteDeferral(slug: string, step: DeferredWorkStep, detail?: string): Promise<void> {
8625
+ if (!this.tickDeferrals.has(slug))
8626
+ this.tickDeferrals.set(slug, { step, ...(detail !== undefined ? { detail } : {}) })
8627
+ await this.persistDeferrals()
8628
+ }
8629
+
8630
+ /** The hint this tick would write: unvisited carried entries first, in
8631
+ * carried order; then visited carried entries that are still outstanding
8632
+ * (re-deferred or interrupted); then this tick's new deferrals. Capped
8633
+ * from the tail, so new entries are dropped first. */
8634
+ private nextDeferralList(): { slug: string; step: DeferredWorkStep }[] {
8635
+ const list: { slug: string; step: DeferredWorkStep }[] = []
8636
+ const seen = new Set<string>()
8637
+ const push = (slug: string, step: DeferredWorkStep) => {
8638
+ if (seen.has(slug)) return
8639
+ seen.add(slug)
8640
+ list.push({ slug, step })
8641
+ }
8642
+ for (const [slug, entry] of this.carriedOutstanding) if (!entry.visited) push(slug, entry.step)
8643
+ for (const [slug, entry] of this.carriedOutstanding)
8644
+ if (entry.visited) push(slug, this.tickDeferrals.get(slug)?.step ?? entry.step)
8645
+ for (const [slug, { step }] of this.tickDeferrals) push(slug, step)
8646
+ return list.slice(0, MAX_DEFERRED_WORK)
8647
+ }
8648
+
8649
+ /** Append the merged hint when it differs from the one last read or
8650
+ * written. Every write keeps every unretired carried entry, so a pass cut
8651
+ * short at any point leaves a durable superset of what still needs
8652
+ * priority. A deferral noted after the work signal aborted is written in
8653
+ * the tick's teardown scope. Best effort: a failure costs only the hint. */
8654
+ private persistDeferrals(): Promise<void> {
8655
+ const write = this.deferralWrites.then(async () => {
8656
+ const next = this.nextDeferralList()
8657
+ const recorded = this.recordedDeferrals
8658
+ if (
8659
+ next.length === recorded.length &&
8660
+ next.every(
8661
+ (entry, i) => entry.slug === recorded[i]!.slug && entry.step === recorded[i]!.step,
8662
+ )
8663
+ )
8664
+ return
8665
+ if (this.deps.holdsRepoAuthority?.() === false) return
8666
+ // Past the work deadline, abandoned work writes nothing, except this
8667
+ // hint through the bounded, authorized teardown scope.
8668
+ const late = this.tickOpts.workSignal?.aborted === true
8669
+ const teardown = this.tickOpts.teardownWrite
8670
+ if (late && teardown === undefined) return
8671
+ const append = () =>
8672
+ this.store.appendRepo(this.deps.repo, {
8673
+ actor: DISPATCHER,
8674
+ type: 'dispatcher.work-deferred',
8675
+ payload: { builds: next },
8676
+ })
8420
8677
  try {
8421
- await this.sweepBuild(record, report, launched, paused, now)
8678
+ await (late ? teardown!(append) : append())
8679
+ this.recordedDeferrals = next
8422
8680
  } catch (error) {
8423
8681
  rethrowAuthorityLapse(error)
8424
- // Per-build containment: one build's failure never stops the sweep
8425
- // from advancing the others. Workspace failures are already durable
8426
- // against the build; a repository-wide cooldown still ends the tick.
8427
- if (
8428
- error instanceof ForgeRequestDeferred ||
8429
- error instanceof MixedVersionDeferral ||
8430
- isRecoveryDeferred(error)
8431
- )
8432
- continue
8433
- if (error instanceof ForgeCooldown) throw error
8434
- const message =
8435
- error instanceof Error || isForgeFailure(error) ? error.message : String(error)
8436
- report.janitorFailed += 1
8437
- report.janitorDiagnostics.push(`build ${record.slug}: lease sweep failed — ${message}`)
8682
+ this.deferralWriteFailure = errorText(error)
8438
8683
  }
8684
+ })
8685
+ this.deferralWrites = write.catch(() => {})
8686
+ return write
8687
+ }
8688
+
8689
+ /** A hint write failure this tick, reported once in the tick's diagnostics. */
8690
+ private deferralWriteFailure: string | undefined
8691
+
8692
+ /** Count and name this tick's deferrals on its report. Runs in `tick()`,
8693
+ * so every early return of `runTick` is covered. */
8694
+ private finishDeferrals(report: TickReport): void {
8695
+ for (const [slug, { step, detail }] of this.tickDeferrals) {
8696
+ if (step !== 'provision') report.recoveryDeferred += 1
8697
+ report.deferredDiagnostics.push(
8698
+ `build ${slug}: ${step} deferred by the invocation budget; the next invocation runs it first` +
8699
+ (detail !== undefined ? ` — ${detail}` : ''),
8700
+ )
8439
8701
  }
8702
+ if (this.deferralWriteFailure !== undefined)
8703
+ report.deferredDiagnostics.push(
8704
+ `deferred work not recorded for the next invocation — ${this.deferralWriteFailure}`,
8705
+ )
8706
+ this.deferralWriteFailure = undefined
8440
8707
  }
8441
8708
 
8442
8709
  /**
@@ -8489,22 +8756,33 @@ export class Dispatcher {
8489
8756
  })
8490
8757
  }
8491
8758
 
8492
- /** One build's lease-sweep pass; `leaseSweep` contains its failures. */
8759
+ /** One build's lease-sweep pass; `sweepContained` contains its failures.
8760
+ * Resolves `waiting` when a mixed-version deferral holds the build, and
8761
+ * `done` otherwise. */
8493
8762
  private async sweepBuild(
8494
8763
  record: BuildRecord,
8495
8764
  report: TickReport,
8496
8765
  launched: Set<string>,
8497
8766
  paused: boolean,
8498
8767
  now: number,
8499
- ): Promise<void> {
8768
+ ): Promise<'done' | 'waiting'> {
8769
+ return (await this.sweepBuildPass(record, report, launched, paused, now)) ?? 'done'
8770
+ }
8771
+
8772
+ private async sweepBuildPass(
8773
+ record: BuildRecord,
8774
+ report: TickReport,
8775
+ launched: Set<string>,
8776
+ paused: boolean,
8777
+ now: number,
8778
+ ): Promise<'waiting' | undefined> {
8500
8779
  if (record.lease) {
8501
8780
  if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
8502
8781
  }
8503
8782
  const facts = await this.store.buildFacts(record.slug)
8504
8783
  const state = facts.state
8505
8784
  if (mixedVersionDeferred(state)) {
8506
- await deferMixedVersion(this.store, record.slug)
8507
- return
8785
+ return (await deferMixedVersion(this.store, record.slug)) ? 'waiting' : undefined
8508
8786
  }
8509
8787
  // The janitor owns this abort: a sweep must never reap, provision or
8510
8788
  // launch a runner only to acknowledge it.
@@ -8640,6 +8918,7 @@ export class Dispatcher {
8640
8918
  ...(this.settlePublication !== undefined
8641
8919
  ? { settlePublication: this.settlePublication }
8642
8920
  : {}),
8921
+ onDeferred: (slug, step, detail) => this.noteDeferral(slug, step, detail),
8643
8922
  },
8644
8923
  record.slug,
8645
8924
  foreignExecution,
@@ -19,6 +19,11 @@ import type {
19
19
  BuildExecutionIdentity,
20
20
  ExecutionObservation,
21
21
  } from '../ports/workspace/build-execution'
22
+ import {
23
+ isRecoveryDeferred,
24
+ recoveryStepOf,
25
+ type WorkspaceRecoveryStep,
26
+ } from '../ports/workspace/recovery-step'
22
27
  import { readBuildFacts } from '../store/reduced-reads'
23
28
  import { defineReducer } from '../kernel/incremental'
24
29
  import type { BuildStore } from '../store/types'
@@ -130,6 +135,10 @@ export interface ExecutionSettlementDeps {
130
135
  execution: BuildExecution
131
136
  /** Trusted publication settlement, invoked only after a recorded completion. */
132
137
  settlePublication?: (slug: string) => Promise<void>
138
+ /** Told when the invocation budget deferred the observation (a `running`
139
+ * observation marked `deferred`, or a thrown recovery deferral). Settlement
140
+ * still returns `running`: a deferral is never exit or loss. */
141
+ onDeferred?: (slug: string, step: WorkspaceRecoveryStep, detail: string) => Promise<void> | void
133
142
  }
134
143
 
135
144
  /** Release the open execution's exact lease, but only while that instance
@@ -162,7 +171,9 @@ export function settleExecution(
162
171
  /** `settleExecution` over an already-derived open execution, for callers that
163
172
  * hold the projection (a reducer snapshot advanced to the log tail) and so
164
173
  * never need the event array. A `running` result or an observation error
165
- * touches no event rows unless the provider also reports actionable attention. */
174
+ * touches no event rows unless the provider also reports actionable attention.
175
+ * An observation the invocation budget deferred reaches `deps.onDeferred`
176
+ * with its step and still reads as `running`. */
166
177
  export async function settleOpenExecution(
167
178
  deps: ExecutionSettlementDeps,
168
179
  slug: string,
@@ -173,7 +184,13 @@ export async function settleOpenExecution(
173
184
  let observation: ExecutionObservation
174
185
  try {
175
186
  observation = await deps.execution.observe(observationIdentity(open))
176
- } catch {
187
+ } catch (error) {
188
+ if (isRecoveryDeferred(error))
189
+ await deps.onDeferred?.(
190
+ slug,
191
+ recoveryStepOf(error) ?? 'resume',
192
+ error instanceof Error ? error.message : String(error),
193
+ )
177
194
  return 'running'
178
195
  }
179
196
  if (observation.attention) {
@@ -192,7 +209,11 @@ export async function settleOpenExecution(
192
209
  },
193
210
  })
194
211
  }
195
- if (observation.state === 'running') return 'running'
212
+ if (observation.state === 'running') {
213
+ if (observation.deferred)
214
+ await deps.onDeferred?.(slug, observation.deferred.step, observation.deferred.detail)
215
+ return 'running'
216
+ }
196
217
 
197
218
  const request = (await readBuildFacts(deps.store, slug)).value.state.drainingExecutions?.[
198
219
  open.instance
@@ -29,6 +29,7 @@ function reportRequiresPublication(
29
29
  if (report[key] !== (previous.payload.counters[key] ?? 0)) return true
30
30
  // Reported once per occurrence, never standing: any one is activity.
31
31
  if (report.agentContextDiagnostics.length > 0) return true
32
+ if (report.deferredDiagnostics.length > 0) return true
32
33
  for (const key of diagnostics) {
33
34
  const before = previous.payload[key] ?? []
34
35
  if (report[key].length !== before.length || report[key].some((value, i) => value !== before[i]))
@@ -1576,6 +1576,7 @@ export function describeBuildStoreContract(name: string, factory: BuildStoreFact
1576
1576
  creationDiagnostics,
1577
1577
  dependencyDiagnostics,
1578
1578
  agentContextDiagnostics,
1579
+ deferredDiagnostics,
1579
1580
  ...counters
1580
1581
  } = emptyTickReport()
1581
1582
  for (let i = 0; i < 20; i++) {
@@ -2286,6 +2287,12 @@ export function describeBuildStoreContract(name: string, factory: BuildStoreFact
2286
2287
  await complete(store, 'de-late')
2287
2288
  await raise(store, 'de-aborted')
2288
2289
  await store.append('de-aborted', { actor: KERNEL, type: 'build.aborted', payload: {} })
2290
+ // The abort closed its escalation, so cleanup's completion lists nothing.
2291
+ await store.append('de-aborted', {
2292
+ actor: DISPATCHER,
2293
+ type: 'build.completed',
2294
+ payload: { outcome: 'abandoned' },
2295
+ })
2289
2296
  await complete(store, 'de-plain')
2290
2297
  expect((await read(store)).builds).toEqual([])
2291
2298
  await raise(store, 'de-late')