@defrex/autobuild 1.19.0 → 1.20.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 (55) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +53 -9
  3. package/docs/architecture.md +23 -7
  4. package/docs/assets/headline-wide.png +0 -0
  5. package/docs/dispatcher.md +1 -1
  6. package/docs/merge-policy.md +2 -1
  7. package/docs/operator-surfaces.md +1 -1
  8. package/docs/plugin-authoring.md +11 -4
  9. package/docs/process-ownership.md +43 -0
  10. package/docs/remote-store-protocol.md +7 -0
  11. package/docs/restacking.md +11 -2
  12. package/docs/setup.md +7 -2
  13. package/docs/verification.md +1 -1
  14. package/package.json +3 -3
  15. package/packages/core/src/cli/dashboard/model.ts +1 -0
  16. package/packages/core/src/cli/dashboard/vocabulary.ts +3 -0
  17. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +1 -0
  18. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3f0c4e6d1d54e5bf.json +92 -0
  19. package/packages/core/src/kernel/dispatch-capacity.ts +15 -3
  20. package/packages/core/src/kernel/engine.ts +15 -2
  21. package/packages/core/src/kernel/janitor-failure.ts +1 -0
  22. package/packages/core/src/kernel/reducer-revisions.ts +1 -0
  23. package/packages/core/src/processes/build-runner.ts +67 -7
  24. package/packages/core/src/processes/check-termination.ts +44 -0
  25. package/packages/core/src/processes/dispatcher.ts +131 -18
  26. package/packages/core/src/processes/publication-loss.ts +29 -0
  27. package/packages/core/src/processes/repo-view.ts +2 -1
  28. package/packages/core/src/store/contract.ts +43 -0
  29. package/packages/core/src/store/digest.ts +19 -1
  30. package/packages/core/src/store/reducer-value-shapes.json +8 -0
  31. package/packages/core/src/store/remote/protocol.ts +3 -0
  32. package/packages/core/src/store/remote/released-clients.json +11 -0
  33. package/packages/core/src/store/remote/released-reducer-values/1.20.0.json +36469 -0
  34. package/packages/core/src/store/remote/released-reducer-values/index.ts +16 -14
  35. package/packages/core/src/store/types.ts +5 -0
  36. package/packages/core/src/testing/reduced-read-budget.ts +131 -0
  37. package/skills/code-review/SKILL.md +5 -0
  38. package/skills/finalize/SKILL.md +5 -0
  39. package/skills/guide/SKILL.md +18 -7
  40. package/skills/guide/references/merge-policy.md +2 -1
  41. package/skills/guide/references/plugin-authoring.md +11 -4
  42. package/skills/guide/references/process-ownership.md +43 -0
  43. package/skills/guide/references/remote-store-protocol.md +7 -0
  44. package/skills/guide/references/restacking.md +11 -2
  45. package/skills/guide/references/setup.md +7 -2
  46. package/skills/harvest/SKILL.md +5 -0
  47. package/skills/harvest-review/SKILL.md +5 -0
  48. package/skills/implement/SKILL.md +5 -0
  49. package/skills/judge/SKILL.md +4 -0
  50. package/skills/operate/SKILL.md +5 -0
  51. package/skills/plan/SKILL.md +5 -0
  52. package/skills/plan-review/SKILL.md +5 -0
  53. package/skills/propose/SKILL.md +5 -0
  54. package/skills/reconcile/SKILL.md +5 -0
  55. package/templates/hosted-service/package.json +2 -2
@@ -243,7 +243,12 @@ export function decideNextFromFacts(state: BuildState, log: LogIndex, config: Co
243
243
  // A requested measurement runs only once the pipeline has nothing else to
244
244
  // do, so restack, re-verify and reconcile keep their precedence over it. A
245
245
  // request whose baseline a later `target.moved` superseded runs nothing.
246
- if (decision.kind === 'wait' && decision.reason === 'awaiting-pr' && state.kind !== 'node') {
246
+ if (
247
+ decision.kind === 'wait' &&
248
+ decision.reason === 'awaiting-pr' &&
249
+ state.kind !== 'node' &&
250
+ state.prState !== 'merged'
251
+ ) {
247
252
  const request = pendingMeasurementRequest(state)
248
253
  if (request !== undefined) return { kind: 'run-measurement', request }
249
254
  }
@@ -310,6 +315,12 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
310
315
  return { kind: 'acknowledge', command: 'pause' }
311
316
  }
312
317
 
318
+ // A merged leaf's work is on the target: nothing runs for it again, whatever
319
+ // its pipeline last decided. The janitor completes it and releases its
320
+ // workspace (§15.7); no runner, restack or measurement is needed.
321
+ if (state.kind !== 'node' && state.prState === 'merged')
322
+ return { kind: 'wait', reason: 'awaiting-pr' }
323
+
313
324
  // A declared ticket wait parks the build until the dispatcher validates it
314
325
  // (SPEC §11 "Ticket waits"): accepted, it becomes an open escalation below;
315
326
  // refused, the declaring phase re-runs with the refusal as guidance.
@@ -1054,9 +1065,11 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
1054
1065
 
1055
1066
  /** The §9 awaiting-landing restack condition: the target moved since the
1056
1067
  * build's last restack base, or a target post-step landed after it. Shared
1057
- * with dispatch capacity, which admits a parked build that must restack. */
1068
+ * with dispatch capacity, which admits a parked build that must restack. A
1069
+ * merged PR has nothing to restack: its work is already on the target. */
1058
1070
  export function landingRestackDue(state: BuildState, log: Pick<LogIndex, 'restack'>): boolean {
1059
1071
  return (
1072
+ state.prState !== 'merged' &&
1060
1073
  log.restack.target !== undefined &&
1061
1074
  (log.restack.target.sha !== leafRestackedBase(log.restack) ||
1062
1075
  (state.target !== undefined &&
@@ -34,6 +34,7 @@ export type JanitorOperation =
34
34
  | 'PR check'
35
35
  | 'attempt rejection'
36
36
  | 'session settlement'
37
+ | 'merged workspace release'
37
38
 
38
39
  /** A build's janitor attempt is due: no episode, an answered escalation asked
39
40
  * for a retry, or the backoff has elapsed. */
@@ -108,4 +108,5 @@ export const REDUCER_REVISIONS: Readonly<Record<string, string>> = {
108
108
  'buildReadFacts/shape/ubvhths92u': '#1452 session.suspended carries the ended execution',
109
109
  'buildStreamSeed/shape/65yse1vuyo': '#1452 session.suspended carries the ended execution',
110
110
  'dashboardFacts/shape/d0avr35e2j': '#1452 session.suspended carries the ended execution',
111
+ 'buildDigest/shape/gfei8y6315': 'buildDigest tracks open workspace for releasePending (#1443)',
111
112
  }
@@ -139,6 +139,11 @@ import { refreshSummaryBoundary } from '../cli/pr-summary-publication'
139
139
  * - The D5 retry guard also covers agent-verify steps (keyed `verify:<step>`,
140
140
  * round = attempt): a no-terminal or provider-failed verify session would
141
141
  * otherwise re-run forever, since its `verify.completed` never lands.
142
+ * - An orderly stop that interrupts a `run-check` (the runner's own
143
+ * `shutdownSignal`, which includes a stage's interruption) records nothing,
144
+ * re-checked immediately before the `verify.completed` append; the relaunch
145
+ * reruns the member at the same attempt. A non-zero exit or a signal kill
146
+ * while the runner's own shutdown is not in effect is still a failed cycle.
142
147
  * - A throwing Exec in `run-check` propagates: deterministic checks carry no
143
148
  * session to fail (§8.2), and a crashed runner's dangling `verify.started`
144
149
  * simply re-runs the check on re-attach (§15.6-C) — the same crash model
@@ -185,7 +190,8 @@ import type {
185
190
  } from '../ports/types'
186
191
  import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution'
187
192
  import { phaseScratchRejection, scratchPathsTouchedInRange } from '../ports/workspace/phase-scratch'
188
- import type { Exec } from '../ports/workspace/git-worktree'
193
+ import type { Exec, ExecResult } from '../ports/workspace/git-worktree'
194
+ import { describeCheckTermination } from './check-termination'
189
195
  import type { BuildScopedStore, Clock } from '../store/types'
190
196
  import {
191
197
  attemptPanelId,
@@ -442,6 +448,13 @@ function errorMessage(error: unknown): string {
442
448
  return error instanceof Error ? error.message : String(error)
443
449
  }
444
450
 
451
+ /** A failed check's combined output, capped to its tail. */
452
+ function reportTail(result: ExecResult): string {
453
+ const output = [result.stdout, result.stderr].filter((s) => s !== '').join('\n')
454
+ const content = output.length > REPORT_TAIL_CHARS ? output.slice(-REPORT_TAIL_CHARS) : output
455
+ return content || '(no output)'
456
+ }
457
+
445
458
  /** Bound one captured diff section: unchanged within the cap, otherwise the
446
459
  * first FINALIZE_DIFF_CAPTURE_CAP characters plus an explicit truncation
447
460
  * marker, so truncation is visible in the record itself. */
@@ -4552,7 +4565,10 @@ export class BuildRunner {
4552
4565
 
4553
4566
  /** Deterministic check (§8.2): NO session, NO CLI — the kernel runs the
4554
4567
  * command directly with `AB_VERIFY_BASE` set to the verify diff base, or
4555
- * unset when none exists; a failure deposits the output tail as the report. */
4568
+ * unset when none exists; a failure deposits the output tail as the report.
4569
+ * A signal-killed command's report names the signal and whether the
4570
+ * runner's own shutdown was in effect when it died; one the shutdown
4571
+ * stopped leaves an uncounted report and no event. */
4556
4572
  private async runCheck(decision: RunCheckDecision): Promise<void> {
4557
4573
  await this.withKernelPhaseFailure(verifyPhase(decision.step), decision.attempt, () =>
4558
4574
  this.runCheckOperation(decision),
@@ -4590,6 +4606,11 @@ export class BuildRunner {
4590
4606
  const signals = [this.deps.shutdownSignal, landing?.signal].filter(
4591
4607
  (signal): signal is AbortSignal => signal !== undefined,
4592
4608
  )
4609
+ // An orderly dispatcher stop (drain, deadline teardown, or a stage
4610
+ // interrupted by pause) records nothing: the relaunched execution reruns
4611
+ // this member at the same attempt (#1458).
4612
+ const interrupted = () =>
4613
+ this.deps.shutdownSignal?.aborted === true || landing?.signal.aborted === true
4593
4614
  let result: Awaited<ReturnType<typeof exec>>
4594
4615
  try {
4595
4616
  result = await exec(['sh', '-c', command], {
@@ -4601,12 +4622,22 @@ export class BuildRunner {
4601
4622
  } finally {
4602
4623
  if (this.checkAbort === landing) this.checkAbort = undefined
4603
4624
  }
4604
- if (this.deps.shutdownSignal?.aborted || landing?.signal.aborted) return
4625
+ // Sampled where the command died, before any await: whether the runner's
4626
+ // own shutdown could have sent a terminating signal.
4627
+ const runnerShutdown = this.deps.shutdownSignal?.aborted === true
4628
+ if (runnerShutdown) {
4629
+ await this.depositInterruptedCheckReport(step, attempt, command, result)
4630
+ return
4631
+ }
4632
+ if (landing?.signal.aborted) return
4605
4633
  await this.withVerifyWrite(async () => {
4606
4634
  const state = (await readBuildFacts(store, slug)).value.state
4607
4635
  const key = verifyMemberKey(step, attempt)
4608
4636
  if (state.verifyStage.cancellations[key] || state.verifyStage.outcomes[key]) return
4609
4637
  if (nodeLanded(state)) return
4638
+ // A stop can land during the awaits above. Keep this re-check the last
4639
+ // statement before the append, with no await between them.
4640
+ if (interrupted()) return
4610
4641
  if (result.exitCode === 0) {
4611
4642
  await store.append(slug, {
4612
4643
  actor: KERNEL,
@@ -4616,8 +4647,8 @@ export class BuildRunner {
4616
4647
  return
4617
4648
  }
4618
4649
 
4619
- const output = [result.stdout, result.stderr].filter((s) => s !== '').join('\n')
4620
- const content = output.length > REPORT_TAIL_CHARS ? output.slice(-REPORT_TAIL_CHARS) : output
4650
+ const termination = describeCheckTermination(result.exitCode, false)
4651
+ const tail = reportTail(result)
4621
4652
  // Atomic deposit (D6): report artifact + verify.completed in one bundle;
4622
4653
  // the report routes back to implement via the engine (§15.6-A).
4623
4654
  await store.appendWithArtifacts(
@@ -4625,8 +4656,14 @@ export class BuildRunner {
4625
4656
  [
4626
4657
  {
4627
4658
  kind: verifyReportKind(step),
4628
- content: content || '(no output)',
4629
- metadata: { step, attempt, command, exitCode: result.exitCode },
4659
+ content: termination ? `${termination.line}\n${tail}` : tail,
4660
+ metadata: {
4661
+ step,
4662
+ attempt,
4663
+ command,
4664
+ exitCode: result.exitCode,
4665
+ ...termination?.metadata,
4666
+ },
4630
4667
  },
4631
4668
  ],
4632
4669
  (deposited) => {
@@ -4648,6 +4685,29 @@ export class BuildRunner {
4648
4685
  })
4649
4686
  }
4650
4687
 
4688
+ /** A check the runner's own shutdown killed by signal leaves an uncounted
4689
+ * report: an artifact revision with no event, so no `verify.completed`, no
4690
+ * failed cycle and no spent attempt. Best-effort — the stop stays orderly
4691
+ * when the store refuses the write. */
4692
+ private async depositInterruptedCheckReport(
4693
+ step: string,
4694
+ attempt: number,
4695
+ command: string,
4696
+ result: ExecResult,
4697
+ ): Promise<void> {
4698
+ const termination = describeCheckTermination(result.exitCode, true)
4699
+ if (termination === undefined) return
4700
+ try {
4701
+ await this.deps.store.putArtifact(this.deps.slug, {
4702
+ kind: verifyReportKind(step),
4703
+ content: `${termination.line}\n${reportTail(result)}`,
4704
+ metadata: { step, attempt, command, exitCode: result.exitCode, ...termination.metadata },
4705
+ })
4706
+ } catch {
4707
+ // A lost diagnosis must never turn an orderly stop into phase.failed.
4708
+ }
4709
+ }
4710
+
4651
4711
  /** Agent-verify step (§5): a session with a pass/fail/skip verdict. */
4652
4712
  private async runAgentVerify(decision: RunAgentVerifyDecision): Promise<void> {
4653
4713
  await this.withKernelPhaseFailure(verifyPhase(decision.step), decision.attempt, () =>
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Diagnosis for a deterministic verify check that died from a signal.
3
+ *
4
+ * Several builds' agents and verify commands share one host, so a name or
5
+ * pattern kill (`pkill -f …`) run by another session can terminate this
6
+ * build's check. The victim's exit looks like any failure, so its report
7
+ * records which signal ended the command and whether the runner's own
8
+ * shutdown was in effect at that moment.
9
+ *
10
+ * Death by signal is read from the exit status with the shell convention
11
+ * 128+N: `sh -c` reports a signal-killed child (or grandchild, through a
12
+ * package-script runner) that way, and Bun's `proc.exited` does the same for
13
+ * the direct child.
14
+ */
15
+ import { constants } from 'node:os'
16
+
17
+ const SIGNAL_NAMES: ReadonlyMap<number, string> = new Map(
18
+ Object.entries(constants.signals).map(([name, number]) => [number, name]),
19
+ )
20
+
21
+ /** The signal name for a 128+N exit status, or undefined for any other. */
22
+ export function signalFromExitStatus(exitCode: number): string | undefined {
23
+ if (exitCode <= 128 || exitCode > 192) return undefined
24
+ return SIGNAL_NAMES.get(exitCode - 128)
25
+ }
26
+
27
+ export type CheckTermination = {
28
+ readonly metadata: { readonly signal: string; readonly runnerShutdown: boolean }
29
+ /** First line of the report, explaining who stopped the check. */
30
+ readonly line: string
31
+ }
32
+
33
+ /** Report annotation for a signal-killed check, or undefined for a normal exit. */
34
+ export function describeCheckTermination(
35
+ exitCode: number,
36
+ runnerShutdown: boolean,
37
+ ): CheckTermination | undefined {
38
+ const signal = signalFromExitStatus(exitCode)
39
+ if (signal === undefined) return undefined
40
+ const line = runnerShutdown
41
+ ? `terminated by ${signal} (exit ${exitCode}) during the runner's own shutdown: an orderly stop, not a failure and not counted; the step reruns after relaunch.`
42
+ : `terminated by ${signal} (exit ${exitCode}) while the runner's own shutdown was not in effect, so another process sent the signal. Rerun the check before changing code.`
43
+ return { metadata: { signal, runnerShutdown }, line }
44
+ }
@@ -422,6 +422,7 @@ import { settleOpenExecution } from './execution-settlement'
422
422
  import { isWorkDigest, RepoViewStore } from './repo-view'
423
423
  import type { OpenBuildWorkspace, ProvisionMarker } from './dispatcher-selectors'
424
424
  import {
425
+ mergedHeadCovers,
425
426
  recordPublicationLossBeforeRelease,
426
427
  settlePublicationFactsBeforeRelease,
427
428
  } from './publication-loss'
@@ -4043,6 +4044,7 @@ export class Dispatcher {
4043
4044
  if (
4044
4045
  state.status === 'done' &&
4045
4046
  digest.reclaimPending !== true &&
4047
+ digest.releasePending !== true &&
4046
4048
  digest.integrationAuditPending !== true
4047
4049
  )
4048
4050
  return
@@ -4100,7 +4102,13 @@ export class Dispatcher {
4100
4102
  undefined,
4101
4103
  )
4102
4104
  : undefined
4103
- if (state.kind === 'node' && !controlDue && pollSchedule && !pollSchedule.due) {
4105
+ if (
4106
+ state.kind === 'node' &&
4107
+ !controlDue &&
4108
+ digest.releasePending !== true &&
4109
+ pollSchedule &&
4110
+ !pollSchedule.due
4111
+ ) {
4104
4112
  attempted = false
4105
4113
  return
4106
4114
  }
@@ -4221,6 +4229,20 @@ export class Dispatcher {
4221
4229
  )
4222
4230
  }
4223
4231
  if (state.status === 'done') {
4232
+ // A merged build's workspace release is a post-terminal duty: its
4233
+ // completion never waited on it (§15.7).
4234
+ if (
4235
+ digest.releasePending === true &&
4236
+ state.prState === 'merged' &&
4237
+ !executionLeaseLive
4238
+ ) {
4239
+ operation = 'merged workspace release'
4240
+ await this.releaseMergedWorkspace(
4241
+ record,
4242
+ state.mergedSha !== undefined ? { sha: state.mergedSha } : {},
4243
+ this.forgeWorkspacePathOf(workspace),
4244
+ )
4245
+ }
4224
4246
  if (digest.reclaimPending === true) {
4225
4247
  operation = 'PR attachment reclaim'
4226
4248
  await this.reclaimPrAttachments(record.slug, await history())
@@ -4299,7 +4321,8 @@ export class Dispatcher {
4299
4321
  }
4300
4322
  }
4301
4323
  if ((state.status === 'paused' || janitorBlocked(state)) && !state.pr) return
4302
- if (state.nodeOpened && state.baseBranch) {
4324
+ // A merged PR has nothing left to restack onto the target.
4325
+ if (state.nodeOpened && state.baseBranch && state.prState !== 'merged') {
4303
4326
  operation = 'target observation'
4304
4327
  if (
4305
4328
  await this.observeTarget(
@@ -4394,7 +4417,9 @@ export class Dispatcher {
4394
4417
  if (
4395
4418
  state.kind !== 'node' &&
4396
4419
  state.status !== 'aborted' &&
4397
- janitorStatus(state) !== 'queued'
4420
+ janitorStatus(state) !== 'queued' &&
4421
+ // A merged PR has nothing left to restack onto the target.
4422
+ state.prState !== 'merged'
4398
4423
  ) {
4399
4424
  const branch = await readBuildSelector(this.store, record.slug, 'baseBranch')
4400
4425
  if (branch !== undefined) {
@@ -5064,6 +5089,10 @@ export class Dispatcher {
5064
5089
  )
5065
5090
  )
5066
5091
  return 'admit'
5092
+ // A merged leaf never takes a slot (§12): its completion and cleanup are
5093
+ // the janitor's, and nothing a runner could do remains. Not a slot
5094
+ // waiter either, so it reserves no intake.
5095
+ if (state.prState === 'merged') return 'wait'
5067
5096
  const builds = await this.capacityBuilds(this.tickLaunched)
5068
5097
  const others = builds.filter((build) => build.record.slug !== slug)
5069
5098
  const capacity = this.deps.config.capacity
@@ -6899,7 +6928,13 @@ export class Dispatcher {
6899
6928
  }
6900
6929
  source.observed?.(prState)
6901
6930
  if (state.prState === 'merged' && state.mergedSha)
6902
- prState = { state: 'merged', sha: state.mergedSha }
6931
+ prState = {
6932
+ state: 'merged',
6933
+ sha: state.mergedSha,
6934
+ ...(prState.state === 'merged' && prState.headSha !== undefined
6935
+ ? { headSha: prState.headSha }
6936
+ : {}),
6937
+ }
6903
6938
  let nativeCancelled = false
6904
6939
  if (
6905
6940
  nodeTarget &&
@@ -7747,7 +7782,6 @@ export class Dispatcher {
7747
7782
  // A merged attempt settles `accepted` with the measurement of the
7748
7783
  // head that landed, before the build can become terminal.
7749
7784
  if (nodeTarget) await this.settleMergedAttempt(record, state, prState.sha)
7750
- await this.releaseWorkspace(record.slug, events)
7751
7785
  if (record.ticket) {
7752
7786
  await tickets.transition(await this.currentTicketId(record), this.doneState)
7753
7787
  await tickets.comment(
@@ -7755,6 +7789,10 @@ export class Dispatcher {
7755
7789
  `build ${record.slug} merged: ${pr.url}`,
7756
7790
  )
7757
7791
  }
7792
+ // Complete before any workspace work: the merged commit is on the
7793
+ // target, so a stopped or unreachable workspace never holds the
7794
+ // build open (§15.7). Its release follows and, when it cannot
7795
+ // finish, stays pending on the completed build (`releasePending`).
7758
7796
  await store.append(record.slug, {
7759
7797
  actor: DISPATCHER,
7760
7798
  type: 'build.completed',
@@ -7762,6 +7800,7 @@ export class Dispatcher {
7762
7800
  } satisfies EventWrite<'build.completed'>)
7763
7801
  await this.reclaimPrAttachments(record.slug, events)
7764
7802
  report.merged += 1
7803
+ await this.releaseMergedWorkspace(record, prState, workspacePath)
7765
7804
  return
7766
7805
  }
7767
7806
  case 'closed': {
@@ -8182,12 +8221,6 @@ export class Dispatcher {
8182
8221
  // No live provider can act on this ref; leave the fact open rather than
8183
8222
  // claim a release that never happened.
8184
8223
  if (owner === null) return undefined
8185
- const handle = {
8186
- provider: open.provider,
8187
- ref: open.ref,
8188
- path: open.path ?? open.ref,
8189
- branch: open.branch,
8190
- }
8191
8224
  // Last-chance settlement boundary (AUT-328): settle or durably record the
8192
8225
  // pending publication BEFORE any provider cleanup call, while the
8193
8226
  // workspace still exists. The guard's append failure propagates — the
@@ -8221,6 +8254,28 @@ export class Dispatcher {
8221
8254
  reason,
8222
8255
  )
8223
8256
  }
8257
+ return this.cleanupAndRelease(slug, open, owner, events, reason, { recordFailure: true })
8258
+ }
8259
+
8260
+ /** The provider cleanup every release ends with: reap (recording the
8261
+ * attempt) or release, then `workspace.released`. A deadline deferral
8262
+ * records nothing and propagates. Any other reap failure records the
8263
+ * unknown cleanup attempt, and with `recordFailure` also charges the
8264
+ * build's infrastructure-failure budget, then propagates. */
8265
+ private async cleanupAndRelease(
8266
+ slug: string,
8267
+ open: OpenBuildWorkspace,
8268
+ owner: WorkspaceProvider,
8269
+ events: CurrentBuildFacts,
8270
+ reason: 'completion' | 'abort' | 'pause' | 'blocked' | 'replacement' | 'discard',
8271
+ options: { recordFailure: boolean },
8272
+ ): Promise<AbEvent> {
8273
+ const handle = {
8274
+ provider: open.provider,
8275
+ ref: open.ref,
8276
+ path: open.path ?? open.ref,
8277
+ branch: open.branch,
8278
+ }
8224
8279
  const recovery = owner.recovery
8225
8280
  if (recovery !== undefined) {
8226
8281
  const attempt = (events.cleanupCounts[JSON.stringify(open.ref)] ?? 0) + 1
@@ -8259,13 +8314,14 @@ export class Dispatcher {
8259
8314
  },
8260
8315
  })
8261
8316
  Object.assign(events, (await readBuildFacts(this.store, slug)).value)
8262
- await this.recordInfrastructureFailure(slug, events, {
8263
- provider: open.provider,
8264
- workspaceRef: open.ref,
8265
- operation: 'delete',
8266
- error: failure,
8267
- cleanupPending: true,
8268
- })
8317
+ if (options.recordFailure)
8318
+ await this.recordInfrastructureFailure(slug, events, {
8319
+ provider: open.provider,
8320
+ workspaceRef: open.ref,
8321
+ operation: 'delete',
8322
+ error: failure,
8323
+ cleanupPending: true,
8324
+ })
8269
8325
  throw error
8270
8326
  }
8271
8327
  } else {
@@ -8278,6 +8334,63 @@ export class Dispatcher {
8278
8334
  } satisfies EventWrite<'workspace.released'>)
8279
8335
  }
8280
8336
 
8337
+ /** Release a merged build's workspace (SPEC §15.7). The merged commit is on
8338
+ * the target, so nothing is fenced, preserved or resumed. A pending
8339
+ * publication the merged PR already contains is recorded lost without
8340
+ * settlement; one it does not contain is settled as every release does.
8341
+ * Runs after `build.completed`: a deferral or failure here leaves the build
8342
+ * completed with `releasePending` in its digest, and the janitor retries it
8343
+ * under janitor-failure backoff. Log-deduped, so re-runs are no-ops. */
8344
+ private async releaseMergedWorkspace(
8345
+ record: BuildRecord,
8346
+ merged: { sha?: string; headSha?: string },
8347
+ path: string,
8348
+ ): Promise<void> {
8349
+ const slug = record.slug
8350
+ let facts = (await readBuildFacts(this.store, slug)).value
8351
+ const open = openWorkspace(facts)
8352
+ if (open === null) return
8353
+ const owner = this.workspaceOwner(open)
8354
+ if (owner === null)
8355
+ throw new Error(
8356
+ `merged workspace ${open.ref} has no configured provider "${open.provider}"; cleanup stays pending`,
8357
+ )
8358
+ // A live runner still owns the workspace; the next visit releases it.
8359
+ if (this.hasLiveExecutionLease(record)) return
8360
+ const request = facts.publication.latestUncompletedRequest()
8361
+ if (request !== undefined && !facts.publication.lostRecorded(request)) {
8362
+ let headSha = merged.headSha
8363
+ const pr = facts.state.pr
8364
+ if (headSha === undefined && pr !== undefined) {
8365
+ const observed = await this.deps.forge.getPrState(path, pr.number)
8366
+ if (observed.state === 'merged') headSha = observed.headSha
8367
+ }
8368
+ const forge = this.deps.forge
8369
+ const covered = await mergedHeadCovers(
8370
+ request.payload.sha,
8371
+ [headSha, merged.sha],
8372
+ forge.isCommitAncestor
8373
+ ? (ancestor, descendant) => forge.isCommitAncestor!(ancestor, descendant)
8374
+ : undefined,
8375
+ )
8376
+ facts = covered
8377
+ ? await recordPublicationLossBeforeRelease(
8378
+ { store: this.store },
8379
+ slug,
8380
+ facts,
8381
+ `completion: merged PR already contains ${request.payload.sha}`,
8382
+ request,
8383
+ )
8384
+ : await settlePublicationFactsBeforeRelease(
8385
+ { store: this.store, settlePublication: this.settlePublication },
8386
+ slug,
8387
+ facts,
8388
+ 'completion',
8389
+ )
8390
+ }
8391
+ await this.cleanupAndRelease(slug, open, owner, facts, 'completion', { recordFailure: false })
8392
+ }
8393
+
8281
8394
  /**
8282
8395
  * One best-effort preservation attempt ahead of an abort release. Only three
8283
8396
  * refusals stop the release: lost repository authority, a mixed-version
@@ -1,6 +1,7 @@
1
1
  import { PublicationRetryPersistenceError } from '../kernel/publication-retry'
2
2
  import { ForgeRequestDeferred } from '../ports/forge-request-context'
3
3
  import { isRemoteWorkspace } from '../events/workspace-remote'
4
+ import { isRepositoryAuthorityLapse } from '../cli/repo-lease'
4
5
  import { isRecoveryDeferred, recoveryStepOf } from '../ports/workspace/recovery-step'
5
6
  /**
6
7
  * Last-chance publication settlement at the workspace-release boundary
@@ -136,3 +137,31 @@ export async function recordPublicationLossBeforeRelease(
136
137
  })
137
138
  return (await readBuildFacts(deps.store, slug)).value
138
139
  }
140
+
141
+ /**
142
+ * Whether a merged PR already contains a pending publication's commit, so its
143
+ * release needs no settlement (merged completion, SPEC §15.7). True when
144
+ * `request` equals a merged head, or a host-side ancestry proof shows it below
145
+ * one. `heads` names the PR's observed head first, then its landing: a squash
146
+ * landing never descends from the PR's commits, but the PR head does. An absent
147
+ * capability, an unknown object or a throwing proof is never coverage. A forge
148
+ * deferral or a lapsed repository lease still propagates.
149
+ */
150
+ export async function mergedHeadCovers(
151
+ request: string,
152
+ heads: readonly (string | undefined)[],
153
+ isAncestor?: (ancestor: string, descendant: string) => Promise<boolean>,
154
+ ): Promise<boolean> {
155
+ const known = heads.filter((head): head is string => head !== undefined && head !== '')
156
+ if (known.includes(request)) return true
157
+ if (isAncestor === undefined) return false
158
+ for (const head of known) {
159
+ try {
160
+ if (await isAncestor(request, head)) return true
161
+ } catch (error) {
162
+ if (error instanceof ForgeRequestDeferred || isRepositoryAuthorityLapse(error)) throw error
163
+ // Unknown ancestry proves nothing; try the next head.
164
+ }
165
+ }
166
+ return false
167
+ }
@@ -103,7 +103,8 @@ export function isWorkDigest(digest: Omit<BuildDigest, 'slug'>): boolean {
103
103
  digest.terminal === 'aborted' ||
104
104
  digest.reclaimPending === true ||
105
105
  digest.executionOpen === true ||
106
- digest.rejectionsPending === true
106
+ digest.rejectionsPending === true ||
107
+ digest.releasePending === true
107
108
  )
108
109
  }
109
110
  class Chain {
@@ -1250,6 +1250,49 @@ export function describeBuildStoreContract(name: string, factory: BuildStoreFact
1250
1250
  })
1251
1251
  })
1252
1252
 
1253
+ test('releasePending marks a completed merged build whose workspace is still open', async () => {
1254
+ await withStore(factory, undefined, async (store) => {
1255
+ const repo = 'acme/dg-release'
1256
+ const pending = async (slug: string) =>
1257
+ (await store.getRepoBuildDigests(repo)).get(slug)!.releasePending
1258
+ const seed = async (slug: string, closing: 'pr.merged' | 'pr.closed') => {
1259
+ await store.createBuild(sampleBuildInput(slug, { repo }))
1260
+ await store.append(slug, buildCreatedWrite())
1261
+ await store.append(slug, {
1262
+ actor: DISPATCHER,
1263
+ type: 'workspace.provisioned',
1264
+ payload: {
1265
+ provider: 'p',
1266
+ ref: 'w',
1267
+ branch: `ab/${slug}`,
1268
+ base: { source: 'remote', sha: 'a'.repeat(40) },
1269
+ },
1270
+ })
1271
+ await store.append(
1272
+ slug,
1273
+ closing === 'pr.merged'
1274
+ ? { actor: DISPATCHER, type: 'pr.merged', payload: { sha: 'm' } }
1275
+ : { actor: DISPATCHER, type: 'pr.closed', payload: {} },
1276
+ )
1277
+ await store.append(slug, {
1278
+ actor: DISPATCHER,
1279
+ type: 'build.completed',
1280
+ payload: { outcome: closing === 'pr.merged' ? 'merged' : 'closed-unmerged' },
1281
+ })
1282
+ }
1283
+ await seed('dg-merged', 'pr.merged')
1284
+ await seed('dg-closed', 'pr.closed')
1285
+ expect(await pending('dg-merged')).toBe(true)
1286
+ expect(await pending('dg-closed')).toBeUndefined()
1287
+ await store.append('dg-merged', {
1288
+ actor: DISPATCHER,
1289
+ type: 'workspace.released',
1290
+ payload: { ref: 'w', reason: 'completion' },
1291
+ })
1292
+ expect(await pending('dg-merged')).toBeUndefined()
1293
+ })
1294
+ })
1295
+
1253
1296
  test('rejectionsPending follows non-accepted attempt settlements until their ticket moves', async () => {
1254
1297
  await withStore(factory, undefined, async (store) => {
1255
1298
  const repo = 'acme/dg-opt'
@@ -50,6 +50,10 @@ export const DIGEST_EVENT_TYPES = [
50
50
  'pr-attachment.reclaimed',
51
51
  'execution.started',
52
52
  'execution.ended',
53
+ // The open workspace a merged build's completion still has to release.
54
+ 'workspace.provisioned',
55
+ 'workspace.cleanup-required',
56
+ 'workspace.released',
53
57
  'wait.requested',
54
58
  'wait.refused',
55
59
  'wait.entered',
@@ -128,6 +132,9 @@ export interface DigestAcc {
128
132
  executionFacts: number
129
133
  /** Sorted unique node slugs any target or parent move has named. */
130
134
  nodeTargets: string[]
135
+ /** The latest `workspace.provisioned` / `workspace.cleanup-required` has no
136
+ * later `workspace.released` (the `openBuildWorkspace` rule). */
137
+ workspaceOpen: boolean
131
138
  /** The latest ticket-wait fact is a request without its outcome. */
132
139
  waitPending?: true
133
140
  /** The entered ticket wait that has not ended. */
@@ -195,6 +202,7 @@ export const buildDigestReducer: IncrementalReducer<
195
202
  openInstance: null,
196
203
  executionFacts: 0,
197
204
  nodeTargets: [],
205
+ workspaceOpen: false,
198
206
  }),
199
207
  fold(acc, events) {
200
208
  for (const event of events) {
@@ -266,7 +274,13 @@ export const buildDigestReducer: IncrementalReducer<
266
274
  const remaining = acc.pendingRejections.filter((p) => p !== event.attemptProposal)
267
275
  acc.pendingRejections = remaining.length > 0 ? remaining : undefined
268
276
  }
269
- } else if (event.type === 'execution.started') {
277
+ } else if (
278
+ event.type === 'workspace.provisioned' ||
279
+ event.type === 'workspace.cleanup-required'
280
+ )
281
+ acc.workspaceOpen = true
282
+ else if (event.type === 'workspace.released') acc.workspaceOpen = false
283
+ else if (event.type === 'execution.started') {
270
284
  acc.executionFacts += 1
271
285
  acc.openInstance = event.instance ?? null
272
286
  } else if (event.type === 'execution.ended') {
@@ -299,6 +313,7 @@ export const buildDigestReducer: IncrementalReducer<
299
313
  optimization,
300
314
  proposerWakeSeq,
301
315
  proposerDeferredSeq,
316
+ workspaceOpen,
302
317
  }) => {
303
318
  const reclaimedSet = new Set(reclaimed)
304
319
  const reclaimPending = hosted.some((seq) => !reclaimedSet.has(seq))
@@ -322,6 +337,9 @@ export const buildDigestReducer: IncrementalReducer<
322
337
  ...(waitPending ? { waitPending } : {}),
323
338
  ...(ticketWait !== undefined ? { ticketWait: structuredClone(ticketWait) } : {}),
324
339
  ...(pendingRejections?.length ? { rejectionsPending: true as const } : {}),
340
+ ...(terminal === 'done' && merged !== undefined && workspaceOpen
341
+ ? { releasePending: true as const }
342
+ : {}),
325
343
  nodeTargets: [...nodeTargets],
326
344
  ...(kind === 'node'
327
345
  ? {