@defrex/autobuild 1.18.0 → 1.19.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.
@@ -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'
@@ -604,18 +605,15 @@ function isPublicationBoundary(event: AbEvent, spec: SessionSpec, session: strin
604
605
  return false
605
606
  }
606
607
 
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
608
+ /** The continuation cause a recovering runner records for `session`. A
609
+ * session the dispatcher suspended after its execution ended was lost with
610
+ * its runner, so it resumes as a runner loss, as it would have while open. */
611
+ function recoveryCauseOf(
612
+ session: OpenSession,
613
+ suspended: boolean,
614
+ ): 'shutdown' | 'pause' | 'runner-loss' {
615
+ if (!suspended || session.suspendedExecution !== undefined) return 'runner-loss'
616
+ return session.suspensionCause ?? 'shutdown'
619
617
  }
620
618
 
621
619
  /** One judge panel run's inputs (SPEC §13.1.1). */
@@ -762,9 +760,10 @@ export class BuildRunner {
762
760
  continuation: {
763
761
  ...write.payload.continuation!,
764
762
  handle: current.nativeHandle,
765
- cause:
766
- current.suspensionCause ??
767
- (current.suspendedActiveMs !== undefined ? 'shutdown' : 'runner-loss'),
763
+ cause: recoveryCauseOf(
764
+ current,
765
+ current.suspensionCause !== undefined || current.suspendedActiveMs !== undefined,
766
+ ),
768
767
  activeMs:
769
768
  (current.continuation?.activeMs ?? 0) +
770
769
  (current.suspendedActiveMs ??
@@ -1218,17 +1217,17 @@ export class BuildRunner {
1218
1217
  else {
1219
1218
  this.recoveryBoundaryMs = this.deps.clock().getTime()
1220
1219
  retained.add(candidate.session)
1220
+ const cause = recoveryCauseOf(
1221
+ candidate,
1222
+ state.sessions.suspended.some((s) => s.session === candidate.session),
1223
+ )
1221
1224
  if (decision.kind === 'run-verify-stage')
1222
1225
  this.stageRecoveries.set(verifyMemberKey(candidate.phase!.slice(7), candidate.round!), {
1223
1226
  session: candidate,
1224
- cause: state.sessions.suspended.some((s) => s.session === candidate.session)
1225
- ? (candidate.suspensionCause ?? 'shutdown')
1226
- : 'runner-loss',
1227
+ cause,
1227
1228
  })
1228
1229
  else this.recovery = candidate
1229
- this.recoveryCause = state.sessions.suspended.some((s) => s.session === candidate.session)
1230
- ? (candidate.suspensionCause ?? 'shutdown')
1231
- : 'runner-loss'
1230
+ this.recoveryCause = cause
1232
1231
  }
1233
1232
  }
1234
1233
  for (const session of [...state.sessions.open, ...state.sessions.suspended]) {
@@ -3408,6 +3407,38 @@ export class BuildRunner {
3408
3407
  }
3409
3408
  }
3410
3409
 
3410
+ /** Close the bracket of an occurrence whose outcome is already durable when
3411
+ * no transcript can be deposited: `reclaimed` by this runner, never a
3412
+ * fabricated transcript. The stream closes first. Best effort: whatever an
3413
+ * ended execution still leaves open, the dispatcher settles. */
3414
+ private async endFinishedBracket(
3415
+ session: string,
3416
+ stream?: SessionBracketStream,
3417
+ outcome: StreamOutcome = 'completed',
3418
+ ): Promise<void> {
3419
+ const { store, slug } = this.deps
3420
+ try {
3421
+ await stream?.sink.close(outcome)
3422
+ for (;;) {
3423
+ const facts = await readBuildFacts(store, slug)
3424
+ const { state } = facts.value
3425
+ if (!state.sessions.open.some((open) => open.session === session)) return
3426
+ const ended = await store.appendIfCurrent(slug, facts.cursor, {
3427
+ actor: KERNEL,
3428
+ type: 'session.ended',
3429
+ payload: {
3430
+ session,
3431
+ outcome: 'reclaimed',
3432
+ reclaimedBy: { instance: this.deps.instance, resumedFromSeq: state.lastSeq },
3433
+ },
3434
+ })
3435
+ if (ended) return
3436
+ }
3437
+ } catch {
3438
+ // The durable terminal remains authoritative over bracket cleanup.
3439
+ }
3440
+ }
3441
+
3411
3442
  /** Handles live only here; every scheduling and barrier decision is read
3412
3443
  * from durable facts. A child runner isolates each occurrence's recovery,
3413
3444
  * provider fallback, stream and retry state without another workspace. */
@@ -3554,6 +3585,22 @@ export class BuildRunner {
3554
3585
  entry.runner.closeBracketStream(stream, 'aborted')
3555
3586
  await entry.runner.closeProducerSessions()
3556
3587
  }
3588
+ // A member whose step has its outcome is finished, so its bracket must
3589
+ // not outlive the stage: the next stage or finalize starts only after
3590
+ // it ends. Under parent shutdown, suspension settles each bracket.
3591
+ // Best effort: a failed read must not mask the stage's own error.
3592
+ if (!this.deps.shutdownSignal?.aborted)
3593
+ try {
3594
+ const { state } = (await readBuildFacts(store, slug)).value
3595
+ for (const open of state.sessions.open) {
3596
+ if (!open.phase.startsWith('verify:') || open.round === undefined) continue
3597
+ const key = verifyMemberKey(open.phase.slice(7), open.round)
3598
+ if (inFlight.get(key)?.done && state.verifyStage.outcomes[key] !== undefined)
3599
+ await this.endFinishedBracket(open.session)
3600
+ }
3601
+ } catch {
3602
+ // The dispatcher settles what an ended execution leaves open.
3603
+ }
3557
3604
  }
3558
3605
  }
3559
3606
 
@@ -5390,13 +5437,29 @@ export class BuildRunner {
5390
5437
  activeMs: number,
5391
5438
  cause: 'shutdown' | 'pause',
5392
5439
  ): Promise<void> {
5440
+ const { store, slug } = this.deps
5441
+ const session = started.payload.session
5442
+ const postStep = started.payload.phase === 'finalize' && started.payload.role !== 'finalize'
5393
5443
  if (
5394
5444
  cause === 'shutdown' &&
5395
5445
  (this.deps.workspaceProvider !== 'git-worktree' || this.deps.workspaceRemote === true)
5396
- )
5446
+ ) {
5447
+ // Nothing here can resume natively. An occurrence whose outcome is
5448
+ // already durable still closes its bracket; an unfinished one stays open
5449
+ // for the dispatcher to settle once the execution ends.
5450
+ const guard = await readTerminalGuardBoundary(
5451
+ store,
5452
+ slug,
5453
+ started.payload.phase,
5454
+ started.payload.round ?? 1,
5455
+ session,
5456
+ )
5457
+ const finished = postStep
5458
+ ? (await readBuildFacts(store, slug)).value.log.finalizeStepsDone.has(started.payload.role)
5459
+ : guard.value.diagnostic !== undefined
5460
+ if (finished) await this.endFinishedBracket(session, this.bracketStreams.get(session))
5397
5461
  return
5398
- const { store, slug } = this.deps
5399
- const session = started.payload.session
5462
+ }
5400
5463
  const state = (await readBuildFacts(store, slug)).value.state
5401
5464
  const native = state.sessions.open.find((s) => s.session === session)?.nativeHandle
5402
5465
  const producer = [...this.producerSessions.entries()].find(
@@ -5437,7 +5500,6 @@ export class BuildRunner {
5437
5500
  )
5438
5501
  const facts = await readBuildFacts(store, slug)
5439
5502
  if (facts.cursor !== guard.cursor) continue
5440
- const postStep = started.payload.phase === 'finalize' && started.payload.role !== 'finalize'
5441
5503
  if (
5442
5504
  postStep
5443
5505
  ? facts.value.log.finalizeStepsDone.has(started.payload.role)
@@ -5456,6 +5518,7 @@ export class BuildRunner {
5456
5518
  usage,
5457
5519
  started.payload.model,
5458
5520
  )
5521
+ else await this.endFinishedBracket(session)
5459
5522
  return
5460
5523
  }
5461
5524
  if (!facts.value.state.sessions.open.some((s) => s.session === session)) return
@@ -5779,8 +5842,10 @@ export class BuildRunner {
5779
5842
  if (spec.producerPhase !== undefined) this.producerSessions.delete(spec.producerPhase)
5780
5843
  }
5781
5844
  } catch (error) {
5845
+ // The durable terminal remains authoritative over optional cleanup;
5846
+ // the finished occurrence's bracket still closes.
5847
+ await this.endFinishedBracket(session, streamBracket)
5782
5848
  if (!(error instanceof StoreWriteTooLargeError)) throw error
5783
- // The durable terminal remains authoritative over optional cleanup.
5784
5849
  }
5785
5850
  return
5786
5851
  }
@@ -5804,7 +5869,9 @@ export class BuildRunner {
5804
5869
  // and best-effort transcript cleanup.
5805
5870
  }
5806
5871
  }
5807
- this.closeBracketStream(streamBracket, 'completed')
5872
+ // A terminal with no endable handle or transcript still finishes the
5873
+ // occurrence: close its bracket rather than leave it open.
5874
+ await this.endFinishedBracket(session, streamBracket)
5808
5875
  if (spec.producerPhase !== undefined) this.producerSessions.delete(spec.producerPhase)
5809
5876
  return
5810
5877
  }
@@ -6108,8 +6175,10 @@ export class BuildRunner {
6108
6175
  )
6109
6176
  }
6110
6177
  } catch (error) {
6178
+ // The durable terminal remains authoritative over optional cleanup;
6179
+ // the finished occurrence's bracket still closes.
6180
+ await this.endFinishedBracket(session, streamBracket)
6111
6181
  if (!(error instanceof StoreWriteTooLargeError)) throw error
6112
- // The durable terminal remains authoritative over optional cleanup.
6113
6182
  }
6114
6183
  return
6115
6184
  }
@@ -6134,7 +6203,9 @@ export class BuildRunner {
6134
6203
  // and best-effort transcript cleanup.
6135
6204
  }
6136
6205
  }
6137
- this.closeBracketStream(streamBracket, 'completed')
6206
+ // A terminal with no endable handle or transcript still finishes the
6207
+ // occurrence: close its bracket rather than leave it open.
6208
+ await this.endFinishedBracket(session, streamBracket)
6138
6209
  if (spec.producerPhase !== undefined) this.producerSessions.delete(spec.producerPhase)
6139
6210
  return
6140
6211
  }
@@ -271,7 +271,12 @@ import { readBuildDigests, readForgeHealth } from '../store/reduced-reads'
271
271
  import { enforceOptimizationStop } from './optimization-stop'
272
272
  import { recordOptimizationActivity } from './optimization-activity'
273
273
  import { reconcileMergedAttempts } from './optimization-merges'
274
- import { readBuildSelector, readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
274
+ import {
275
+ readBuildSelector,
276
+ readBuildFacts,
277
+ readTerminalGuardBoundary,
278
+ type CurrentBuildFacts,
279
+ } from '../store/reduced-reads'
275
280
  import { ensureExecutionProgress } from './execution-no-progress'
276
281
  import { ticketIdentity } from '../ports/tickets/identity'
277
282
  import { holdsState, ticketLifecycle } from '../ports/tickets/lifecycle'
@@ -339,6 +344,10 @@ import type { IdSource } from '../ids'
339
344
  import { recordAutoMergeDeferralObservation } from '../kernel/auto-merge'
340
345
  import type { AutoMergeDefaultFact } from '../kernel/auto-merge-default'
341
346
  import { decideNextFromFacts, landingRestackDue } from '../kernel/engine'
347
+ import {
348
+ endedExecutionSessionSettlement,
349
+ settlementTerminalChecks,
350
+ } from '../kernel/session-settlement'
342
351
  import { composeBuildConfig } from '../config/live'
343
352
  import { profileConflictDiagnostic, selectProfile } from '../config/profiles'
344
353
  import {
@@ -4047,6 +4056,32 @@ export class Dispatcher {
4047
4056
  loaded ??= (await readBuildFacts(this.store, record.slug)).value
4048
4057
  return loaded
4049
4058
  }
4059
+ // An ended execution's open sessions would hold the leaf's landing
4060
+ // decision; settle them in place before anything below reads it.
4061
+ if (
4062
+ state.kind !== 'node' &&
4063
+ initialFacts.open === null &&
4064
+ !executionLeaseLive &&
4065
+ !launched.has(record.slug) &&
4066
+ state.sessions.open.length > 0 &&
4067
+ state.executions.length > 0
4068
+ ) {
4069
+ const prior = operation
4070
+ operation = 'session settlement'
4071
+ const facts = await this.store.buildFacts(record.slug)
4072
+ // A done or aborted build resumes nothing: no decision is needed
4073
+ // to end what its ended execution left open.
4074
+ const terminal = facts.state.status === 'done' || facts.state.status === 'aborted'
4075
+ const decision = terminal
4076
+ ? undefined
4077
+ : await this.decideBuild(record.slug, facts.state, facts.log, report)
4078
+ if (
4079
+ (terminal || decision !== undefined) &&
4080
+ (await this.settleEndedExecutionSessions(record.slug, facts, decision))
4081
+ )
4082
+ ({ state, log } = await this.store.buildFacts(record.slug))
4083
+ operation = prior
4084
+ }
4050
4085
  const pollStart = state
4051
4086
  const pollChildren =
4052
4087
  state.kind === 'node' ? await this.nodePollingChildren(record.slug) : []
@@ -9768,6 +9803,116 @@ export class Dispatcher {
9768
9803
 
9769
9804
  /** `carried` is a deferred-work entry's pass: its facts are already read,
9770
9805
  * and the first-claim grace does not apply. */
9806
+ /** Settle, in place and without a runner, every session an ended execution
9807
+ * left open (SPEC §15.6-C), on running, held and terminal builds alike: an
9808
+ * unfinished occurrence with a native handle of a live build is suspended as
9809
+ * resumable, every other session is ended `reclaimed`. A terminal build
9810
+ * needs no `decision`. Each write is conditional on the cursor, so a runner that
9811
+ * attached meanwhile wins; the next visit decides again. Returns whether
9812
+ * anything was written. */
9813
+ private async settleEndedExecutionSessions(
9814
+ slug: string,
9815
+ facts: CurrentBuildFacts,
9816
+ decision: ReturnType<typeof decideNextFromFacts> | undefined,
9817
+ ): Promise<boolean> {
9818
+ const { state } = facts
9819
+ if (facts.open !== null) return false
9820
+ // A hold (pause, escalation) keeps the engine waiting, so its decision
9821
+ // cannot say whether an occurrence is finished. Its durable terminal can:
9822
+ // an unfinished one keeps its native continuation through suspension.
9823
+ const unfinished = new Set<string>()
9824
+ for (const session of settlementTerminalChecks(state, decision)) {
9825
+ const postStep = session.phase === 'finalize' && session.role !== 'finalize'
9826
+ const finished = postStep
9827
+ ? facts.log.finalizeStepsDone.has(session.role)
9828
+ : (
9829
+ await readTerminalGuardBoundary(
9830
+ this.store,
9831
+ slug,
9832
+ session.phase,
9833
+ session.round ?? 1,
9834
+ session.session,
9835
+ )
9836
+ ).value.diagnostic !== undefined
9837
+ if (!finished) unfinished.add(session.session)
9838
+ }
9839
+ const { suspend, end } = endedExecutionSessionSettlement(state, decision, unfinished)
9840
+ if (suspend.length === 0 && end.length === 0) return false
9841
+ const ended = state.executions.at(-1)
9842
+ const outcome = facts.lastExecution
9843
+ if (ended === undefined || outcome === 'open' || outcome === 'none') return false
9844
+ const execution = { instance: ended.instance, outcome }
9845
+ const now = this.deps.clock().getTime()
9846
+ let cursor = state.lastSeq
9847
+ let wrote = false
9848
+ for (const session of end) {
9849
+ const appended = await this.store.appendIfCurrent(slug, cursor, {
9850
+ actor: KERNEL,
9851
+ type: 'session.ended',
9852
+ payload: {
9853
+ session: session.session,
9854
+ outcome: 'reclaimed',
9855
+ reclaimedBy: {
9856
+ instance: this.deps.ids('session-settlement'),
9857
+ resumedFromSeq: state.lastSeq,
9858
+ },
9859
+ },
9860
+ })
9861
+ if (appended === null) return wrote
9862
+ cursor = appended.seq
9863
+ wrote = true
9864
+ }
9865
+ for (const session of suspend) {
9866
+ const { session: id, phase, round, role, runner, model } = session
9867
+ const appended = await this.store.appendWithArtifactsIfCurrent(
9868
+ slug,
9869
+ cursor,
9870
+ [
9871
+ {
9872
+ kind: 'transcript',
9873
+ content: JSON.stringify({ session: id, interrupted: true, execution }),
9874
+ metadata: {
9875
+ session: id,
9876
+ phase,
9877
+ round,
9878
+ role,
9879
+ runner,
9880
+ ...(model !== undefined ? { model } : {}),
9881
+ interrupted: true,
9882
+ },
9883
+ },
9884
+ ],
9885
+ (deposited) => ({
9886
+ actor: KERNEL,
9887
+ type: 'session.suspended',
9888
+ payload: {
9889
+ session: id,
9890
+ phase,
9891
+ ...(round !== undefined ? { round } : {}),
9892
+ handle: session.nativeHandle,
9893
+ cause: 'shutdown',
9894
+ activeMs: Math.max(0, now - Date.parse(session.startedAt)),
9895
+ transcript: { kind: deposited[0]!.kind, rev: deposited[0]!.revision },
9896
+ execution,
9897
+ },
9898
+ }),
9899
+ )
9900
+ if (appended === null) return wrote
9901
+ cursor = appended.event.seq
9902
+ wrote = true
9903
+ }
9904
+ // Settling the last open session can complete a summary boundary the
9905
+ // ended guest never requested. The host's publication settlement repairs
9906
+ // that, as it does before any launch; it is best effort here.
9907
+ if (wrote)
9908
+ try {
9909
+ await this.settlePublication?.(slug)
9910
+ } catch (error) {
9911
+ rethrowAuthorityLapse(error)
9912
+ }
9913
+ return wrote
9914
+ }
9915
+
9771
9916
  private async sweepBuildPass(
9772
9917
  record: BuildRecord,
9773
9918
  report: TickReport,
@@ -9780,7 +9925,7 @@ export class Dispatcher {
9780
9925
  if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
9781
9926
  }
9782
9927
  const facts = carried?.facts ?? (await this.store.buildFacts(record.slug))
9783
- const state = facts.state
9928
+ let state = facts.state
9784
9929
  if (mixedVersionDeferred(state)) {
9785
9930
  return (await deferMixedVersion(this.store, record.slug)) ? 'waiting' : undefined
9786
9931
  }
@@ -9887,6 +10032,16 @@ export class Dispatcher {
9887
10032
  // proved end settles first (completion facts, lease release, publication)
9888
10033
  // and then falls through to the normal decision; a provider-proved loss
9889
10034
  // falls through to the existing stale path below.
10035
+ // An ended execution's open sessions are settled in place, without a
10036
+ // runner. Orphan relaunch remains for sessions no recorded execution
10037
+ // opened, and for a settlement that lost a race.
10038
+ if (
10039
+ facts.open === null &&
10040
+ !launched.has(record.slug) &&
10041
+ state.sessions.open.length > 0 &&
10042
+ (await this.settleEndedExecutionSessions(record.slug, facts, decision))
10043
+ )
10044
+ state = (await this.store.buildFacts(record.slug)).state
9890
10045
  let orphanRecoveryDue = orphanEligible(state) && facts.open === null
9891
10046
  const foreignExecution = facts.open
9892
10047
  // A provider- or log-proved end in the same generation re-attaches in
@@ -9928,7 +10083,13 @@ export class Dispatcher {
9928
10083
  // Unknown liveness is never proof that an open execution is dead.
9929
10084
  // Settlement may itself raise provider attention. Revalidate cleanup
9930
10085
  // eligibility from the advanced canonical state before admission.
9931
- orphanRecoveryDue = orphanEligible((await this.store.buildFacts(record.slug)).state)
10086
+ let settled = await this.store.buildFacts(record.slug)
10087
+ if (
10088
+ settled.state.sessions.open.length > 0 &&
10089
+ (await this.settleEndedExecutionSessions(record.slug, settled, decision))
10090
+ )
10091
+ settled = await this.store.buildFacts(record.slug)
10092
+ orphanRecoveryDue = orphanEligible(settled.state)
9932
10093
  if (settlement === 'settled') {
9933
10094
  report.settled += 1
9934
10095
  endedInPlace = true
@@ -28,6 +28,35 @@ import { readBuildFacts } from '../store/reduced-reads'
28
28
  import { defineReducer } from '../kernel/incremental'
29
29
  import type { BuildStore } from '../store/types'
30
30
 
31
+ /** A done or aborted build resumes nothing, so the sessions an exited
32
+ * execution left open are ended `reclaimed` (SPEC §15.6-C). Callers run this
33
+ * once the provider proves the execution exited and before they record
34
+ * `execution.ended`: a crash in between leaves the execution open, so the
35
+ * build stays visited and the next settlement repeats this. One reduced read
36
+ * per call, and a CAS write per leftover session. */
37
+ export async function endTerminalBuildSessions(
38
+ store: Pick<BuildStore, 'appendIfCurrent'> & Parameters<typeof readBuildFacts>[0],
39
+ slug: string,
40
+ instance: string,
41
+ ): Promise<void> {
42
+ for (;;) {
43
+ const facts = await readBuildFacts(store, slug)
44
+ const { state } = facts.value
45
+ if (state.status !== 'done' && state.status !== 'aborted') return
46
+ const session = state.sessions.open[0]
47
+ if (session === undefined) return
48
+ await store.appendIfCurrent(slug, facts.cursor, {
49
+ actor: KERNEL,
50
+ type: 'session.ended',
51
+ payload: {
52
+ session: session.session,
53
+ outcome: 'reclaimed',
54
+ reclaimedBy: { instance, resumedFromSeq: state.lastSeq },
55
+ },
56
+ })
57
+ }
58
+ }
59
+
31
60
  export interface OpenExecution {
32
61
  instance: string
33
62
  workspaceRef: string
@@ -218,6 +247,7 @@ export async function settleOpenExecution(
218
247
  const request = (await readBuildFacts(deps.store, slug)).value.state.drainingExecutions?.[
219
248
  open.instance
220
249
  ]?.relaunch
250
+ await endTerminalBuildSessions(deps.store, slug, open.instance)
221
251
  const ended: EventWrite<'execution.ended'> =
222
252
  observation.state === 'ended'
223
253
  ? {