@defrex/autobuild 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +307 -27
  3. package/docs/accounts.md +38 -0
  4. package/docs/architecture.md +198 -25
  5. package/docs/build-store.md +18 -0
  6. package/docs/builds.md +5 -1
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +38 -19
  9. package/docs/dispatcher-hosting.md +42 -0
  10. package/docs/dispatcher.md +41 -0
  11. package/docs/forges.md +5 -0
  12. package/docs/integration-tree.md +8 -0
  13. package/docs/operating.md +11 -3
  14. package/docs/operator-api.md +37 -4
  15. package/docs/plugin-authoring.md +45 -1
  16. package/docs/remote-store-protocol.md +262 -42
  17. package/docs/remote-ticket-protocol.md +12 -10
  18. package/docs/restacking.md +60 -3
  19. package/docs/setup.md +37 -8
  20. package/docs/skills.md +1 -1
  21. package/docs/spec-standard.md +37 -3
  22. package/docs/troubleshooting.md +9 -0
  23. package/docs/workspaces.md +1 -1
  24. package/package.json +4 -3
  25. package/packages/core/src/accounts/availability.ts +96 -0
  26. package/packages/core/src/accounts/local-owner.ts +49 -2
  27. package/packages/core/src/cli/attention.ts +2 -0
  28. package/packages/core/src/cli/binary.ts +17 -1
  29. package/packages/core/src/cli/context.ts +62 -0
  30. package/packages/core/src/cli/dashboard/model.ts +12 -3
  31. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  32. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  33. package/packages/core/src/cli/dashboard/render.ts +46 -5
  34. package/packages/core/src/cli/dispatch-args.ts +27 -3
  35. package/packages/core/src/cli/dispatch-frontend.ts +187 -53
  36. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  38. package/packages/core/src/cli/dispatch-repository-feed.ts +45 -9
  39. package/packages/core/src/cli/dispatch.ts +145 -11
  40. package/packages/core/src/cli/harvest.ts +2 -1
  41. package/packages/core/src/cli/help.ts +16 -3
  42. package/packages/core/src/cli/historical-build-state.ts +6 -0
  43. package/packages/core/src/cli/main.ts +15 -2
  44. package/packages/core/src/cli/publication-settlement.ts +17 -0
  45. package/packages/core/src/cli/remote-poll.ts +11 -1
  46. package/packages/core/src/cli/repository-status.ts +11 -0
  47. package/packages/core/src/cli/status.ts +7 -1
  48. package/packages/core/src/cli/wait.ts +9 -2
  49. package/packages/core/src/cli/watch.ts +38 -3
  50. package/packages/core/src/config/roles.ts +16 -1
  51. package/packages/core/src/events/catalog.ts +7 -0
  52. package/packages/core/src/events/payloads.ts +85 -2
  53. package/packages/core/src/events/policy.ts +10 -0
  54. package/packages/core/src/events/repository.ts +35 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +189 -0
  56. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  57. package/packages/core/src/kernel/engine.ts +19 -12
  58. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  59. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  60. package/packages/core/src/kernel/log-index.ts +1 -1
  61. package/packages/core/src/kernel/node-landing.ts +27 -10
  62. package/packages/core/src/kernel/node-restack-demand.ts +1 -0
  63. package/packages/core/src/kernel/node-restack-state.ts +16 -1
  64. package/packages/core/src/kernel/node-restack-transaction.ts +14 -0
  65. package/packages/core/src/kernel/read-facts.ts +114 -9
  66. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  67. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  68. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  69. package/packages/core/src/kernel/reducer.ts +20 -2
  70. package/packages/core/src/kernel/replay-retention.ts +176 -0
  71. package/packages/core/src/kernel/target-lineage.ts +65 -0
  72. package/packages/core/src/kernel/target-observation.ts +117 -0
  73. package/packages/core/src/operator/registry.ts +5 -13
  74. package/packages/core/src/operator/tickets.ts +8 -2
  75. package/packages/core/src/plugin-sdk/index.ts +1 -0
  76. package/packages/core/src/ports/forge/fake.ts +22 -0
  77. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  78. package/packages/core/src/ports/forge/github.ts +42 -10
  79. package/packages/core/src/ports/forge/local-git.ts +16 -1
  80. package/packages/core/src/ports/types.ts +58 -4
  81. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  82. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  83. package/packages/core/src/ports/workspace/create.ts +2 -0
  84. package/packages/core/src/ports/workspace/distribution-archive.ts +14 -4
  85. package/packages/core/src/ports/workspace/fake.ts +4 -0
  86. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  87. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  88. package/packages/core/src/processes/build-runner.ts +240 -111
  89. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  90. package/packages/core/src/processes/dispatcher.ts +262 -80
  91. package/packages/core/src/processes/execution-no-progress.ts +7 -0
  92. package/packages/core/src/processes/harvest-runner.ts +6 -7
  93. package/packages/core/src/processes/publication-state.ts +2 -1
  94. package/packages/core/src/processes/repo-view.ts +22 -0
  95. package/packages/core/src/processes/tick-publication.ts +35 -47
  96. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  97. package/packages/core/src/scenarios/harness.ts +7 -0
  98. package/packages/core/src/store/adapter.ts +9 -0
  99. package/packages/core/src/store/build-scope.ts +28 -0
  100. package/packages/core/src/store/contract.ts +125 -0
  101. package/packages/core/src/store/event-reads.ts +156 -0
  102. package/packages/core/src/store/local/schema.ts +11 -0
  103. package/packages/core/src/store/local/store.ts +117 -2
  104. package/packages/core/src/store/memory.ts +237 -0
  105. package/packages/core/src/store/phase-session.ts +47 -0
  106. package/packages/core/src/store/reduced-reads.ts +8 -0
  107. package/packages/core/src/store/reducer-value-shapes.json +6262 -5227
  108. package/packages/core/src/store/reducer-value-validation.ts +3 -0
  109. package/packages/core/src/store/reducer-values.ts +62 -2
  110. package/packages/core/src/store/remote/client.ts +161 -16
  111. package/packages/core/src/store/remote/compatibility.ts +177 -46
  112. package/packages/core/src/store/remote/errors.ts +16 -0
  113. package/packages/core/src/store/remote/index.ts +11 -0
  114. package/packages/core/src/store/remote/protocol.ts +22 -0
  115. package/packages/core/src/store/remote/released-clients.json +48 -0
  116. package/packages/core/src/store/remote/released-clients.ts +88 -0
  117. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  118. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  119. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  120. package/packages/core/src/store/remote/version.ts +5 -2
  121. package/packages/core/src/store/repo-state-events.ts +4 -3
  122. package/packages/core/src/store/scan-cadence.ts +15 -0
  123. package/packages/core/src/store/session-handle.ts +18 -0
  124. package/packages/core/src/store/types.ts +27 -6
  125. package/packages/core/src/testing/dispatch-read-budget.ts +313 -2
  126. package/packages/core/src/testing/index.ts +5 -0
  127. package/packages/core/src/testing/reduced-read-budget.ts +728 -5
  128. package/skills/guide/SKILL.md +201 -18
  129. package/skills/guide/references/accounts.md +38 -0
  130. package/skills/guide/references/integration-tree.md +8 -0
  131. package/skills/guide/references/operator-api.md +37 -4
  132. package/skills/guide/references/plugin-authoring.md +45 -1
  133. package/skills/guide/references/remote-store-protocol.md +262 -42
  134. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  135. package/skills/guide/references/restacking.md +60 -3
  136. package/skills/guide/references/setup.md +37 -8
  137. package/skills/guide/references/spec-standard.md +37 -3
  138. package/skills/implement/SKILL.md +12 -3
  139. package/skills/operate/SKILL.md +87 -15
  140. package/skills/plan/SKILL.md +27 -4
  141. package/skills/plan-review/SKILL.md +22 -2
  142. package/skills/reconcile/SKILL.md +10 -1
  143. package/skills/spec/SKILL.md +7 -4
  144. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,6 @@
1
+ import { StoreWriteTooLargeError } from '../store/remote/errors'
2
+ import { observeTarget } from '../kernel/target-observation'
3
+ import { readBuildRange } from '../store/event-reads'
1
4
  import { accountRedactor, redactAccountStore } from '../store/account-redaction'
2
5
  import {
3
6
  capturedBuildConfig,
@@ -38,6 +41,7 @@ import { isRemoteWorkspace } from '../events/workspace-remote'
38
41
  import { withBuildTrailer } from '../kernel/build-identity'
39
42
  import {
40
43
  prepareRestack,
44
+ recoverLostCandidate,
41
45
  publishRestack,
42
46
  retainReplay,
43
47
  requireRewrite,
@@ -1220,6 +1224,7 @@ export class BuildRunner {
1220
1224
  return { kind: 'wait', reason: 'mixed-version' }
1221
1225
  const { store, slug } = this.deps
1222
1226
  try {
1227
+ await recoverLostCandidate(this.deps)
1223
1228
  await this.settleLocalReconcile()
1224
1229
  } catch (error) {
1225
1230
  if (error instanceof ForgeRequestDeferred)
@@ -1615,6 +1620,14 @@ export class BuildRunner {
1615
1620
  * again, preserving the execution-boundary freshness guarantee.
1616
1621
  */
1617
1622
  private async checkReconcileProgress(decision: CheckReconcileProgressDecision): Promise<void> {
1623
+ await this.withKernelPhaseFailure('reconcile', decision.nextAttempt, () =>
1624
+ this.checkReconcileProgressOperation(decision),
1625
+ )
1626
+ }
1627
+
1628
+ private async checkReconcileProgressOperation(
1629
+ decision: CheckReconcileProgressDecision,
1630
+ ): Promise<void> {
1618
1631
  const { nextAttempt } = decision
1619
1632
  const failures = await readPhaseFailures(
1620
1633
  this.deps.store,
@@ -1640,6 +1653,7 @@ export class BuildRunner {
1640
1653
  nextAttempt,
1641
1654
  failures.count,
1642
1655
  `failed to check reconcile progress: ${errorMessage(error)}`,
1656
+ !(error instanceof StoreWriteTooLargeError),
1643
1657
  )
1644
1658
  return
1645
1659
  }
@@ -1657,6 +1671,12 @@ export class BuildRunner {
1657
1671
 
1658
1672
  /** A core-phase run: retry guard (D5), started event (§15.3), session. */
1659
1673
  private async runPhase(decision: RunPhaseDecision): Promise<void> {
1674
+ await this.withKernelPhaseFailure(decision.phase, decision.round, () =>
1675
+ this.runPhaseOperation(decision),
1676
+ )
1677
+ }
1678
+
1679
+ private async runPhaseOperation(decision: RunPhaseDecision): Promise<void> {
1660
1680
  const { store, slug } = this.deps
1661
1681
  const { phase, round } = decision
1662
1682
 
@@ -1698,6 +1718,7 @@ export class BuildRunner {
1698
1718
  round,
1699
1719
  failures.count,
1700
1720
  `failed to refresh reconcile base: ${errorMessage(error)}`,
1721
+ !(error instanceof StoreWriteTooLargeError),
1701
1722
  )
1702
1723
  return
1703
1724
  }
@@ -1759,6 +1780,7 @@ export class BuildRunner {
1759
1780
  round,
1760
1781
  failures.count,
1761
1782
  `failed to prepare reconcile replay: ${errorMessage(error)}`,
1783
+ !(error instanceof StoreWriteTooLargeError),
1762
1784
  )
1763
1785
  return
1764
1786
  }
@@ -1793,6 +1815,15 @@ export class BuildRunner {
1793
1815
  const active = node.active!
1794
1816
  const conflict = node.conflict!
1795
1817
  const change = active.changes[conflict.index]!
1818
+ const failures = await readPhaseFailures(store, slug, 'reconcile', round)
1819
+ if (failures.count >= this.maxPhaseAttempts) {
1820
+ await this.raisePolicyExhausted('reconcile', round, failures)
1821
+ return
1822
+ }
1823
+ if (failures.lastWillRetry === false) {
1824
+ await this.raisePolicyNonRetryable('reconcile', round, failures)
1825
+ return
1826
+ }
1796
1827
  if (!this.recovery) {
1797
1828
  try {
1798
1829
  for (const sha of [active.expected, active.parent]) {
@@ -1848,6 +1879,7 @@ export class BuildRunner {
1848
1879
  if (result.kind !== 'conflict')
1849
1880
  throw new Error('reserved conflict no longer reproduces from frozen inputs')
1850
1881
  } catch (error) {
1882
+ if (error instanceof StoreWriteTooLargeError) throw error
1851
1883
  await store.append(slug, {
1852
1884
  actor: KERNEL,
1853
1885
  type: 'escalation.raised',
@@ -1866,11 +1898,6 @@ export class BuildRunner {
1866
1898
  payload: { attempt: round, baseSha: conflict.base },
1867
1899
  })
1868
1900
  }
1869
- const failures = await readPhaseFailures(store, slug, 'reconcile', round)
1870
- if (failures.count >= this.maxPhaseAttempts) {
1871
- await this.raisePolicyExhausted('reconcile', round, failures)
1872
- return
1873
- }
1874
1901
  await this.executeSession({
1875
1902
  phase: 'reconcile',
1876
1903
  round,
@@ -2003,6 +2030,10 @@ export class BuildRunner {
2003
2030
  await this.raisePolicyExhausted('reconcile', round, failures)
2004
2031
  return
2005
2032
  }
2033
+ if (failures.lastWillRetry === false) {
2034
+ await this.raisePolicyNonRetryable('reconcile', round, failures)
2035
+ return
2036
+ }
2006
2037
  try {
2007
2038
  await this.assertAutomaticRewriteOwnership()
2008
2039
  if (facts.log.restack.intent)
@@ -2019,17 +2050,11 @@ export class BuildRunner {
2019
2050
  let id: string
2020
2051
  let targetBase: string
2021
2052
  if (transaction === undefined) {
2022
- targetBase = await this.refreshReconcileBase()
2053
+ targetBase = await this.refreshReconcileBase(true)
2023
2054
  const branch = facts.lastCreated?.payload.baseBranch
2024
2055
  if (branch === undefined) throw new Error('missing frozen target')
2025
- if (facts.log.restack.target?.sha !== targetBase) {
2026
- await store.append(slug, {
2027
- actor: KERNEL,
2028
- type: 'target.moved',
2029
- payload: { branch, sha: targetBase },
2030
- })
2031
- facts = (await readBuildFacts(store, slug)).value
2032
- }
2056
+ // refreshReconcileBase admits the remote snapshot before any replay.
2057
+ facts = (await readBuildFacts(store, slug)).value
2033
2058
  const description = await store.getArtifact(slug, 'pr-description')
2034
2059
  const title =
2035
2060
  facts.lastCreated?.payload.ticket.title ?? facts.lastCreated?.payload.ticket.id ?? slug
@@ -2164,12 +2189,13 @@ export class BuildRunner {
2164
2189
  round,
2165
2190
  failures.count,
2166
2191
  `automatic restack failed: ${errorMessage(error)}`,
2192
+ !(error instanceof StoreWriteTooLargeError),
2167
2193
  )
2168
2194
  }
2169
2195
  }
2170
2196
 
2171
2197
  /** Snapshot the frozen target in a build-private ref without tracking-ref updates. */
2172
- private async refreshReconcileBase(): Promise<string> {
2198
+ private async refreshReconcileBase(recordAccepted = false): Promise<string> {
2173
2199
  const baseBranch = await readBuildSelector(this.deps.store, this.deps.slug, 'baseBranch')
2174
2200
  if (baseBranch === undefined) {
2175
2201
  throw new Error(
@@ -2190,6 +2216,7 @@ export class BuildRunner {
2190
2216
  `${this.deps.forge.name} base snapshot did not return a commit SHA: ${JSON.stringify(sha)}`,
2191
2217
  )
2192
2218
  }
2219
+ await this.admitReconcileBase(baseBranch, sha, recordAccepted)
2193
2220
  return sha
2194
2221
  }
2195
2222
 
@@ -2219,9 +2246,28 @@ export class BuildRunner {
2219
2246
  `${resolved.stderr.trim() || sha || '(no output)'}`,
2220
2247
  )
2221
2248
  }
2249
+ await this.admitReconcileBase(baseBranch, sha, recordAccepted)
2222
2250
  return sha
2223
2251
  }
2224
2252
 
2253
+ private async admitReconcileBase(
2254
+ branch: string,
2255
+ sha: string,
2256
+ recordAccepted: boolean,
2257
+ ): Promise<void> {
2258
+ const result = await observeTarget({
2259
+ store: this.deps.store,
2260
+ forge: this.deps.forge,
2261
+ slug: this.deps.slug,
2262
+ branch,
2263
+ sha,
2264
+ enforceUsedBaseline: true,
2265
+ recordAccepted,
2266
+ actor: KERNEL,
2267
+ })
2268
+ if (result === 'rejected') throw new Error(`upstream target rewrite on ${branch}: ${sha}`)
2269
+ }
2270
+
2225
2271
  /**
2226
2272
  * Resolve a conditional verifier against the live branch diff. Exclusion is
2227
2273
  * a canonical kernel-authored skip and launches no command or session.
@@ -2360,6 +2406,8 @@ export class BuildRunner {
2360
2406
  },
2361
2407
  )
2362
2408
  let decision: Decision = initial
2409
+ let drain = false
2410
+ let terminalDrain = false
2363
2411
  try {
2364
2412
  for (;;) {
2365
2413
  const observed = revision
@@ -2368,6 +2416,8 @@ export class BuildRunner {
2368
2416
  if (decision.kind === 'cancel-verify-stage') {
2369
2417
  await this.cancelVerifyStage(decision)
2370
2418
  await this.endCancelledVerifySessions(decision)
2419
+ } else {
2420
+ drain = terminalDrain
2371
2421
  }
2372
2422
  return
2373
2423
  }
@@ -2375,8 +2425,10 @@ export class BuildRunner {
2375
2425
  decision.members.some(
2376
2426
  (member) => !initial.members.some((first) => first.step === member.step),
2377
2427
  )
2378
- )
2428
+ ) {
2429
+ drain = terminalDrain
2379
2430
  return
2431
+ }
2380
2432
  const members = await Promise.all(
2381
2433
  decision.members.map((member) =>
2382
2434
  member.kind === 'evaluate-verify' ? this.resolveVerify(member) : member,
@@ -2436,11 +2488,20 @@ export class BuildRunner {
2436
2488
  wake = undefined
2437
2489
  const facts = (await readBuildFacts(store, slug)).value
2438
2490
  decision = decideNextFromFacts(facts.state, facts.log, await this.captureConfig())
2491
+ terminalDrain =
2492
+ facts.state.status === 'running' &&
2493
+ facts.state.pendingCommands.length === 0 &&
2494
+ [...inFlight.keys()].every((key) => facts.state.verifyStage.outcomes[key] !== undefined)
2495
+
2439
2496
  for (const entry of inFlight.values()) if (entry.error) throw entry.error
2440
2497
  }
2441
2498
  } finally {
2442
2499
  unsubscribe()
2443
2500
  this.deps.shutdownSignal?.removeEventListener('abort', onShutdown)
2501
+ // A terminal can precede the adapter return. Let normal agent settlement
2502
+ // close its bracket before stage-local shutdown can suspend it remotely.
2503
+ // Parent shutdown and session budgets remain active throughout this drain.
2504
+ if (drain) for (const entry of inFlight.values()) if (entry.agent) await entry.pending
2444
2505
  interrupted.abort()
2445
2506
  for (const entry of inFlight.values()) {
2446
2507
  // Fail-fast must reach whole-execution teardown even when an adapter
@@ -2505,12 +2566,27 @@ export class BuildRunner {
2505
2566
  /** Deterministic check (§8.2): NO session, NO CLI — the kernel runs the
2506
2567
  * command directly; a failure deposits the output tail as the report. */
2507
2568
  private async runCheck(decision: RunCheckDecision): Promise<void> {
2569
+ await this.withKernelPhaseFailure(verifyPhase(decision.step), decision.attempt, () =>
2570
+ this.runCheckOperation(decision),
2571
+ )
2572
+ }
2573
+
2574
+ private async runCheckOperation(decision: RunCheckDecision): Promise<void> {
2508
2575
  const { store, slug, exec, workspacePath } = this.deps
2509
2576
  const { step, command, attempt } = decision
2510
2577
  const current = (await readBuildFacts(store, slug)).value.state
2511
2578
  const memberKey = verifyMemberKey(step, attempt)
2512
2579
  if (current.verifyStage.outcomes[memberKey] || current.verifyStage.cancellations[memberKey])
2513
2580
  return
2581
+ const failures = await readPhaseFailures(store, slug, verifyPhase(step), attempt)
2582
+ if (failures.count >= this.maxPhaseAttempts) {
2583
+ await this.raisePolicyExhausted(verifyPhase(step), attempt, failures)
2584
+ return
2585
+ }
2586
+ if (failures.lastWillRetry === false) {
2587
+ await this.raisePolicyNonRetryable(verifyPhase(step), attempt, failures)
2588
+ return
2589
+ }
2514
2590
  const evidence = await this.verifyEvidence()
2515
2591
  if (!this.recovery)
2516
2592
  await store.append(slug, {
@@ -2571,6 +2647,12 @@ export class BuildRunner {
2571
2647
 
2572
2648
  /** Agent-verify step (§5): a session with a pass/fail/skip verdict. */
2573
2649
  private async runAgentVerify(decision: RunAgentVerifyDecision): Promise<void> {
2650
+ await this.withKernelPhaseFailure(verifyPhase(decision.step), decision.attempt, () =>
2651
+ this.runAgentVerifyOperation(decision),
2652
+ )
2653
+ }
2654
+
2655
+ private async runAgentVerifyOperation(decision: RunAgentVerifyDecision): Promise<void> {
2574
2656
  const { store, slug } = this.deps
2575
2657
  const { step, skill, attempt, feedback } = decision
2576
2658
  const evidence = await this.verifyEvidence()
@@ -3594,7 +3676,7 @@ export class BuildRunner {
3594
3676
  this.releaseLateStart(turn.pending, target.runner)
3595
3677
  }
3596
3678
 
3597
- const since = await store.getEvents(slug, preSeq)
3679
+ const since = await readBuildRange(store, slug, preSeq)
3598
3680
  const terminal = since.some(
3599
3681
  (event) =>
3600
3682
  spec.isTerminal(event) ||
@@ -3651,53 +3733,58 @@ export class BuildRunner {
3651
3733
  }
3652
3734
 
3653
3735
  if (terminal && handle !== undefined && result !== undefined) {
3654
- if (spec.producerPhase !== undefined && index === 0) {
3655
- this.producerSessions.set(spec.producerPhase, {
3656
- handle,
3657
- runner: owner,
3658
- route: primaryRoute,
3659
- })
3660
- const content = JSON.stringify(
3661
- {
3662
- session,
3663
- phase: spec.phase,
3664
- round: spec.round,
3665
- note: 'producer session kept live for §10 continuation; per-round turn transcript',
3666
- turn: {
3667
- text: result.text,
3668
- usage: result.usage,
3669
- prompt: this.interruptionPrompts.get(session),
3736
+ try {
3737
+ if (spec.producerPhase !== undefined && index === 0) {
3738
+ this.producerSessions.set(spec.producerPhase, {
3739
+ handle,
3740
+ runner: owner,
3741
+ route: primaryRoute,
3742
+ })
3743
+ const content = JSON.stringify(
3744
+ {
3745
+ session,
3746
+ phase: spec.phase,
3747
+ round: spec.round,
3748
+ note: 'producer session kept live for §10 continuation; per-round turn transcript',
3749
+ turn: {
3750
+ text: result.text,
3751
+ usage: result.usage,
3752
+ prompt: this.interruptionPrompts.get(session),
3753
+ },
3670
3754
  },
3671
- },
3672
- null,
3673
- 2,
3674
- )
3675
- await this.depositTranscriptAndEnd(
3676
- session,
3677
- bracket,
3678
- content,
3679
- result.usage,
3680
- target.model,
3681
- streamBracket !== undefined
3682
- ? { stream: streamBracket, outcome: 'completed' }
3683
- : undefined,
3684
- )
3685
- } else {
3686
- // An alternate producer must not become sticky across the review
3687
- // boundary. End it like any fresh session; the next round begins on
3688
- // the primary and rehydrates context from durable artifacts.
3689
- const transcript = await owner.end(handle)
3690
- await this.depositTranscriptAndEnd(
3691
- session,
3692
- bracket,
3693
- transcript.content,
3694
- transcript.metadata.usage,
3695
- transcript.metadata.model ?? target.model,
3696
- streamBracket !== undefined
3697
- ? { stream: streamBracket, outcome: 'completed' }
3698
- : undefined,
3699
- )
3700
- if (spec.producerPhase !== undefined) this.producerSessions.delete(spec.producerPhase)
3755
+ null,
3756
+ 2,
3757
+ )
3758
+ await this.depositTranscriptAndEnd(
3759
+ session,
3760
+ bracket,
3761
+ content,
3762
+ result.usage,
3763
+ target.model,
3764
+ streamBracket !== undefined
3765
+ ? { stream: streamBracket, outcome: 'completed' }
3766
+ : undefined,
3767
+ )
3768
+ } else {
3769
+ // An alternate producer must not become sticky across the review
3770
+ // boundary. End it like any fresh session; the next round begins on
3771
+ // the primary and rehydrates context from durable artifacts.
3772
+ const transcript = await owner.end(handle)
3773
+ await this.depositTranscriptAndEnd(
3774
+ session,
3775
+ bracket,
3776
+ transcript.content,
3777
+ transcript.metadata.usage,
3778
+ transcript.metadata.model ?? target.model,
3779
+ streamBracket !== undefined
3780
+ ? { stream: streamBracket, outcome: 'completed' }
3781
+ : undefined,
3782
+ )
3783
+ if (spec.producerPhase !== undefined) this.producerSessions.delete(spec.producerPhase)
3784
+ }
3785
+ } catch (error) {
3786
+ if (!(error instanceof StoreWriteTooLargeError)) throw error
3787
+ // The durable terminal remains authoritative over optional cleanup.
3701
3788
  }
3702
3789
  return
3703
3790
  }
@@ -3754,13 +3841,16 @@ export class BuildRunner {
3754
3841
  transcript.metadata.model ?? target.model,
3755
3842
  streamBracket !== undefined ? { stream: streamBracket, outcome: 'aborted' } : undefined,
3756
3843
  )
3757
- } catch {
3844
+ } catch (error) {
3845
+ if (error instanceof StoreWriteTooLargeError) turnError = error
3758
3846
  // A dead provider may leave no recoverable transcript.
3759
3847
  }
3760
3848
  }
3761
3849
  this.closeBracketStream(streamBracket, 'aborted')
3762
3850
  if (spec.producerPhase !== undefined) this.producerSessions.delete(spec.producerPhase)
3763
3851
 
3852
+ if (turnError instanceof StoreWriteTooLargeError) throw turnError
3853
+
3764
3854
  const failure: AgentTurnFailure =
3765
3855
  turnError !== undefined
3766
3856
  ? { message: errorMessage(turnError), permanent: false, cause: 'availability' }
@@ -3905,7 +3995,7 @@ export class BuildRunner {
3905
3995
  // The turn is over: what did the CLI leave in the log? Terminal = the
3906
3996
  // phase's terminal event for this round, or an `ab escalate` from this
3907
3997
  // session (§8.4: escalate is always an allowed terminal).
3908
- const since = await store.getEvents(slug, preSeq)
3998
+ const since = await readBuildRange(store, slug, preSeq)
3909
3999
  const terminal = since.some(
3910
4000
  (event) =>
3911
4001
  spec.isTerminal(event) ||
@@ -3968,49 +4058,59 @@ export class BuildRunner {
3968
4058
  }
3969
4059
 
3970
4060
  if (terminal && handle !== undefined && result !== undefined) {
3971
- if (spec.producerPhase !== undefined) {
3972
- // §10 memory: keep the handle live for the next round; the bracket
3973
- // closes with THIS turn's transcript (see module doc — ending the
3974
- // runner session would destroy the continuation every adapter needs).
3975
- this.producerSessions.set(spec.producerPhase, {
3976
- handle,
3977
- runner: live?.runner ?? runner,
3978
- route,
3979
- })
3980
- const content = JSON.stringify(
3981
- {
3982
- session,
3983
- phase: spec.phase,
3984
- round: spec.round,
3985
- note: 'producer session kept live for §10 continuation; ' + 'per-round turn transcript',
3986
- turn: {
3987
- text: result.text,
3988
- usage: result.usage,
3989
- prompt: this.interruptionPrompts.get(session),
4061
+ try {
4062
+ if (spec.producerPhase !== undefined) {
4063
+ // §10 memory: keep the handle live for the next round; the bracket
4064
+ // closes with THIS turn's transcript (see module doc — ending the
4065
+ // runner session would destroy the continuation every adapter needs).
4066
+ this.producerSessions.set(spec.producerPhase, {
4067
+ handle,
4068
+ runner: live?.runner ?? runner,
4069
+ route,
4070
+ })
4071
+ const content = JSON.stringify(
4072
+ {
4073
+ session,
4074
+ phase: spec.phase,
4075
+ round: spec.round,
4076
+ note:
4077
+ 'producer session kept live for §10 continuation; ' + 'per-round turn transcript',
4078
+ turn: {
4079
+ text: result.text,
4080
+ usage: result.usage,
4081
+ prompt: this.interruptionPrompts.get(session),
4082
+ },
3990
4083
  },
3991
- },
3992
- null,
3993
- 2,
3994
- )
3995
- await this.depositTranscriptAndEnd(
3996
- session,
3997
- bracket,
3998
- content,
3999
- result.usage,
4000
- model,
4001
- streamBracket !== undefined ? { stream: streamBracket, outcome: 'completed' } : undefined,
4002
- )
4003
- } else {
4004
- // Reviewer / agent-verify: single-run session, real transcript.
4005
- const transcript = await runner.end(handle)
4006
- await this.depositTranscriptAndEnd(
4007
- session,
4008
- bracket,
4009
- transcript.content,
4010
- transcript.metadata.usage,
4011
- transcript.metadata.model ?? model,
4012
- streamBracket !== undefined ? { stream: streamBracket, outcome: 'completed' } : undefined,
4013
- )
4084
+ null,
4085
+ 2,
4086
+ )
4087
+ await this.depositTranscriptAndEnd(
4088
+ session,
4089
+ bracket,
4090
+ content,
4091
+ result.usage,
4092
+ model,
4093
+ streamBracket !== undefined
4094
+ ? { stream: streamBracket, outcome: 'completed' }
4095
+ : undefined,
4096
+ )
4097
+ } else {
4098
+ // Reviewer / agent-verify: single-run session, real transcript.
4099
+ const transcript = await runner.end(handle)
4100
+ await this.depositTranscriptAndEnd(
4101
+ session,
4102
+ bracket,
4103
+ transcript.content,
4104
+ transcript.metadata.usage,
4105
+ transcript.metadata.model ?? model,
4106
+ streamBracket !== undefined
4107
+ ? { stream: streamBracket, outcome: 'completed' }
4108
+ : undefined,
4109
+ )
4110
+ }
4111
+ } catch (error) {
4112
+ if (!(error instanceof StoreWriteTooLargeError)) throw error
4113
+ // The durable terminal remains authoritative over optional cleanup.
4014
4114
  }
4015
4115
  return
4016
4116
  }
@@ -4075,7 +4175,8 @@ export class BuildRunner {
4075
4175
  transcript.metadata.model ?? model,
4076
4176
  streamBracket !== undefined ? { stream: streamBracket, outcome: 'aborted' } : undefined,
4077
4177
  )
4078
- } catch {
4178
+ } catch (error) {
4179
+ if (error instanceof StoreWriteTooLargeError) turnError = error
4079
4180
  // Transcript deposition can still fail. A later recovering runner
4080
4181
  // explicitly reclaims this open session before announcing attachment.
4081
4182
  }
@@ -4084,6 +4185,7 @@ export class BuildRunner {
4084
4185
  if (spec.producerPhase !== undefined) {
4085
4186
  this.producerSessions.delete(spec.producerPhase)
4086
4187
  }
4188
+ if (turnError instanceof StoreWriteTooLargeError) throw turnError
4087
4189
  const failure =
4088
4190
  turnError !== undefined
4089
4191
  ? { message: errorMessage(turnError), mayRetry: true }
@@ -4345,7 +4447,34 @@ export class BuildRunner {
4345
4447
  })
4346
4448
  }
4347
4449
 
4348
- private async failPhase(
4450
+ /** Only typed kernel write failures change disposition; persistence errors escape. */
4451
+ private async withKernelPhaseFailure(
4452
+ phase: Phase,
4453
+ round: number,
4454
+ operation: () => Promise<void>,
4455
+ ): Promise<void> {
4456
+ try {
4457
+ await operation()
4458
+ } catch (error) {
4459
+ if (!(error instanceof StoreWriteTooLargeError) || this.failurePersistenceErrors.has(error))
4460
+ throw error
4461
+ const failures = await readPhaseFailures(this.deps.store, this.deps.slug, phase, round)
4462
+ await this.failPhase(phase, round, failures.count, error.message, false)
4463
+ }
4464
+ }
4465
+
4466
+ private readonly failurePersistenceErrors = new WeakSet<Error>()
4467
+
4468
+ private async failPhase(...args: Parameters<BuildRunner['persistPhaseFailure']>): Promise<void> {
4469
+ try {
4470
+ await this.persistPhaseFailure(...args)
4471
+ } catch (error) {
4472
+ if (error instanceof Error) this.failurePersistenceErrors.add(error)
4473
+ throw error
4474
+ }
4475
+ }
4476
+
4477
+ private async persistPhaseFailure(
4349
4478
  phase: Phase,
4350
4479
  round: number,
4351
4480
  priorFailures: number,
@@ -4395,7 +4524,7 @@ export class BuildRunner {
4395
4524
  }
4396
4525
  }
4397
4526
 
4398
- /** A provider/runner-declared permanent failure parks immediately. The fact
4527
+ /** A permanent failure parks immediately. The fact
4399
4528
  * comes from the latest durable `phase.failed {willRetry:false}`, so a crash
4400
4529
  * between that write and this escalation resumes safely without attempt 2. */
4401
4530
  private async raisePolicyNonRetryable(
@@ -4418,7 +4547,7 @@ export class BuildRunner {
4418
4547
  policyCause: 'non-retryable-phase-failure',
4419
4548
  question:
4420
4549
  `${phase} round ${round} stopped after a non-retryable ` +
4421
- `provider/runner failure on attempt ${failures.count}; last error: ` +
4550
+ `failure on attempt ${failures.count}; last error: ` +
4422
4551
  `${failures.lastError ?? 'unknown'}` +
4423
4552
  providerAttemptSummary(failures.lastProviderAttempts),
4424
4553
  },
@@ -10,7 +10,7 @@ import { defineReducer } from '../kernel/incremental'
10
10
 
11
11
  export type OpenBuildWorkspace = EventPayload<'workspace.provisioned'>
12
12
 
13
- export const OPEN_BUILD_WORKSPACE_REDUCER_VERSION = 1
13
+ export const OPEN_BUILD_WORKSPACE_REDUCER_VERSION = 2
14
14
 
15
15
  /** Latest `workspace.provisioned` not followed by a `workspace.released` —
16
16
  * the reducer deliberately ignores workspace events (liveness is the
@@ -24,7 +24,8 @@ export const openBuildWorkspaceReducer = defineReducer<
24
24
  initial: () => ({ open: null }),
25
25
  fold(acc, events) {
26
26
  for (const event of events) {
27
- if (event.type === 'workspace.provisioned') acc.open = event.payload
27
+ if (event.type === 'workspace.provisioned' || event.type === 'workspace.cleanup-required')
28
+ acc.open = event.payload
28
29
  else if (event.type === 'workspace.released') acc.open = null
29
30
  }
30
31
  },