@defrex/autobuild 1.18.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 (63) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +97 -18
  3. package/docs/architecture.md +53 -16
  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/cli/dispatch.ts +2 -0
  18. package/packages/core/src/events/catalog-identity.ts +3 -1
  19. package/packages/core/src/events/payloads.ts +7 -1
  20. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +1 -0
  21. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3f0c4e6d1d54e5bf.json +92 -0
  22. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e012e9e8f3e82935.json +424 -0
  23. package/packages/core/src/kernel/dispatch-capacity.ts +15 -3
  24. package/packages/core/src/kernel/engine.ts +15 -2
  25. package/packages/core/src/kernel/janitor-failure.ts +2 -0
  26. package/packages/core/src/kernel/reducer-revisions.ts +5 -0
  27. package/packages/core/src/kernel/reducer.ts +6 -0
  28. package/packages/core/src/kernel/session-settlement.ts +82 -0
  29. package/packages/core/src/processes/build-runner.ts +167 -36
  30. package/packages/core/src/processes/check-termination.ts +44 -0
  31. package/packages/core/src/processes/dispatcher.ts +295 -21
  32. package/packages/core/src/processes/execution-settlement.ts +30 -0
  33. package/packages/core/src/processes/publication-loss.ts +29 -0
  34. package/packages/core/src/processes/repo-view.ts +2 -1
  35. package/packages/core/src/store/contract.ts +43 -0
  36. package/packages/core/src/store/digest.ts +19 -1
  37. package/packages/core/src/store/reducer-value-shapes.json +2742 -2709
  38. package/packages/core/src/store/remote/protocol.ts +3 -0
  39. package/packages/core/src/store/remote/released-clients.json +22 -0
  40. package/packages/core/src/store/remote/released-reducer-values/1.19.0.json +36461 -0
  41. package/packages/core/src/store/remote/released-reducer-values/1.20.0.json +36469 -0
  42. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  43. package/packages/core/src/store/types.ts +5 -0
  44. package/packages/core/src/testing/reduced-read-budget.ts +167 -0
  45. package/skills/code-review/SKILL.md +5 -0
  46. package/skills/finalize/SKILL.md +5 -0
  47. package/skills/guide/SKILL.md +42 -17
  48. package/skills/guide/references/merge-policy.md +2 -1
  49. package/skills/guide/references/plugin-authoring.md +11 -4
  50. package/skills/guide/references/process-ownership.md +43 -0
  51. package/skills/guide/references/remote-store-protocol.md +7 -0
  52. package/skills/guide/references/restacking.md +11 -2
  53. package/skills/guide/references/setup.md +7 -2
  54. package/skills/harvest/SKILL.md +5 -0
  55. package/skills/harvest-review/SKILL.md +5 -0
  56. package/skills/implement/SKILL.md +5 -0
  57. package/skills/judge/SKILL.md +4 -0
  58. package/skills/operate/SKILL.md +5 -0
  59. package/skills/plan/SKILL.md +5 -0
  60. package/skills/plan-review/SKILL.md +5 -0
  61. package/skills/propose/SKILL.md +5 -0
  62. package/skills/reconcile/SKILL.md +5 -0
  63. 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 &&
@@ -33,6 +33,8 @@ export type JanitorOperation =
33
33
  | 'target observation'
34
34
  | 'PR check'
35
35
  | 'attempt rejection'
36
+ | 'session settlement'
37
+ | 'merged workspace release'
36
38
 
37
39
  /** A build's janitor attempt is due: no episode, an answered escalation asked
38
40
  * for a retry, or the backoff has elapsed. */
@@ -104,4 +104,9 @@ export const REDUCER_REVISIONS: Readonly<Record<string, string>> = {
104
104
  'repositoryReadFacts/fold/3vtj9fjj4k': '#1431 deferredWork carries tickets',
105
105
  'repositoryReadFacts/shape/l3uobdw03l': '#1431 intended records the admitted level',
106
106
  'ticketPreparation/shape/3hfd72gfgz': '#1431 intended records the admitted level',
107
+ 'build/shape/arlz7no6sx': '#1452 session.suspended carries the ended execution',
108
+ 'buildReadFacts/shape/ubvhths92u': '#1452 session.suspended carries the ended execution',
109
+ 'buildStreamSeed/shape/65yse1vuyo': '#1452 session.suspended carries the ended execution',
110
+ 'dashboardFacts/shape/d0avr35e2j': '#1452 session.suspended carries the ended execution',
111
+ 'buildDigest/shape/gfei8y6315': 'buildDigest tracks open workspace for releasePending (#1443)',
107
112
  }
@@ -169,6 +169,9 @@ export interface OpenSession {
169
169
  resumed?: boolean
170
170
  suspensionCause?: EventPayload<'session.suspended'>['cause']
171
171
  suspendedActiveMs?: number
172
+ /** The ended execution a dispatcher-settled suspension names; its
173
+ * continuation is a runner loss. */
174
+ suspendedExecution?: EventPayload<'session.suspended'>['execution']
172
175
  session: string
173
176
  role: string
174
177
  runner: string
@@ -1478,6 +1481,9 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1478
1481
  nativeHandle: event.payload.handle ?? open.nativeHandle,
1479
1482
  suspensionCause: event.payload.cause,
1480
1483
  suspendedActiveMs: event.payload.activeMs,
1484
+ ...(event.payload.execution !== undefined
1485
+ ? { suspendedExecution: event.payload.execution }
1486
+ : {}),
1481
1487
  })
1482
1488
  openSessions.delete(open.session)
1483
1489
  }
@@ -0,0 +1,82 @@
1
+ /** Which open sessions belong to the engine's next step, and how the
2
+ * dispatcher settles the sessions an ended execution left open. Pure: the
3
+ * runner and the dispatcher pass reduced state and the engine decision. */
4
+ import { verifyPhase } from '../ontology'
5
+ import type { Decision } from './engine'
6
+ import type { BuildState, OpenSession } from './reducer'
7
+
8
+ /** Whether `session` is the occurrence `decision` runs next, so a runner may
9
+ * continue it natively. */
10
+ export function recoveryMatches(decision: Decision, session: OpenSession): boolean {
11
+ if (decision.kind === 'run-verify-stage')
12
+ return decision.members.some((member) =>
13
+ recoveryMatches(member.kind === 'evaluate-verify' ? member.action : member, session),
14
+ )
15
+ return decision.kind === 'run-phase'
16
+ ? session.phase === decision.phase && session.round === decision.round
17
+ : decision.kind === 'run-agent-verify'
18
+ ? session.phase === verifyPhase(decision.step) && session.round === decision.attempt
19
+ : decision.kind === 'run-finalize-step'
20
+ ? session.phase === 'finalize' && session.role === decision.step
21
+ : false
22
+ }
23
+
24
+ /** Sessions open only inside executions, so once an execution has been
25
+ * recorded and none is open, every open session belongs to an ended one and
26
+ * no runner owns it. The dispatcher settles each without launching a runner:
27
+ *
28
+ * - `suspend`: an unfinished occurrence with a recorded native handle — the
29
+ * one the engine runs next, or one the caller found unfinished
30
+ * (`unfinished`) while a pause, escalation or other hold keeps the engine
31
+ * waiting. Suspending keeps it the native continuation candidate; the next
32
+ * runner resumes it as a runner loss.
33
+ * - `end`: everything else — a step that already has its outcome, a
34
+ * superseded round or attempt, or a session with no handle. These are ended
35
+ * `reclaimed`.
36
+ *
37
+ * A done or aborted build, or one with an abort pending, resumes nothing, so
38
+ * every session it left open is ended. A session whose phase has completed since it started is never
39
+ * suspended: the reducer ignores that suspension. Builds with no recorded
40
+ * execution keep the orphan-relaunch path, and already-suspended sessions are
41
+ * left alone. `decision` is absent only for a terminal build. */
42
+ export function endedExecutionSessionSettlement(
43
+ state: BuildState,
44
+ decision: Decision | undefined,
45
+ unfinished: ReadonlySet<string> = new Set(),
46
+ ): { suspend: OpenSession[]; end: OpenSession[] } {
47
+ const settlement = { suspend: [] as OpenSession[], end: [] as OpenSession[] }
48
+ if (state.openExecution !== undefined || state.executions.length === 0) return settlement
49
+ for (const session of state.sessions.open)
50
+ (resumable(state, session) &&
51
+ ((decision !== undefined && recoveryMatches(decision, session)) ||
52
+ unfinished.has(session.session))
53
+ ? settlement.suspend
54
+ : settlement.end
55
+ ).push(session)
56
+ return settlement
57
+ }
58
+
59
+ /** Open sessions of an ended execution whose resumability the engine
60
+ * decision does not settle: the caller checks each occurrence's durable
61
+ * terminal and passes the unfinished ones back as `unfinished`. */
62
+ export function settlementTerminalChecks(
63
+ state: BuildState,
64
+ decision: Decision | undefined,
65
+ ): OpenSession[] {
66
+ if (state.openExecution !== undefined || state.executions.length === 0) return []
67
+ return state.sessions.open.filter(
68
+ (session) =>
69
+ resumable(state, session) && (decision === undefined || !recoveryMatches(decision, session)),
70
+ )
71
+ }
72
+
73
+ function resumable(state: BuildState, session: OpenSession): boolean {
74
+ const completed = state.lastCompletedPhase
75
+ return (
76
+ state.status !== 'done' &&
77
+ state.status !== 'aborted' &&
78
+ !state.pendingCommands.some((command) => command.command === 'abort') &&
79
+ session.nativeHandle !== undefined &&
80
+ !(completed?.phase === session.phase && completed.seq > session.seq)
81
+ )
82
+ }
@@ -41,6 +41,7 @@ import { resumeAgent } from '../ports/runner/native-session'
41
41
  import type { AgentStartOpts, StartPromptOpts } from '../ports/types'
42
42
  import { readTerminalGuardBoundary } from '../store/reduced-reads'
43
43
  import type { OpenSession } from '../kernel/reducer'
44
+ import { recoveryMatches } from '../kernel/session-settlement'
44
45
  import { nativeSessionHandleSchema } from '../ports/runner/native-session'
45
46
  import type { NativeSessionObserver } from '../ports/types'
46
47
  import { suspendNativeLanding } from '../kernel/landing-publication'
@@ -138,6 +139,11 @@ import { refreshSummaryBoundary } from '../cli/pr-summary-publication'
138
139
  * - The D5 retry guard also covers agent-verify steps (keyed `verify:<step>`,
139
140
  * round = attempt): a no-terminal or provider-failed verify session would
140
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.
141
147
  * - A throwing Exec in `run-check` propagates: deterministic checks carry no
142
148
  * session to fail (§8.2), and a crashed runner's dangling `verify.started`
143
149
  * simply re-runs the check on re-attach (§15.6-C) — the same crash model
@@ -184,7 +190,8 @@ import type {
184
190
  } from '../ports/types'
185
191
  import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution'
186
192
  import { phaseScratchRejection, scratchPathsTouchedInRange } from '../ports/workspace/phase-scratch'
187
- import type { Exec } from '../ports/workspace/git-worktree'
193
+ import type { Exec, ExecResult } from '../ports/workspace/git-worktree'
194
+ import { describeCheckTermination } from './check-termination'
188
195
  import type { BuildScopedStore, Clock } from '../store/types'
189
196
  import {
190
197
  attemptPanelId,
@@ -441,6 +448,13 @@ function errorMessage(error: unknown): string {
441
448
  return error instanceof Error ? error.message : String(error)
442
449
  }
443
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
+
444
458
  /** Bound one captured diff section: unchanged within the cap, otherwise the
445
459
  * first FINALIZE_DIFF_CAPTURE_CAP characters plus an explicit truncation
446
460
  * marker, so truncation is visible in the record itself. */
@@ -604,18 +618,15 @@ function isPublicationBoundary(event: AbEvent, spec: SessionSpec, session: strin
604
618
  return false
605
619
  }
606
620
 
607
- function recoveryMatches(decision: Decision, session: OpenSession): boolean {
608
- if (decision.kind === 'run-verify-stage')
609
- return decision.members.some((member) =>
610
- recoveryMatches(member.kind === 'evaluate-verify' ? member.action : member, session),
611
- )
612
- return decision.kind === 'run-phase'
613
- ? session.phase === decision.phase && session.round === decision.round
614
- : decision.kind === 'run-agent-verify'
615
- ? session.phase === verifyPhase(decision.step) && session.round === decision.attempt
616
- : decision.kind === 'run-finalize-step'
617
- ? session.phase === 'finalize' && session.role === decision.step
618
- : false
621
+ /** The continuation cause a recovering runner records for `session`. A
622
+ * session the dispatcher suspended after its execution ended was lost with
623
+ * its runner, so it resumes as a runner loss, as it would have while open. */
624
+ function recoveryCauseOf(
625
+ session: OpenSession,
626
+ suspended: boolean,
627
+ ): 'shutdown' | 'pause' | 'runner-loss' {
628
+ if (!suspended || session.suspendedExecution !== undefined) return 'runner-loss'
629
+ return session.suspensionCause ?? 'shutdown'
619
630
  }
620
631
 
621
632
  /** One judge panel run's inputs (SPEC §13.1.1). */
@@ -762,9 +773,10 @@ export class BuildRunner {
762
773
  continuation: {
763
774
  ...write.payload.continuation!,
764
775
  handle: current.nativeHandle,
765
- cause:
766
- current.suspensionCause ??
767
- (current.suspendedActiveMs !== undefined ? 'shutdown' : 'runner-loss'),
776
+ cause: recoveryCauseOf(
777
+ current,
778
+ current.suspensionCause !== undefined || current.suspendedActiveMs !== undefined,
779
+ ),
768
780
  activeMs:
769
781
  (current.continuation?.activeMs ?? 0) +
770
782
  (current.suspendedActiveMs ??
@@ -1218,17 +1230,17 @@ export class BuildRunner {
1218
1230
  else {
1219
1231
  this.recoveryBoundaryMs = this.deps.clock().getTime()
1220
1232
  retained.add(candidate.session)
1233
+ const cause = recoveryCauseOf(
1234
+ candidate,
1235
+ state.sessions.suspended.some((s) => s.session === candidate.session),
1236
+ )
1221
1237
  if (decision.kind === 'run-verify-stage')
1222
1238
  this.stageRecoveries.set(verifyMemberKey(candidate.phase!.slice(7), candidate.round!), {
1223
1239
  session: candidate,
1224
- cause: state.sessions.suspended.some((s) => s.session === candidate.session)
1225
- ? (candidate.suspensionCause ?? 'shutdown')
1226
- : 'runner-loss',
1240
+ cause,
1227
1241
  })
1228
1242
  else this.recovery = candidate
1229
- this.recoveryCause = state.sessions.suspended.some((s) => s.session === candidate.session)
1230
- ? (candidate.suspensionCause ?? 'shutdown')
1231
- : 'runner-loss'
1243
+ this.recoveryCause = cause
1232
1244
  }
1233
1245
  }
1234
1246
  for (const session of [...state.sessions.open, ...state.sessions.suspended]) {
@@ -3408,6 +3420,38 @@ export class BuildRunner {
3408
3420
  }
3409
3421
  }
3410
3422
 
3423
+ /** Close the bracket of an occurrence whose outcome is already durable when
3424
+ * no transcript can be deposited: `reclaimed` by this runner, never a
3425
+ * fabricated transcript. The stream closes first. Best effort: whatever an
3426
+ * ended execution still leaves open, the dispatcher settles. */
3427
+ private async endFinishedBracket(
3428
+ session: string,
3429
+ stream?: SessionBracketStream,
3430
+ outcome: StreamOutcome = 'completed',
3431
+ ): Promise<void> {
3432
+ const { store, slug } = this.deps
3433
+ try {
3434
+ await stream?.sink.close(outcome)
3435
+ for (;;) {
3436
+ const facts = await readBuildFacts(store, slug)
3437
+ const { state } = facts.value
3438
+ if (!state.sessions.open.some((open) => open.session === session)) return
3439
+ const ended = await store.appendIfCurrent(slug, facts.cursor, {
3440
+ actor: KERNEL,
3441
+ type: 'session.ended',
3442
+ payload: {
3443
+ session,
3444
+ outcome: 'reclaimed',
3445
+ reclaimedBy: { instance: this.deps.instance, resumedFromSeq: state.lastSeq },
3446
+ },
3447
+ })
3448
+ if (ended) return
3449
+ }
3450
+ } catch {
3451
+ // The durable terminal remains authoritative over bracket cleanup.
3452
+ }
3453
+ }
3454
+
3411
3455
  /** Handles live only here; every scheduling and barrier decision is read
3412
3456
  * from durable facts. A child runner isolates each occurrence's recovery,
3413
3457
  * provider fallback, stream and retry state without another workspace. */
@@ -3554,6 +3598,22 @@ export class BuildRunner {
3554
3598
  entry.runner.closeBracketStream(stream, 'aborted')
3555
3599
  await entry.runner.closeProducerSessions()
3556
3600
  }
3601
+ // A member whose step has its outcome is finished, so its bracket must
3602
+ // not outlive the stage: the next stage or finalize starts only after
3603
+ // it ends. Under parent shutdown, suspension settles each bracket.
3604
+ // Best effort: a failed read must not mask the stage's own error.
3605
+ if (!this.deps.shutdownSignal?.aborted)
3606
+ try {
3607
+ const { state } = (await readBuildFacts(store, slug)).value
3608
+ for (const open of state.sessions.open) {
3609
+ if (!open.phase.startsWith('verify:') || open.round === undefined) continue
3610
+ const key = verifyMemberKey(open.phase.slice(7), open.round)
3611
+ if (inFlight.get(key)?.done && state.verifyStage.outcomes[key] !== undefined)
3612
+ await this.endFinishedBracket(open.session)
3613
+ }
3614
+ } catch {
3615
+ // The dispatcher settles what an ended execution leaves open.
3616
+ }
3557
3617
  }
3558
3618
  }
3559
3619
 
@@ -4505,7 +4565,10 @@ export class BuildRunner {
4505
4565
 
4506
4566
  /** Deterministic check (§8.2): NO session, NO CLI — the kernel runs the
4507
4567
  * command directly with `AB_VERIFY_BASE` set to the verify diff base, or
4508
- * 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. */
4509
4572
  private async runCheck(decision: RunCheckDecision): Promise<void> {
4510
4573
  await this.withKernelPhaseFailure(verifyPhase(decision.step), decision.attempt, () =>
4511
4574
  this.runCheckOperation(decision),
@@ -4543,6 +4606,11 @@ export class BuildRunner {
4543
4606
  const signals = [this.deps.shutdownSignal, landing?.signal].filter(
4544
4607
  (signal): signal is AbortSignal => signal !== undefined,
4545
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
4546
4614
  let result: Awaited<ReturnType<typeof exec>>
4547
4615
  try {
4548
4616
  result = await exec(['sh', '-c', command], {
@@ -4554,12 +4622,22 @@ export class BuildRunner {
4554
4622
  } finally {
4555
4623
  if (this.checkAbort === landing) this.checkAbort = undefined
4556
4624
  }
4557
- 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
4558
4633
  await this.withVerifyWrite(async () => {
4559
4634
  const state = (await readBuildFacts(store, slug)).value.state
4560
4635
  const key = verifyMemberKey(step, attempt)
4561
4636
  if (state.verifyStage.cancellations[key] || state.verifyStage.outcomes[key]) return
4562
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
4563
4641
  if (result.exitCode === 0) {
4564
4642
  await store.append(slug, {
4565
4643
  actor: KERNEL,
@@ -4569,8 +4647,8 @@ export class BuildRunner {
4569
4647
  return
4570
4648
  }
4571
4649
 
4572
- const output = [result.stdout, result.stderr].filter((s) => s !== '').join('\n')
4573
- 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)
4574
4652
  // Atomic deposit (D6): report artifact + verify.completed in one bundle;
4575
4653
  // the report routes back to implement via the engine (§15.6-A).
4576
4654
  await store.appendWithArtifacts(
@@ -4578,8 +4656,14 @@ export class BuildRunner {
4578
4656
  [
4579
4657
  {
4580
4658
  kind: verifyReportKind(step),
4581
- content: content || '(no output)',
4582
- 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
+ },
4583
4667
  },
4584
4668
  ],
4585
4669
  (deposited) => {
@@ -4601,6 +4685,29 @@ export class BuildRunner {
4601
4685
  })
4602
4686
  }
4603
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
+
4604
4711
  /** Agent-verify step (§5): a session with a pass/fail/skip verdict. */
4605
4712
  private async runAgentVerify(decision: RunAgentVerifyDecision): Promise<void> {
4606
4713
  await this.withKernelPhaseFailure(verifyPhase(decision.step), decision.attempt, () =>
@@ -5390,13 +5497,29 @@ export class BuildRunner {
5390
5497
  activeMs: number,
5391
5498
  cause: 'shutdown' | 'pause',
5392
5499
  ): Promise<void> {
5500
+ const { store, slug } = this.deps
5501
+ const session = started.payload.session
5502
+ const postStep = started.payload.phase === 'finalize' && started.payload.role !== 'finalize'
5393
5503
  if (
5394
5504
  cause === 'shutdown' &&
5395
5505
  (this.deps.workspaceProvider !== 'git-worktree' || this.deps.workspaceRemote === true)
5396
- )
5506
+ ) {
5507
+ // Nothing here can resume natively. An occurrence whose outcome is
5508
+ // already durable still closes its bracket; an unfinished one stays open
5509
+ // for the dispatcher to settle once the execution ends.
5510
+ const guard = await readTerminalGuardBoundary(
5511
+ store,
5512
+ slug,
5513
+ started.payload.phase,
5514
+ started.payload.round ?? 1,
5515
+ session,
5516
+ )
5517
+ const finished = postStep
5518
+ ? (await readBuildFacts(store, slug)).value.log.finalizeStepsDone.has(started.payload.role)
5519
+ : guard.value.diagnostic !== undefined
5520
+ if (finished) await this.endFinishedBracket(session, this.bracketStreams.get(session))
5397
5521
  return
5398
- const { store, slug } = this.deps
5399
- const session = started.payload.session
5522
+ }
5400
5523
  const state = (await readBuildFacts(store, slug)).value.state
5401
5524
  const native = state.sessions.open.find((s) => s.session === session)?.nativeHandle
5402
5525
  const producer = [...this.producerSessions.entries()].find(
@@ -5437,7 +5560,6 @@ export class BuildRunner {
5437
5560
  )
5438
5561
  const facts = await readBuildFacts(store, slug)
5439
5562
  if (facts.cursor !== guard.cursor) continue
5440
- const postStep = started.payload.phase === 'finalize' && started.payload.role !== 'finalize'
5441
5563
  if (
5442
5564
  postStep
5443
5565
  ? facts.value.log.finalizeStepsDone.has(started.payload.role)
@@ -5456,6 +5578,7 @@ export class BuildRunner {
5456
5578
  usage,
5457
5579
  started.payload.model,
5458
5580
  )
5581
+ else await this.endFinishedBracket(session)
5459
5582
  return
5460
5583
  }
5461
5584
  if (!facts.value.state.sessions.open.some((s) => s.session === session)) return
@@ -5779,8 +5902,10 @@ export class BuildRunner {
5779
5902
  if (spec.producerPhase !== undefined) this.producerSessions.delete(spec.producerPhase)
5780
5903
  }
5781
5904
  } catch (error) {
5905
+ // The durable terminal remains authoritative over optional cleanup;
5906
+ // the finished occurrence's bracket still closes.
5907
+ await this.endFinishedBracket(session, streamBracket)
5782
5908
  if (!(error instanceof StoreWriteTooLargeError)) throw error
5783
- // The durable terminal remains authoritative over optional cleanup.
5784
5909
  }
5785
5910
  return
5786
5911
  }
@@ -5804,7 +5929,9 @@ export class BuildRunner {
5804
5929
  // and best-effort transcript cleanup.
5805
5930
  }
5806
5931
  }
5807
- this.closeBracketStream(streamBracket, 'completed')
5932
+ // A terminal with no endable handle or transcript still finishes the
5933
+ // occurrence: close its bracket rather than leave it open.
5934
+ await this.endFinishedBracket(session, streamBracket)
5808
5935
  if (spec.producerPhase !== undefined) this.producerSessions.delete(spec.producerPhase)
5809
5936
  return
5810
5937
  }
@@ -6108,8 +6235,10 @@ export class BuildRunner {
6108
6235
  )
6109
6236
  }
6110
6237
  } catch (error) {
6238
+ // The durable terminal remains authoritative over optional cleanup;
6239
+ // the finished occurrence's bracket still closes.
6240
+ await this.endFinishedBracket(session, streamBracket)
6111
6241
  if (!(error instanceof StoreWriteTooLargeError)) throw error
6112
- // The durable terminal remains authoritative over optional cleanup.
6113
6242
  }
6114
6243
  return
6115
6244
  }
@@ -6134,7 +6263,9 @@ export class BuildRunner {
6134
6263
  // and best-effort transcript cleanup.
6135
6264
  }
6136
6265
  }
6137
- this.closeBracketStream(streamBracket, 'completed')
6266
+ // A terminal with no endable handle or transcript still finishes the
6267
+ // occurrence: close its bracket rather than leave it open.
6268
+ await this.endFinishedBracket(session, streamBracket)
6138
6269
  if (spec.producerPhase !== undefined) this.producerSessions.delete(spec.producerPhase)
6139
6270
  return
6140
6271
  }
@@ -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
+ }