@defrex/autobuild 1.17.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.
Files changed (65) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +85 -11
  3. package/docs/architecture.md +57 -11
  4. package/docs/configuration.md +11 -3
  5. package/docs/dispatcher-hosting.md +5 -3
  6. package/docs/operator-api.md +14 -1
  7. package/docs/plugin-authoring.md +29 -1
  8. package/docs/remote-ticket-protocol.md +34 -1
  9. package/docs/restacking.md +5 -0
  10. package/docs/setup.md +9 -3
  11. package/docs/ticket-sources.md +28 -1
  12. package/docs/troubleshooting.md +15 -0
  13. package/docs/workspaces.md +1 -1
  14. package/package.json +4 -4
  15. package/packages/core/src/cli/dashboard/refresh.ts +8 -0
  16. package/packages/core/src/cli/dispatch.ts +2 -0
  17. package/packages/core/src/config/schema.ts +2 -1
  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/events/repository.ts +37 -1
  21. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/d41044cb2e54809c.json +194 -0
  22. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e012e9e8f3e82935.json +424 -0
  23. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e0f89f52e48cbf62.json +197 -0
  24. package/packages/core/src/kernel/janitor-failure.ts +1 -0
  25. package/packages/core/src/kernel/reducer-revisions.ts +9 -0
  26. package/packages/core/src/kernel/reducer.ts +6 -0
  27. package/packages/core/src/kernel/repository-read-facts.ts +9 -2
  28. package/packages/core/src/kernel/session-settlement.ts +82 -0
  29. package/packages/core/src/kernel/ticket-preparation.ts +10 -0
  30. package/packages/core/src/operator/registry.ts +64 -9
  31. package/packages/core/src/operator/tickets.ts +139 -25
  32. package/packages/core/src/plugin-sdk/index.ts +4 -0
  33. package/packages/core/src/plugins/manifest.ts +1 -1
  34. package/packages/core/src/ports/tickets/completion.ts +71 -0
  35. package/packages/core/src/ports/tickets/contract.ts +73 -0
  36. package/packages/core/src/ports/tickets/github-fake.ts +8 -0
  37. package/packages/core/src/ports/tickets/github-issues.ts +1 -0
  38. package/packages/core/src/ports/tickets/github.ts +18 -6
  39. package/packages/core/src/ports/tickets/hosted-index.ts +8 -0
  40. package/packages/core/src/ports/tickets/linear.ts +18 -2
  41. package/packages/core/src/ports/tickets/remote-protocol.ts +37 -8
  42. package/packages/core/src/ports/tickets/remote.ts +41 -3
  43. package/packages/core/src/ports/tickets/tree.ts +11 -1
  44. package/packages/core/src/ports/types.ts +32 -4
  45. package/packages/core/src/ports/workspace/vercel-sandbox.ts +78 -25
  46. package/packages/core/src/processes/build-runner.ts +100 -29
  47. package/packages/core/src/processes/dispatcher.ts +1016 -279
  48. package/packages/core/src/processes/execution-settlement.ts +30 -0
  49. package/packages/core/src/processes/pass-stages.ts +32 -6
  50. package/packages/core/src/store/reducer-value-shapes.json +8440 -8346
  51. package/packages/core/src/store/remote/released-clients.json +22 -0
  52. package/packages/core/src/store/remote/released-reducer-values/1.18.0.json +36436 -0
  53. package/packages/core/src/store/remote/released-reducer-values/1.19.0.json +36461 -0
  54. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  55. package/packages/core/src/testing/dispatch-read-budget.ts +143 -16
  56. package/packages/core/src/testing/index.ts +2 -0
  57. package/packages/core/src/testing/reduced-read-budget.ts +234 -2
  58. package/skills/guide/SKILL.md +45 -15
  59. package/skills/guide/references/operator-api.md +14 -1
  60. package/skills/guide/references/plugin-authoring.md +29 -1
  61. package/skills/guide/references/remote-ticket-protocol.md +34 -1
  62. package/skills/guide/references/restacking.md +5 -0
  63. package/skills/guide/references/setup.md +9 -3
  64. package/skills/operate/SKILL.md +18 -1
  65. package/templates/hosted-service/package.json +2 -2
@@ -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 {
@@ -699,8 +708,15 @@ export interface TickReport {
699
708
  * is recorded in `dispatcher.work-deferred` and the next tick runs it
700
709
  * first. */
701
710
  recoveryDeferred: number
711
+ /** Ticket preparations this bounded tick carried to the next invocation
712
+ * (#1431): an admission the work deadline left no time to prepare, or a
713
+ * preparation the deadline cut. Recorded in `dispatcher.work-deferred`;
714
+ * the next tick resumes each first, and none is handed back. Absent when
715
+ * none was carried. */
716
+ preparationsCarried?: number
702
717
  /** One line per build whose deadline-gated work (a provision, a cut launch
703
- * or a recovery step) this tick deferred for budget, naming the step. */
718
+ * or a recovery step) this tick deferred for budget, naming the step, and
719
+ * one per carried ticket preparation, naming the ticket. */
704
720
  deferredDiagnostics: string[]
705
721
  /** Dispatch (§12): builds created and launched. With durable supervision
706
722
  * this counts ACCEPTED dispatches — durable boundaries recorded — not
@@ -845,6 +861,11 @@ const IDENTITY_RELEASES_PER_APPEND = 256
845
861
  // ── Dispatcher ───────────────────────────────────────────────────────────────
846
862
 
847
863
  const DEFAULT_SLUG_NAMING_TIMEOUT_MS = 10_000
864
+ /** What one ticket preparation (claim, asset pin, spec import, the slug
865
+ * naming ceiling and its store writes) needs, with headroom: a bounded pass
866
+ * with less time left before its work deadline carries the admission
867
+ * instead of starting it (#1431). */
868
+ const DEFAULT_PREPARATION_ESTIMATE_MS = 30_000
848
869
  /** Bound on -2/-3/… candidates one claim may probe for a free slug. */
849
870
  const MAX_SLUG_CANDIDATES = 100
850
871
  /** Body of the comment dispatch posts on every claimed ticket. The
@@ -910,6 +931,10 @@ export interface DispatcherOpts {
910
931
  /** Internal deadline for the optional pre-build naming seam. Production is
911
932
  * fixed; injection exists only so timeout behavior is deterministic in tests. */
912
933
  slugNamingTimeoutMs?: number
934
+ /** The time a bounded pass needs left before its work deadline to start a
935
+ * ticket preparation; with less, intake journals the admission and the
936
+ * next invocation prepares it first (#1431). Default 30 s. */
937
+ preparationEstimateMs?: number
913
938
  /** Must match the HarvestRunner's durable outer recovery budget. */
914
939
  maxHarvestRecoveryAttempts?: number
915
940
  /** Backstop for the crash window between a `workspace.provision-started`
@@ -990,6 +1015,42 @@ interface DeferredWorkEntry {
990
1015
  /** Most entries one `dispatcher.work-deferred` hint carries. */
991
1016
  const MAX_DEFERRED_WORK = 64
992
1017
 
1018
+ /** One carried ticket-preparation attempt in `dispatcher.work-deferred`. */
1019
+ interface CarriedPreparation {
1020
+ ticket: TicketRef
1021
+ attempt: string
1022
+ }
1023
+
1024
+ /** Most ticket-preparation attempts one hint carries. */
1025
+ const MAX_CARRIED_PREPARATIONS = 8
1026
+
1027
+ /** What one ticket preparation reached: a build `started`; the ticket `left`
1028
+ * the queue without a build (claim refused or bounced); it was `blocked` by
1029
+ * a blocker the claim found; the work deadline `carried` it to the next
1030
+ * invocation; or nothing durable was started and the loop must `stop`. */
1031
+ type PreparationOutcome = 'started' | 'left' | 'blocked' | 'carried' | 'stop'
1032
+
1033
+ /** One ticket preparation's inputs: the ticket sample it prepares from, its
1034
+ * attempt, the node target and claim level admission resolved, and how the
1035
+ * caller records outcomes. `resume` marks a carried attempt the deferred
1036
+ * stage or preparation recovery continues (#1431). */
1037
+ interface PreparationInput {
1038
+ ticket: Ticket
1039
+ attempt: TicketPreparation
1040
+ target:
1041
+ | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
1042
+ | undefined
1043
+ level: BuildPriority
1044
+ report: TickReport
1045
+ launched: Set<string>
1046
+ settle: (outcome: TargetedOutcome) => void
1047
+ /** The pass part a carry is recorded on. */
1048
+ part: PassStagePart
1049
+ resume?: true
1050
+ autoMergeUser?: string
1051
+ autoMergeSeedFact?: AutoMergeDefaultFact
1052
+ }
1053
+
993
1054
  /** Process-local launch coordination result. Durable lease acquisition remains
994
1055
  * the BuildRunner's responsibility; "scheduled" means only that this process
995
1056
  * accepted a runner launch rather than suppressing a known in-flight slug. */
@@ -1147,6 +1208,14 @@ function errorText(error: unknown): string {
1147
1208
  return error instanceof Error ? error.message : String(error)
1148
1209
  }
1149
1210
 
1211
+ /** The report and dispatch-log line naming one carried ticket preparation. */
1212
+ function preparationCarryLine(ticket: TicketRef, detail?: string): string {
1213
+ return (
1214
+ `ticket ${ticket.id}: preparation carried by the invocation budget; the next invocation runs it first` +
1215
+ (detail !== undefined ? ` — ${detail}` : '')
1216
+ )
1217
+ }
1218
+
1150
1219
  /** The report and dispatch-log line naming one deferral by build and step. */
1151
1220
  function deferralLine(slug: string, deferral: { step: DeferredWorkStep; detail?: string }): string {
1152
1221
  return (
@@ -1406,6 +1475,7 @@ export class Dispatcher {
1406
1475
  )
1407
1476
  }
1408
1477
  private readonly slugNamingTimeoutMs: number
1478
+ private readonly preparationEstimateMs: number
1409
1479
  private readonly maxHarvestRecoveryAttempts: number
1410
1480
  private readonly provisionStaleMs: number
1411
1481
  /** Process-local background provisioning, keyed by slug. A tick that sees a
@@ -1438,6 +1508,23 @@ export class Dispatcher {
1438
1508
  >()
1439
1509
  /** The durable hint as last read or written. */
1440
1510
  private recordedDeferrals: DeferredWorkEntry[] = []
1511
+ /** Per tick, keyed by attempt: ticket preparations this tick carried to
1512
+ * the next invocation (#1431), with the reason. */
1513
+ private readonly tickPreparationCarries = new Map<
1514
+ string,
1515
+ { ticket: TicketRef; detail?: string }
1516
+ >()
1517
+ /** Per tick, in carried order: the hint's carried preparation attempts not
1518
+ * yet retired. */
1519
+ private readonly carriedPreparationsOutstanding = new Map<
1520
+ string,
1521
+ { ticket: TicketRef; visited: boolean }
1522
+ >()
1523
+ /** Per tick: carried attempts the early stage resumed, which preparation
1524
+ * recovery then skips. */
1525
+ private readonly tickResumedAttempts = new Set<string>()
1526
+ /** The hint's preparation entries as last read or written. */
1527
+ private recordedPreparationCarries: CarriedPreparation[] = []
1441
1528
  /** The current tick's options, for writes made from deferral sites. */
1442
1529
  private tickOpts: TickOpts = {}
1443
1530
  /** Serializes hint writes so concurrent deferral notes never race. */
@@ -1555,6 +1642,7 @@ export class Dispatcher {
1555
1642
  })
1556
1643
  this.leaseTtlMs = deps.opts?.leaseTtlMs ?? 0
1557
1644
  this.slugNamingTimeoutMs = deps.opts?.slugNamingTimeoutMs ?? DEFAULT_SLUG_NAMING_TIMEOUT_MS
1645
+ this.preparationEstimateMs = deps.opts?.preparationEstimateMs ?? DEFAULT_PREPARATION_ESTIMATE_MS
1558
1646
  this.maxHarvestRecoveryAttempts =
1559
1647
  deps.opts?.maxHarvestRecoveryAttempts ?? DEFAULT_MAX_HARVEST_RECOVERY_ATTEMPTS
1560
1648
  this.provisionStaleMs = deps.opts?.provisionStaleMs ?? DEFAULT_PROVISION_STALE_MS
@@ -1768,6 +1856,9 @@ export class Dispatcher {
1768
1856
  this.deferralsFinished = false
1769
1857
  this.tickPrioritized.clear()
1770
1858
  this.carriedOutstanding.clear()
1859
+ this.tickPreparationCarries.clear()
1860
+ this.carriedPreparationsOutstanding.clear()
1861
+ this.tickResumedAttempts.clear()
1771
1862
  this.deferralWriteFailure = undefined
1772
1863
  this.tickOpts = opts
1773
1864
  this.admissionBoundary = false
@@ -1779,13 +1870,19 @@ export class Dispatcher {
1779
1870
  if (opts.viewRefreshed !== true) await this.store.refresh()
1780
1871
  // The durable deferral hint from the previous invocation: zero extra
1781
1872
  // reads, it is part of the repository facts the refresh reduced.
1782
- this.recordedDeferrals = (this.store.repositoryFacts().deferredWork?.builds ?? []).map(
1783
- ({ slug, step, instance }) => ({
1784
- slug,
1785
- step,
1786
- ...(instance !== undefined ? { instance } : {}),
1787
- }),
1788
- )
1873
+ const deferredWork = this.store.repositoryFacts().deferredWork
1874
+ this.recordedDeferrals = (deferredWork?.builds ?? []).map(({ slug, step, instance }) => ({
1875
+ slug,
1876
+ step,
1877
+ ...(instance !== undefined ? { instance } : {}),
1878
+ }))
1879
+ this.recordedPreparationCarries = (deferredWork?.tickets ?? []).map(({ ticket, attempt }) => ({
1880
+ ticket,
1881
+ attempt,
1882
+ }))
1883
+ for (const { ticket, attempt } of this.recordedPreparationCarries)
1884
+ if (!this.carriedPreparationsOutstanding.has(attempt))
1885
+ this.carriedPreparationsOutstanding.set(attempt, { ticket, visited: false })
1789
1886
  // The rotated loops' positions, from the same reduced facts: no read.
1790
1887
  this.passCursors =
1791
1888
  opts.deadlineAt === undefined
@@ -1859,7 +1956,7 @@ export class Dispatcher {
1859
1956
  if (opts.observationOnly) return report
1860
1957
  if (this.outOfBudget(opts)) return report
1861
1958
  await this.runStage('preparations', opts, (stageOpts) =>
1862
- this.recoverTicketPreparations(report, stageOpts),
1959
+ this.recoverTicketPreparations(report, launched, paused, stageOpts),
1863
1960
  )
1864
1961
  if (this.outOfBudget(opts)) return report
1865
1962
  await this.runStage('janitor', opts, (stageOpts) => this.janitor(report, launched, stageOpts))
@@ -2036,11 +2133,16 @@ export class Dispatcher {
2036
2133
  const report = structuredClone(this.inFlightReport)
2037
2134
  // The deferrals so far, counted as the finished tick would count them;
2038
2135
  // a finished tick already counted them on its report.
2039
- if (!this.deferralsFinished)
2136
+ if (!this.deferralsFinished) {
2040
2137
  for (const [slug, deferral] of this.tickDeferrals) {
2041
2138
  if (deferral.step !== 'provision') report.recoveryDeferred += 1
2042
2139
  report.deferredDiagnostics.push(deferralLine(slug, deferral))
2043
2140
  }
2141
+ if (this.tickPreparationCarries.size > 0)
2142
+ report.preparationsCarried = this.tickPreparationCarries.size
2143
+ for (const { ticket, detail } of this.tickPreparationCarries.values())
2144
+ report.deferredDiagnostics.push(preparationCarryLine(ticket, detail))
2145
+ }
2044
2146
  return { ...report, stages: this.pass.summary() }
2045
2147
  }
2046
2148
 
@@ -2479,7 +2581,7 @@ export class Dispatcher {
2479
2581
  // checked, needs the pass.
2480
2582
  const now = this.deps.clock()
2481
2583
  const measured = await this.capacityBuilds(launched, true)
2482
- const projection = dispatchCapacity(measured, config.capacity, now, {
2584
+ const projection = this.measureCapacity(measured, config.capacity, now, {
2483
2585
  claims: this.claims(),
2484
2586
  startRequests: this.startClaims(),
2485
2587
  })
@@ -3954,6 +4056,32 @@ export class Dispatcher {
3954
4056
  loaded ??= (await readBuildFacts(this.store, record.slug)).value
3955
4057
  return loaded
3956
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
+ }
3957
4085
  const pollStart = state
3958
4086
  const pollChildren =
3959
4087
  state.kind === 'node' ? await this.nodePollingChildren(record.slug) : []
@@ -4944,8 +5072,8 @@ export class Dispatcher {
4944
5072
  let outcome = this.slotAdmission(
4945
5073
  slug,
4946
5074
  priority,
4947
- dispatchCapacity(others, capacity, now).occupied,
4948
- dispatchCapacity(builds, capacity, now, {
5075
+ this.measureCapacity(others, capacity, now).occupied,
5076
+ this.measureCapacity(builds, capacity, now, {
4949
5077
  claims: this.claims(),
4950
5078
  startRequests: this.startClaims(),
4951
5079
  }),
@@ -5217,7 +5345,7 @@ export class Dispatcher {
5217
5345
  (only === undefined || build.record.slug === only),
5218
5346
  )
5219
5347
  if (proposers.length === 0) return
5220
- const projection = dispatchCapacity(builds, this.deps.config.capacity, now, {
5348
+ const projection = this.measureCapacity(builds, this.deps.config.capacity, now, {
5221
5349
  claims: this.claims(),
5222
5350
  startRequests: this.startClaims(),
5223
5351
  })
@@ -5647,12 +5775,12 @@ export class Dispatcher {
5647
5775
  const outcome = this.slotAdmission(
5648
5776
  slug,
5649
5777
  buildPriority(node.state),
5650
- dispatchCapacity(
5778
+ this.measureCapacity(
5651
5779
  builds.filter((build) => build.record.slug !== slug),
5652
5780
  capacity,
5653
5781
  now,
5654
5782
  ).occupied,
5655
- dispatchCapacity(builds, capacity, now, {
5783
+ this.measureCapacity(builds, capacity, now, {
5656
5784
  claims: this.claims(),
5657
5785
  startRequests: this.startClaims(),
5658
5786
  }),
@@ -9104,13 +9232,54 @@ export class Dispatcher {
9104
9232
  paused: boolean,
9105
9233
  opts: TickOpts,
9106
9234
  ): Promise<void> {
9107
- if (this.carriedOutstanding.size === 0) return this.pass.total('deferred', 0)
9235
+ const carriedPreparations = this.carriedPreparationsOutstanding.size
9236
+ if (this.carriedOutstanding.size === 0 && carriedPreparations === 0)
9237
+ return this.pass.total('deferred', 0)
9238
+ this.pass.total('deferred', this.carriedOutstanding.size + carriedPreparations)
9239
+ if (this.carriedOutstanding.size > 0)
9240
+ await this.serviceDeferredBuilds(report, launched, paused, opts)
9241
+ // Carried ticket preparations (#1431), after the carried builds: each
9242
+ // attempt resumes from its durable boundaries, with no fleet read.
9243
+ for (const attempt of [...this.carriedPreparationsOutstanding.keys()]) {
9244
+ if (!this.passItem(opts, 'deferred')) break
9245
+ const entry = this.carriedPreparationsOutstanding.get(attempt)!
9246
+ const held = this.store.repositoryFacts().preparation[attempt]
9247
+ if (held === undefined) {
9248
+ this.carriedPreparationsOutstanding.delete(attempt)
9249
+ continue
9250
+ }
9251
+ entry.visited = true
9252
+ this.tickResumedAttempts.add(attempt)
9253
+ let outcome: 'done' | 'waiting' | 'failed'
9254
+ try {
9255
+ outcome = await this.resumeCarriedPreparation(held, report, launched, paused, 'deferred')
9256
+ } catch (error) {
9257
+ rethrowAuthorityLapse(error)
9258
+ // Contained like a recovery failure; the attempt's stamp resumes it
9259
+ // in a later pass.
9260
+ report.janitorFailed += 1
9261
+ report.janitorDiagnostics.push(String(error))
9262
+ outcome = 'failed'
9263
+ }
9264
+ const interrupted = this.budgetSpent(this.tickOpts)
9265
+ if (outcome !== 'waiting' && !interrupted && !this.tickPreparationCarries.has(attempt))
9266
+ this.carriedPreparationsOutstanding.delete(attempt)
9267
+ }
9268
+ await this.persistDeferrals()
9269
+ }
9270
+
9271
+ /** The carried builds of `serviceDeferredWork`. */
9272
+ private async serviceDeferredBuilds(
9273
+ report: TickReport,
9274
+ launched: Set<string>,
9275
+ paused: boolean,
9276
+ opts: TickOpts,
9277
+ ): Promise<void> {
9108
9278
  // Never the default form: it would run the mixed-version check for every
9109
9279
  // compatibility-bearing build. `sweepBuild` checks each carried build.
9110
9280
  const entries = new Map(
9111
9281
  (await this.repoBuildDigests(true)).map((entry) => [entry.record.slug, entry]),
9112
9282
  )
9113
- this.pass.total('deferred', this.carriedOutstanding.size)
9114
9283
  for (const slug of [...this.carriedOutstanding.keys()]) {
9115
9284
  if (!this.passItem(opts, 'deferred')) break
9116
9285
  const entry = this.carriedOutstanding.get(slug)!
@@ -9132,7 +9301,6 @@ export class Dispatcher {
9132
9301
  if (outcome !== 'waiting' && !interrupted && !this.tickDeferrals.has(slug))
9133
9302
  this.retireCarried(slug)
9134
9303
  }
9135
- await this.persistDeferrals()
9136
9304
  }
9137
9305
 
9138
9306
  /**
@@ -9347,9 +9515,59 @@ export class Dispatcher {
9347
9515
  this.reportedDeferrals.add(slug)
9348
9516
  lines.push(deferralLine(slug, deferral))
9349
9517
  }
9518
+ lines.push(...this.unreportedPreparationCarries())
9350
9519
  return lines
9351
9520
  }
9352
9521
 
9522
+ /** This tick's carried preparations not yet named in a report or teardown
9523
+ * line, each marked reported. */
9524
+ private unreportedPreparationCarries(): string[] {
9525
+ const lines: string[] = []
9526
+ for (const [attempt, { ticket, detail }] of this.tickPreparationCarries) {
9527
+ const key = `prep:${attempt}`
9528
+ if (this.reportedDeferrals.has(key)) continue
9529
+ this.reportedDeferrals.add(key)
9530
+ lines.push(preparationCarryLine(ticket, detail))
9531
+ }
9532
+ return lines
9533
+ }
9534
+
9535
+ /** Record that this tick carried `attempt`'s ticket preparation to the
9536
+ * next invocation (#1431), and keep the durable hint current. The first
9537
+ * reason noted wins. */
9538
+ private async notePreparationCarry(
9539
+ attempt: string,
9540
+ ticket: TicketRef,
9541
+ detail?: string,
9542
+ ): Promise<void> {
9543
+ if (!this.tickPreparationCarries.has(attempt))
9544
+ this.tickPreparationCarries.set(attempt, {
9545
+ ticket,
9546
+ ...(detail !== undefined ? { detail } : {}),
9547
+ })
9548
+ await this.persistDeferrals()
9549
+ }
9550
+
9551
+ /** The hint's preparation entries this tick would write, ordered as
9552
+ * `nextDeferralList` orders builds and capped from the tail. A dropped
9553
+ * entry is still resumed: its attempt carries the work-deadline stamp
9554
+ * preparation recovery resumes from. */
9555
+ private nextPreparationCarryList(): CarriedPreparation[] {
9556
+ const list: CarriedPreparation[] = []
9557
+ const seen = new Set<string>()
9558
+ const push = (attempt: string, ticket: TicketRef) => {
9559
+ if (seen.has(attempt)) return
9560
+ seen.add(attempt)
9561
+ list.push({ ticket, attempt })
9562
+ }
9563
+ for (const [attempt, entry] of this.carriedPreparationsOutstanding)
9564
+ if (!entry.visited) push(attempt, entry.ticket)
9565
+ for (const [attempt, entry] of this.carriedPreparationsOutstanding)
9566
+ if (entry.visited) push(attempt, entry.ticket)
9567
+ for (const [attempt, { ticket }] of this.tickPreparationCarries) push(attempt, ticket)
9568
+ return list.slice(0, MAX_CARRIED_PREPARATIONS)
9569
+ }
9570
+
9353
9571
  /** A carried hint entry whose own pass showed it no longer needs priority.
9354
9572
  * Never writes: the next hint write simply omits it. */
9355
9573
  private retireCarried(slug: string): void {
@@ -9408,6 +9626,8 @@ export class Dispatcher {
9408
9626
  const write = this.deferralWrites.then(async () => {
9409
9627
  const next = this.nextDeferralList()
9410
9628
  const recorded = this.recordedDeferrals
9629
+ const tickets = this.nextPreparationCarryList()
9630
+ const recordedTickets = this.recordedPreparationCarries
9411
9631
  if (
9412
9632
  next.length === recorded.length &&
9413
9633
  next.every(
@@ -9415,6 +9635,13 @@ export class Dispatcher {
9415
9635
  entry.slug === recorded[i]!.slug &&
9416
9636
  entry.step === recorded[i]!.step &&
9417
9637
  entry.instance === recorded[i]!.instance,
9638
+ ) &&
9639
+ tickets.length === recordedTickets.length &&
9640
+ tickets.every(
9641
+ (entry, i) =>
9642
+ entry.attempt === recordedTickets[i]!.attempt &&
9643
+ entry.ticket.source === recordedTickets[i]!.ticket.source &&
9644
+ entry.ticket.id === recordedTickets[i]!.ticket.id,
9418
9645
  )
9419
9646
  )
9420
9647
  return
@@ -9422,11 +9649,14 @@ export class Dispatcher {
9422
9649
  this.store.appendRepo(this.deps.repo, {
9423
9650
  actor: DISPATCHER,
9424
9651
  type: 'dispatcher.work-deferred',
9425
- payload: { builds: next },
9652
+ // A hint without carried preparations keeps its earlier payload.
9653
+ payload: { builds: next, ...(tickets.length > 0 ? { tickets } : {}) },
9426
9654
  }),
9427
9655
  )
9428
- if (outcome === true) this.recordedDeferrals = next
9429
- else if (outcome !== false) this.deferralWriteFailure = outcome
9656
+ if (outcome === true) {
9657
+ this.recordedDeferrals = next
9658
+ this.recordedPreparationCarries = tickets
9659
+ } else if (outcome !== false) this.deferralWriteFailure = outcome
9430
9660
  })
9431
9661
  this.deferralWrites = write.catch(() => {})
9432
9662
  return write
@@ -9492,6 +9722,9 @@ export class Dispatcher {
9492
9722
  this.reportedDeferrals.add(slug)
9493
9723
  report.deferredDiagnostics.push(deferralLine(slug, deferral))
9494
9724
  }
9725
+ if (this.tickPreparationCarries.size > 0)
9726
+ report.preparationsCarried = this.tickPreparationCarries.size
9727
+ report.deferredDiagnostics.push(...this.unreportedPreparationCarries())
9495
9728
  if (this.deferralWriteFailure !== undefined)
9496
9729
  report.deferredDiagnostics.push(
9497
9730
  `deferred work not recorded for the next invocation — ${this.deferralWriteFailure}`,
@@ -9570,6 +9803,116 @@ export class Dispatcher {
9570
9803
 
9571
9804
  /** `carried` is a deferred-work entry's pass: its facts are already read,
9572
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
+
9573
9916
  private async sweepBuildPass(
9574
9917
  record: BuildRecord,
9575
9918
  report: TickReport,
@@ -9582,7 +9925,7 @@ export class Dispatcher {
9582
9925
  if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
9583
9926
  }
9584
9927
  const facts = carried?.facts ?? (await this.store.buildFacts(record.slug))
9585
- const state = facts.state
9928
+ let state = facts.state
9586
9929
  if (mixedVersionDeferred(state)) {
9587
9930
  return (await deferMixedVersion(this.store, record.slug)) ? 'waiting' : undefined
9588
9931
  }
@@ -9689,6 +10032,16 @@ export class Dispatcher {
9689
10032
  // proved end settles first (completion facts, lease release, publication)
9690
10033
  // and then falls through to the normal decision; a provider-proved loss
9691
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
9692
10045
  let orphanRecoveryDue = orphanEligible(state) && facts.open === null
9693
10046
  const foreignExecution = facts.open
9694
10047
  // A provider- or log-proved end in the same generation re-attaches in
@@ -9730,7 +10083,13 @@ export class Dispatcher {
9730
10083
  // Unknown liveness is never proof that an open execution is dead.
9731
10084
  // Settlement may itself raise provider attention. Revalidate cleanup
9732
10085
  // eligibility from the advanced canonical state before admission.
9733
- 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)
9734
10093
  if (settlement === 'settled') {
9735
10094
  report.settled += 1
9736
10095
  endedInPlace = true
@@ -9842,10 +10201,24 @@ export class Dispatcher {
9842
10201
 
9843
10202
  /** Retry a fixed batch under the same repository ownership as intake.
9844
10203
  * No provider calls for parked deadlines; no history or orphan scans. */
9845
- private async recoverTicketPreparations(report: TickReport, opts: TickOpts): Promise<void> {
9846
- const pending = Object.values(this.store.repositoryFacts().preparation)
10204
+ private async recoverTicketPreparations(
10205
+ report: TickReport,
10206
+ launched: Set<string>,
10207
+ paused: boolean,
10208
+ opts: TickOpts,
10209
+ ): Promise<void> {
10210
+ const attempts = Object.values(this.store.repositoryFacts().preparation)
10211
+ // Read the clock only when an attempt needs scheduling.
10212
+ const now = attempts.length ? this.deps.clock().getTime() : 0
10213
+ const pending = attempts
9847
10214
  .filter(
9848
- (attempt) => !attempt.retryAt || Date.parse(attempt.retryAt) <= this.deps.clock().getTime(),
10215
+ (attempt) =>
10216
+ // The early stage resumed it this tick.
10217
+ !this.tickResumedAttempts.has(attempt.attempt) &&
10218
+ // A deadline stamp not yet passed belongs to an invocation still
10219
+ // running (or a skewed clock): a later pass decides it.
10220
+ !(this.interruptedByDeadline(attempt) && Date.parse(attempt.workDeadlineAt!) > now) &&
10221
+ (!attempt.retryAt || Date.parse(attempt.retryAt) <= now),
9849
10222
  )
9850
10223
  .sort(
9851
10224
  (a, b) =>
@@ -9859,7 +10232,12 @@ export class Dispatcher {
9859
10232
  for (const attempt of pending) {
9860
10233
  if (!this.passItem(opts, 'preparations')) break
9861
10234
  try {
9862
- await this.recoverTicketPreparation(attempt)
10235
+ // A preparation its invocation's work deadline interrupted resumes,
10236
+ // even when its carry hint was lost (#1431); everything else
10237
+ // recovers as before.
10238
+ if (this.interruptedByDeadline(attempt))
10239
+ await this.resumeCarriedPreparation(attempt, report, launched, paused, 'preparations')
10240
+ else await this.recoverTicketPreparation(attempt)
9863
10241
  } catch (error) {
9864
10242
  rethrowAuthorityLapse(error)
9865
10243
  failures.push(error)
@@ -9947,39 +10325,251 @@ export class Dispatcher {
9947
10325
  }
9948
10326
  }
9949
10327
 
9950
- private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
9951
- try {
9952
- // A rejected create can have committed. Unavailable or conflicting readback
9953
- // is never absence and must not authorize a ticket transition. A keyed
9954
- // attempt's build is at its proposed slug (exact-slug store) or the slug
9955
- // its own key derives (allocating store): at most two point reads, and
9956
- // never another attempt's build.
9957
- if (attempt.slug) {
9958
- const found = await this.creationCandidates(attempt, attempt.slug)
9959
- if (found.length > 1)
9960
- return await this.abandonPreparation(
10328
+ /** Whether an attempt's selected creation committed: the one build it
10329
+ * owns, `absent` when no build answers it (or it selected no slug), or
10330
+ * `abandoned` once an ambiguous, conflicting or unprovable outcome was
10331
+ * durably abandoned. */
10332
+ private async creationReadback(
10333
+ attempt: TicketPreparation,
10334
+ ): Promise<{ owned: BuildRecord } | 'absent' | 'abandoned'> {
10335
+ // A rejected create can have committed. Unavailable or conflicting readback
10336
+ // is never absence and must not authorize a ticket transition. A keyed
10337
+ // attempt's build is at its proposed slug (exact-slug store) or the slug
10338
+ // its own key derives (allocating store): at most two point reads, and
10339
+ // never another attempt's build.
10340
+ if (!attempt.slug) return 'absent'
10341
+ const found = await this.creationCandidates(attempt, attempt.slug)
10342
+ if (found.length > 1) {
10343
+ await this.abandonPreparation(
10344
+ attempt,
10345
+ `Ambiguous creation identity: builds at ${found.map((record) => record.slug).join(' and ')} both answer this attempt; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10346
+ )
10347
+ return 'abandoned'
10348
+ }
10349
+ const [record] = found
10350
+ if (record) {
10351
+ if (!(await this.preparationOwns(attempt, record))) {
10352
+ await this.abandonPreparation(
10353
+ attempt,
10354
+ `Conflicting build ownership at ${record.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10355
+ )
10356
+ return 'abandoned'
10357
+ }
10358
+ return { owned: record }
10359
+ }
10360
+ // Absence is evidence only where the creation slug is known: an
10361
+ // allocating store may have committed an unkeyed create under a slug
10362
+ // no point read can find, and enumerating builds is never a fallback.
10363
+ if (!attempt.creationKey && (await this.store.buildCreationIdentity?.()) !== undefined) {
10364
+ await this.abandonPreparation(
10365
+ attempt,
10366
+ `Creation outcome unknown: the build store allocates canonical slugs and this attempt recorded no creation key, so a build created under an unrecorded slug cannot be ruled out; ticket unchanged. Inspect the repository's builds for ticket ${attempt.ticket.id} before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10367
+ )
10368
+ return 'abandoned'
10369
+ }
10370
+ return 'absent'
10371
+ }
10372
+
10373
+ /** `dispatchCapacity` with every outstanding admitted preparation holding
10374
+ * its slot (#1431). A carried attempt was admitted when its `intended` was
10375
+ * written and finishes without re-measuring capacity, so until it resolves
10376
+ * no later admission (intake, start requests, parked or node slot
10377
+ * admission) may spend its slot, however many passes its resume takes.
10378
+ * In memory over the tick's repository facts: no read. */
10379
+ private measureCapacity(
10380
+ ...args: Parameters<typeof dispatchCapacity>
10381
+ ): ReturnType<typeof dispatchCapacity> {
10382
+ const capacity = dispatchCapacity(...args)
10383
+ const reserved = this.reservedPreparations()
10384
+ return reserved === 0 ? capacity : { ...capacity, occupied: capacity.occupied + reserved }
10385
+ }
10386
+
10387
+ /** Unresolved ticket preparations a bounded pass admitted and its work
10388
+ * deadline interrupted (or deferred), each holding one slot until it
10389
+ * resolves. A node ticket's attempt reserves too, at most until its next
10390
+ * resume: the attempt does not record the ticket's kind. */
10391
+ private reservedPreparations(): number {
10392
+ let reserved = 0
10393
+ for (const attempt of Object.values(this.store.repositoryFacts().preparation))
10394
+ if (this.interruptedByDeadline(attempt)) reserved++
10395
+ return reserved
10396
+ }
10397
+
10398
+ /** Whether the work deadline of the invocation that wrote this attempt
10399
+ * interrupted it (#1431): stamped by a bounded pass, that deadline passed,
10400
+ * and no failure or bounce was recorded. Such an attempt resumes; it is
10401
+ * never handed back. */
10402
+ private interruptedByDeadline(attempt: TicketPreparation): boolean {
10403
+ return (
10404
+ attempt.workDeadlineAt !== undefined &&
10405
+ attempt.stage === undefined &&
10406
+ attempt.handback === undefined
10407
+ )
10408
+ }
10409
+
10410
+ /**
10411
+ * Continue one carried ticket preparation (#1431) from its last durable
10412
+ * boundary: the claim, the claim confirmation, or the creation readback.
10413
+ * Admission was decided when its `intended` was written, so nothing here
10414
+ * re-measures capacity. Never hands a ticket back for the interruption;
10415
+ * a resumed preparation that fails for real takes the ordinary failure
10416
+ * path, and one the deadline cuts again is carried again under the same
10417
+ * attempt. Reads: one `tickets.get`, plus the existing creation readback
10418
+ * when a slug was selected and a target node's facts for a node child.
10419
+ */
10420
+ private async resumeCarriedPreparation(
10421
+ held: TicketPreparation,
10422
+ report: TickReport,
10423
+ launched: Set<string>,
10424
+ paused: boolean,
10425
+ part: PassStagePart,
10426
+ ): Promise<'done' | 'waiting' | 'failed'> {
10427
+ // Nothing claims while the repository is paused; the entry waits.
10428
+ if (paused) return 'waiting'
10429
+ const attempt: TicketPreparation = structuredClone(held)
10430
+ // A selected bounce is a real outcome: finish it.
10431
+ if (attempt.handback !== undefined) {
10432
+ await this.recoverTicketPreparation(attempt)
10433
+ return 'done'
10434
+ }
10435
+ const readback = await this.creationReadback(attempt)
10436
+ if (readback === 'abandoned') return 'done'
10437
+ if (readback !== 'absent') {
10438
+ await this.preparationResolved(attempt, 'owned')
10439
+ return this.serviceCarriedStart(
10440
+ readback.owned,
10441
+ { step: 'provision' },
10442
+ report,
10443
+ launched,
10444
+ paused,
10445
+ )
10446
+ }
10447
+ const ref = resolveTicketRef(
10448
+ this.store.repositoryFacts().ticketMigrations,
10449
+ attempt.ticket,
10450
+ this.deps.tickets.name,
10451
+ attempt.slug ?? attempt.attempt,
10452
+ )
10453
+ const ticket = await this.deps.tickets.get(ref.id)
10454
+ if (!ticket) {
10455
+ await this.abandonPreparation(attempt, 'Ticket no longer exists; ticket unchanged.')
10456
+ return 'done'
10457
+ }
10458
+ if (ticket.state === undefined) {
10459
+ await this.abandonPreparation(
10460
+ attempt,
10461
+ 'Ticket state is unavailable; ticket unchanged. Inspect the provider record before manually retrying.',
10462
+ )
10463
+ return 'done'
10464
+ }
10465
+ const is = (state: string) => ticket.state!.toLowerCase() === state.toLowerCase()
10466
+ if (!attempt.claimed) {
10467
+ if (is(attempt.readyState)) {
10468
+ // Still Ready: no claim applied. A ticket that no longer qualifies
10469
+ // is released with no tracker write, and intake re-evaluates it.
10470
+ if (!this.tickAcceptsNewWork) {
10471
+ await this.preparationResolved(
9961
10472
  attempt,
9962
- `Ambiguous creation identity: builds at ${found.map((record) => record.slug).join(' and ')} both answer this attempt; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10473
+ 'lost-claim',
10474
+ 'intake turned off before its carried claim',
9963
10475
  )
9964
- const [record] = found
9965
- if (record) {
9966
- if (!(await this.preparationOwns(attempt, record)))
9967
- return await this.abandonPreparation(
9968
- attempt,
9969
- `Conflicting build ownership at ${record.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
9970
- )
9971
- await this.preparationResolved(attempt, 'owned')
9972
- return
10476
+ return 'done'
9973
10477
  }
9974
- // Absence is evidence only where the creation slug is known: an
9975
- // allocating store may have committed an unkeyed create under a slug
9976
- // no point read can find, and enumerating builds is never a fallback.
9977
- if (!attempt.creationKey && (await this.store.buildCreationIdentity?.()) !== undefined)
9978
- return await this.abandonPreparation(
10478
+ if (ticket.blockersResolved === false) {
10479
+ await this.preparationResolved(
9979
10480
  attempt,
9980
- `Creation outcome unknown: the build store allocates canonical slugs and this attempt recorded no creation key, so a build created under an unrecorded slug cannot be ruled out; ticket unchanged. Inspect the repository's builds for ticket ${attempt.ticket.id} before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10481
+ 'lost-claim',
10482
+ 'unresolved blockers before its carried claim',
9981
10483
  )
10484
+ return 'done'
10485
+ }
10486
+ } else if (attempt.claimDeferred) {
10487
+ // No claim call was ever made: the ticket is not ours.
10488
+ await this.preparationResolved(
10489
+ attempt,
10490
+ 'lost-claim',
10491
+ `ticket left ${attempt.readyState} (${ticket.state}) before its carried claim`,
10492
+ )
10493
+ return 'done'
10494
+ } else if (is(attempt.claimedState)) {
10495
+ // The claim applied but its confirmation was cut.
10496
+ await this.store.appendRepo(this.deps.repo, {
10497
+ actor: DISPATCHER,
10498
+ type: 'ticket-preparation.claimed',
10499
+ payload: { attempt: attempt.attempt, ticket: attempt.ticket },
10500
+ })
10501
+ attempt.claimed = true
10502
+ } else {
10503
+ await this.abandonPreparation(
10504
+ attempt,
10505
+ `Claim outcome uncertain: the claim request did not confirm and the provider may have applied it; ticket observed in state ${ticket.state}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10506
+ )
10507
+ return 'done'
9982
10508
  }
10509
+ } else if (!is(attempt.claimedState)) {
10510
+ await this.abandonPreparation(
10511
+ attempt,
10512
+ `Confirmed claim but ticket externally changed to state ${ticket.state}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
10513
+ )
10514
+ return 'done'
10515
+ }
10516
+ const target = await this.resolveNodeTarget(ticket, {
10517
+ listed: new Set(),
10518
+ foreign: new Map(),
10519
+ generation: ++this.foreignScanGeneration,
10520
+ })
10521
+ if (typeof target === 'string') {
10522
+ if (!attempt.claimed) {
10523
+ await this.preparationResolved(attempt, 'lost-claim', target)
10524
+ return 'done'
10525
+ }
10526
+ return this.failPreparation(attempt, 'target', new Error(target))
10527
+ }
10528
+ if (!attempt.claimed && attempt.claimDeferred) {
10529
+ // The claim-started boundary: from here on the claim may have applied,
10530
+ // so recovery confirms it from the ticket's state rather than
10531
+ // releasing the ticket. Nothing has reached the tracker yet.
10532
+ try {
10533
+ await this.appendIntended(attempt)
10534
+ } catch (error) {
10535
+ rethrowAuthorityLapse(error)
10536
+ if (!this.budgetSpent(this.tickOpts)) throw error
10537
+ await this.notePreparationCarry(
10538
+ attempt.attempt,
10539
+ attempt.ticket,
10540
+ 'the work deadline cut its preparation (claim)',
10541
+ ).catch(() => {})
10542
+ this.pass.carry(part, attempt.ticket.id)
10543
+ return 'waiting'
10544
+ }
10545
+ }
10546
+ // The level admission decided (a start request's own level included),
10547
+ // recorded with the attempt. An attempt without one is re-derived as
10548
+ // intake derives an ordinary claim's: an optimization attempt's node
10549
+ // priority, else the ticket's.
10550
+ const level =
10551
+ attempt.level ??
10552
+ (await this.attemptClaimTiers([ticket])).get(ticket.ref.id) ??
10553
+ (this.deps.tickets.priority ? ticketPriority(ticket) : 'normal')
10554
+ const outcome = await this.prepareTicket({
10555
+ ticket,
10556
+ attempt,
10557
+ target,
10558
+ level,
10559
+ report,
10560
+ launched,
10561
+ settle: () => {},
10562
+ part,
10563
+ resume: true,
10564
+ })
10565
+ return outcome === 'started' || outcome === 'left' || outcome === 'blocked' ? 'done' : 'waiting'
10566
+ }
10567
+
10568
+ private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
10569
+ try {
10570
+ const readback = await this.creationReadback(attempt)
10571
+ if (readback === 'abandoned') return
10572
+ if (readback !== 'absent') return await this.preparationResolved(attempt, 'owned')
9983
10573
  // A committed `ticket.handed-back` whose acknowledgement or resolution
9984
10574
  // was lost means the hand-back already happened, and a watcher may have
9985
10575
  // moved the ticket since. Resolve without touching the ticket.
@@ -10102,7 +10692,7 @@ export class Dispatcher {
10102
10692
  if (!targeted && this.deferredAdmissions.size > 0) {
10103
10693
  deferralBuilds = await this.capacityBuilds(launched)
10104
10694
  const key = this.deferralKey(
10105
- dispatchCapacity(deferralBuilds, config.capacity, this.deps.clock()).occupied,
10695
+ this.measureCapacity(deferralBuilds, config.capacity, this.deps.clock()).occupied,
10106
10696
  )
10107
10697
  if (key !== this.lastForcedDeferralKey) {
10108
10698
  force = true
@@ -10147,7 +10737,7 @@ export class Dispatcher {
10147
10737
  // tell a reserved request from one filed since.
10148
10738
  const pendingStarts = this.store.repositoryFacts().ticketStarts.pending
10149
10739
  const startDemand = this.startClaims()
10150
- const projection = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock(), {
10740
+ const projection = this.measureCapacity(capacityBuilds, config.capacity, this.deps.clock(), {
10151
10741
  openPrs: { policy: config.policy, engaged },
10152
10742
  startRequests: startDemand,
10153
10743
  })
@@ -10649,23 +11239,94 @@ export class Dispatcher {
10649
11239
  }
10650
11240
  // Cancellation and a priority change are checked again before claiming.
10651
11241
  if (targeted && !(await this.startStillPending(targeted, ticket))) continue
10652
- await store.appendRepo(this.deps.repo, {
10653
- actor: DISPATCHER,
10654
- type: 'ticket-preparation.intended',
10655
- payload: {
10656
- attempt: attempt.attempt,
10657
- ticket: attempt.ticket,
10658
- readyState: attempt.readyState,
10659
- claimedState: attempt.claimedState,
10660
- },
11242
+ // A bounded pass does not start a preparation it cannot finish before
11243
+ // its work deadline (#1431). Intake's admission is journaled and the
11244
+ // next invocation prepares it first; a start request's own pending
11245
+ // request is already its carry. Time only shrinks: stop claiming.
11246
+ if (this.preparationWontFit()) {
11247
+ claimLoopCompleted = false
11248
+ attempt.level = this.claimedLevel(ticket, startTier(ticket), tierOf)
11249
+ if (!targeted && (await this.deferPreparation(attempt, part ?? 'tickets'))) {
11250
+ report.queued -= 1
11251
+ if (ticket.kind !== 'node') for (const entry of TICKET_PRIORITIES) budgets[entry] -= 1
11252
+ }
11253
+ break
11254
+ }
11255
+ const outcome = await this.prepareTicket({
11256
+ ticket,
11257
+ attempt,
11258
+ target,
11259
+ level: this.claimedLevel(ticket, startTier(ticket), tierOf),
11260
+ report,
11261
+ launched,
11262
+ settle: (outcome) => settle(ticket, outcome),
11263
+ part: part ?? 'starts',
11264
+ ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
11265
+ ...(autoMergeSeedFact !== undefined ? { autoMergeSeedFact } : {}),
10661
11266
  })
10662
- let stage = 'claim'
10663
- let established = false
10664
- let record: BuildRecord
10665
- let body = ticket.body
10666
- let authoredSession: string | undefined
10667
- let createdSeed: Parameters<Dispatcher['buildCreatedPayload']>[2]
11267
+ if (outcome === 'blocked') continue
11268
+ if (outcome === 'stop') {
11269
+ claimLoopCompleted = false
11270
+ break
11271
+ }
11272
+ report.queued -= 1
11273
+ if (outcome === 'left') continue
11274
+ // A carried admission holds its slot until the next invocation
11275
+ // prepares it.
11276
+ if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
11277
+ else if (ticket.kind !== 'node') for (const entry of TICKET_PRIORITIES) budgets[entry] -= 1
11278
+ if (outcome === 'carried') {
11279
+ claimLoopCompleted = false
11280
+ break
11281
+ }
11282
+ }
11283
+ if (checkpoint !== undefined && scanSuccessful && !this.outOfBudget(opts)) {
11284
+ await this.completeScan(checkpoint, report, waiting)
11285
+ // The only other place this tick authorizes deferred admissions.
11286
+ if (claimLoopCompleted) this.claimsEvaluated = true
11287
+ }
11288
+ }
11289
+
11290
+ /**
11291
+ * One ticket preparation (SPEC §6.3), from the `intended` append through
11292
+ * the first dispatch: claim → `.claimed` → asset pin → spec → naming →
11293
+ * `.creation-selected` → `createBuild` → `.resolved owned` → first
11294
+ * dispatch. With `resume`, a carried attempt (#1431) continues from its
11295
+ * claim when unclaimed, or from its asset pin when claimed, appending no
11296
+ * `intended`. Tracked as a start in flight, so bounded teardown awaits a
11297
+ * preparation the work deadline cut. A preparation the deadline cuts
11298
+ * before `build.created` is carried to the next invocation: nothing is
11299
+ * marked failed, nothing is handed back and the tracker is not touched.
11300
+ * Every other failure keeps its failure record and recovery.
11301
+ */
11302
+ private prepareTicket(input: PreparationInput): Promise<PreparationOutcome> {
11303
+ return this.trackStart(this.runPreparation(input))
11304
+ }
11305
+
11306
+ private async runPreparation(input: PreparationInput): Promise<PreparationOutcome> {
11307
+ const { ticket, attempt, target, level, report, launched, settle, resume } = input
11308
+ const { autoMergeUser, autoMergeSeedFact } = input
11309
+ const store = this.store
11310
+ const { tickets } = this.deps
11311
+ if (!resume) {
11312
+ attempt.level = level
10668
11313
  try {
11314
+ await this.appendIntended(attempt)
11315
+ } catch (error) {
11316
+ rethrowAuthorityLapse(error)
11317
+ // Nothing durable began: the next scan admits the ticket again.
11318
+ if (this.budgetSpent(this.tickOpts)) return 'stop'
11319
+ throw error
11320
+ }
11321
+ }
11322
+ let stage = attempt.claimed ? 'assets' : 'claim'
11323
+ let established = false
11324
+ let record: BuildRecord
11325
+ let body = ticket.body
11326
+ let authoredSession: string | undefined
11327
+ let createdSeed: Parameters<Dispatcher['buildCreatedPayload']>[2]
11328
+ try {
11329
+ if (!attempt.claimed) {
10669
11330
  let claimed: boolean
10670
11331
  try {
10671
11332
  claimed = await tickets.claim(ticket.ref.id, { blockedBy: ticket.blockedBy ?? [] })
@@ -10677,18 +11338,17 @@ export class Dispatcher {
10677
11338
  await this.preparationResolved(attempt, 'lost-claim', error.message)
10678
11339
  report.dependencyBlocked += 1
10679
11340
  report.dependencyDiagnostics.push(detail)
10680
- settle(ticket, { outcome: 'blocked', detail })
10681
- continue
11341
+ settle({ outcome: 'blocked', detail })
11342
+ return 'blocked'
10682
11343
  }
10683
11344
  if (!claimed) {
10684
11345
  await this.preparationResolved(attempt, 'lost-claim')
10685
- settle(ticket, {
11346
+ settle({
10686
11347
  outcome: 'claim-refused',
10687
11348
  detail: `the ${tickets.name} ticket source refused the claim of ${ticket.ref.id}`,
10688
11349
  })
10689
11350
  report.claimRaces += 1
10690
- report.queued -= 1
10691
- continue
11351
+ return 'left'
10692
11352
  }
10693
11353
  attempt.claimed = true
10694
11354
  stage = 'claim-confirmation'
@@ -10697,220 +11357,297 @@ export class Dispatcher {
10697
11357
  type: 'ticket-preparation.claimed',
10698
11358
  payload: { attempt: attempt.attempt, ticket: attempt.ticket },
10699
11359
  })
10700
- stage = 'assets'
10701
- // Freeze the ticket's assets at the claim (SPEC §6.3): sampled before the
10702
- // spec-authoring interval so edits made during it are never pinned.
10703
- const assets = await preparePinnedAssets(tickets, store, this.deps.repo, ticket.ref.id)
10704
-
10705
- // Quality gate (§6.3): import a conforming ticket body as the spec;
10706
- // author one for thin-but-groomed tickets; otherwise bounce.
10707
- stage = 'spec'
10708
- // An objective refusal bounces before any authoring: an authored spec
10709
- // could strip the block and open a plain node instead (SPEC §13.1).
10710
- const refusals = objectiveRefusals(body, {
10711
- kind: ticket.kind ?? 'work',
10712
- rejectedState: this.rejectedState(),
10713
- })
10714
- let conformance =
10715
- refusals.length > 0 ? { conforms: false, missing: refusals } : specConformance(body)
10716
- if (
10717
- !conformance.conforms &&
10718
- refusals.length === 0 &&
10719
- objectiveBlocks(body).length === 0 &&
10720
- this.deps.authorSpec
10721
- ) {
10722
- const authored = await this.deps.authorSpec(ticket)
10723
- // An authored spec never gains the marker the ticket did not carry.
10724
- if (authored !== null && objectiveBlocks(authored).length === 0) {
10725
- conformance = specConformance(authored)
10726
- if (conformance.conforms) {
10727
- body = authored
10728
- authoredSession = this.deps.ids('s')
10729
- }
11360
+ }
11361
+ stage = 'assets'
11362
+ // Freeze the ticket's assets at the claim (SPEC §6.3): sampled before the
11363
+ // spec-authoring interval so edits made during it are never pinned.
11364
+ const assets = await preparePinnedAssets(tickets, store, this.deps.repo, ticket.ref.id)
11365
+
11366
+ // Quality gate (§6.3): import a conforming ticket body as the spec;
11367
+ // author one for thin-but-groomed tickets; otherwise bounce.
11368
+ stage = 'spec'
11369
+ // An objective refusal bounces before any authoring: an authored spec
11370
+ // could strip the block and open a plain node instead (SPEC §13.1).
11371
+ const refusals = objectiveRefusals(body, {
11372
+ kind: ticket.kind ?? 'work',
11373
+ rejectedState: this.rejectedState(),
11374
+ })
11375
+ let conformance =
11376
+ refusals.length > 0 ? { conforms: false, missing: refusals } : specConformance(body)
11377
+ if (
11378
+ !conformance.conforms &&
11379
+ refusals.length === 0 &&
11380
+ objectiveBlocks(body).length === 0 &&
11381
+ this.deps.authorSpec
11382
+ ) {
11383
+ const authored = await this.deps.authorSpec(ticket)
11384
+ // An authored spec never gains the marker the ticket did not carry.
11385
+ if (authored !== null && objectiveBlocks(authored).length === 0) {
11386
+ conformance = specConformance(authored)
11387
+ if (conformance.conforms) {
11388
+ body = authored
11389
+ authoredSession = this.deps.ids('s')
10730
11390
  }
10731
11391
  }
10732
- if (!conformance.conforms) {
10733
- attempt.handback = this.triageState()
10734
- const missing = conformance.missing.length > 0 ? conformance.missing : undefined
10735
- if (missing) attempt.missing = missing
10736
- await store.appendRepo(this.deps.repo, {
10737
- actor: DISPATCHER,
10738
- type: 'ticket-preparation.handback-selected',
10739
- payload: {
10740
- attempt: attempt.attempt,
10741
- ticket: attempt.ticket,
10742
- state: attempt.handback,
10743
- ...(missing ? { missing } : {}),
10744
- },
10745
- })
10746
- stage = 'bounce'
10747
- await this.bounce(ticket, conformance.missing, refusals.length > 0)
10748
- stage = 'handback-report'
10749
- await this.reportPreparationHandback(attempt, {
10750
- ticket: ticket.ref,
10751
- attempt: attempt.attempt,
10752
- cause: 'spec-bounce',
10753
- state: attempt.handback,
10754
- role: 'triage',
10755
- ...(missing ? { missing } : {}),
10756
- })
10757
- await this.preparationResolved(attempt, 'bounced')
10758
- settle(ticket, {
10759
- outcome: 'invalid',
10760
- detail: `bounced to ${attempt.handback}${
10761
- conformance.missing.length > 0 ? `; missing: ${conformance.missing.join('; ')}` : ''
10762
- }`,
10763
- })
10764
- report.bounced += 1
10765
- report.queued -= 1
10766
- continue
10767
- }
10768
-
10769
- stage = 'naming'
10770
- const baseSlug = await this.chooseSlugBase(ticket.title, body)
10771
- const prefix = ticket.kind === 'node' ? 'ab-node' : 'ab'
10772
- const slug = await this.uniqueSlug(baseSlug, prefix)
10773
- const branch = `${prefix}/${slug}`
10774
- const repoOrigin = await this.resolveRepoOriginOnce()
10775
- // Recorded only on the store's attestation, so recovery never treats
10776
- // an unkeyed creation's absence at the derived slug as evidence.
10777
- const creationKey =
10778
- (await store.buildCreationIdentity?.()) === 'keyed' ? attempt.attempt : undefined
10779
- createdSeed = {
10780
- ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
10781
- ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
10782
- ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
10783
- // Claim-time provenance: the newest durable default fact that agrees
10784
- // with the launch sample, recorded on `build.created` so the fan-out's
10785
- // seq comparison sees the claim as already answering that fact — and
10786
- // so a newer opposite fact (an interleaved toggle) stays strictly
10787
- // ahead of it and reconciles this build on the next tick (f_b851c0e8).
10788
- ...(autoMergeSeedFact !== undefined
10789
- ? { autoMergeDefaultSeq: autoMergeSeedFact.seq }
10790
- : {}),
10791
- assets,
10792
- // Frozen from the same claimed ticket sample as the body (SPEC
10793
- // "Forge issue links"); later ticket edits never reach this build.
10794
- ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
10795
- // Fixed at claim from the same sample: relabelling never changes it.
10796
- ...this.selectedProfile(ticket),
10797
- // `manual` is admission-only: a build started by any other request
10798
- // takes the request's level, every other build its ticket's.
10799
- ...createdPriorityFields(this.claimedLevel(ticket, startTier(ticket), tierOf)),
10800
- }
10801
- // `build.created` rides with the record so the pinned assets and the
10802
- // record exist together or not at all.
10803
- stage = 'creation-identity'
10804
- attempt.slug = slug
10805
- if (creationKey !== undefined) attempt.creationKey = creationKey
11392
+ }
11393
+ if (!conformance.conforms) {
11394
+ attempt.handback = this.triageState()
11395
+ const missing = conformance.missing.length > 0 ? conformance.missing : undefined
11396
+ if (missing) attempt.missing = missing
10806
11397
  await store.appendRepo(this.deps.repo, {
10807
11398
  actor: DISPATCHER,
10808
- type: 'ticket-preparation.creation-selected',
11399
+ type: 'ticket-preparation.handback-selected',
10809
11400
  payload: {
10810
11401
  attempt: attempt.attempt,
10811
11402
  ticket: attempt.ticket,
10812
- slug,
10813
- ...(creationKey !== undefined ? { creationKey } : {}),
11403
+ state: attempt.handback,
11404
+ ...(missing ? { missing } : {}),
10814
11405
  },
10815
11406
  })
10816
- stage = 'create-build'
10817
- // Tracked from the creation on: `build.created` admits the build, so
10818
- // a work deadline that cuts anything after it must carry the start.
10819
- record = await this.trackStart(
10820
- (async () => {
10821
- const created = await store
10822
- .createBuild({
10823
- slug,
10824
- repo: this.deps.repo,
10825
- ticket: ticket.ref,
10826
- branch,
10827
- ...(repoOrigin !== undefined ? { repoOrigin } : {}),
10828
- ...(creationKey !== undefined ? { creationKey } : {}),
10829
- created: {
10830
- actor: DISPATCHER,
10831
- type: 'build.created',
10832
- payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
10833
- },
10834
- })
10835
- .catch(async (error: unknown) => {
10836
- // The deadline may have cut only the acknowledgement: a
10837
- // committed `build.created` admitted the build, so resolve
10838
- // the preparation and carry its first provision.
10839
- if (!this.budgetSpent(this.tickOpts)) throw error
10840
- const owned = await this.cutCreation(attempt, slug)
10841
- if (owned === undefined) throw error
10842
- established = true
10843
- await this.scoped(() => this.preparationResolved(attempt, 'owned')).catch(
10844
- (resolution: unknown) => rethrowAuthorityLapse(resolution),
10845
- )
10846
- return this.carryCutFirstDispatch(owned.slug, error)
10847
- })
10848
- established = true
10849
- await this.preparationResolved(attempt, 'owned').catch((error: unknown) =>
10850
- this.carryCutFirstDispatch(created.slug, error),
10851
- )
10852
- return created
10853
- })(),
10854
- )
10855
- settle(ticket, { outcome: 'started', slug: record.slug })
10856
- } catch (error) {
10857
- // A lapse is not a preparation failure: the successor recovers the
10858
- // intended attempt through `recoverTicketPreparations`.
10859
- rethrowAuthorityLapse(error)
10860
- // Settlement and completion errors after successful creation cannot
10861
- // release the claim. A later tick settles the retained creation identity.
10862
- if (established) throw error
10863
- const errors: unknown[] = [error]
10864
- attempt.error =
10865
- (error instanceof Error ? error.message : String(error)).slice(0, 4000) ||
10866
- 'unknown preparation failure'
10867
- attempt.stage = stage
10868
- try {
10869
- await store.appendRepo(this.deps.repo, {
10870
- actor: DISPATCHER,
10871
- type: 'ticket-preparation.failed',
10872
- payload: {
10873
- attempt: attempt.attempt,
10874
- ticket: attempt.ticket,
10875
- stage,
10876
- claimed: attempt.claimed,
10877
- handback: attempt.handback ?? attempt.readyState,
10878
- error: attempt.error,
10879
- },
10880
- })
10881
- } catch (diagnosticError) {
10882
- errors.push(diagnosticError)
10883
- }
10884
- try {
10885
- await this.recoverTicketPreparation(attempt)
10886
- } catch (recoveryError) {
10887
- errors.push(recoveryError)
10888
- }
10889
- throw new AggregateError(
10890
- errors,
10891
- `ticket preparation failed (${stage}): ${errors.map(String).join('; ')}`,
10892
- )
11407
+ stage = 'bounce'
11408
+ await this.bounce(ticket, conformance.missing, refusals.length > 0)
11409
+ stage = 'handback-report'
11410
+ await this.reportPreparationHandback(attempt, {
11411
+ ticket: ticket.ref,
11412
+ attempt: attempt.attempt,
11413
+ cause: 'spec-bounce',
11414
+ state: attempt.handback,
11415
+ role: 'triage',
11416
+ ...(missing ? { missing } : {}),
11417
+ })
11418
+ await this.preparationResolved(attempt, 'bounced')
11419
+ settle({
11420
+ outcome: 'invalid',
11421
+ detail: `bounced to ${attempt.handback}${
11422
+ conformance.missing.length > 0 ? `; missing: ${conformance.missing.join('; ')}` : ''
11423
+ }`,
11424
+ })
11425
+ report.bounced += 1
11426
+ return 'left'
10893
11427
  }
10894
- report.queued -= 1
10895
- if (ticket.kind !== 'node' && targeted) targeted.budgets[startTier(ticket)] -= 1
10896
- else if (ticket.kind !== 'node') for (const entry of TICKET_PRIORITIES) budgets[entry] -= 1
10897
- const outcome = await this.trackStart(
10898
- this.attemptDispatchCompletion(record, launched, report, {
10899
- ticket,
10900
- body,
10901
- ...(authoredSession !== undefined ? { authoredSession } : {}),
10902
- ...createdSeed,
10903
- }).catch((error: unknown) => this.carryCutFirstDispatch(record.slug, error)),
11428
+
11429
+ stage = 'naming'
11430
+ const baseSlug = await this.chooseSlugBase(ticket.title, body)
11431
+ const prefix = ticket.kind === 'node' ? 'ab-node' : 'ab'
11432
+ const slug = await this.uniqueSlug(baseSlug, prefix)
11433
+ const branch = `${prefix}/${slug}`
11434
+ const repoOrigin = await this.resolveRepoOriginOnce()
11435
+ // Recorded only on the store's attestation, so recovery never treats
11436
+ // an unkeyed creation's absence at the derived slug as evidence.
11437
+ const creationKey =
11438
+ (await store.buildCreationIdentity?.()) === 'keyed' ? attempt.attempt : undefined
11439
+ createdSeed = {
11440
+ ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
11441
+ ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
11442
+ ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
11443
+ // Claim-time provenance: the newest durable default fact that agrees
11444
+ // with the launch sample, recorded on `build.created` so the fan-out's
11445
+ // seq comparison sees the claim as already answering that fact — and
11446
+ // so a newer opposite fact (an interleaved toggle) stays strictly
11447
+ // ahead of it and reconciles this build on the next tick (f_b851c0e8).
11448
+ ...(autoMergeSeedFact !== undefined ? { autoMergeDefaultSeq: autoMergeSeedFact.seq } : {}),
11449
+ assets,
11450
+ // Frozen from the same claimed ticket sample as the body (SPEC
11451
+ // "Forge issue links"); later ticket edits never reach this build.
11452
+ ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
11453
+ // Fixed at claim from the same sample: relabelling never changes it.
11454
+ ...this.selectedProfile(ticket),
11455
+ // `manual` is admission-only: a build started by any other request
11456
+ // takes the request's level, every other build its ticket's.
11457
+ ...createdPriorityFields(level),
11458
+ }
11459
+ // `build.created` rides with the record so the pinned assets and the
11460
+ // record exist together or not at all.
11461
+ stage = 'creation-identity'
11462
+ attempt.slug = slug
11463
+ if (creationKey !== undefined) attempt.creationKey = creationKey
11464
+ await store.appendRepo(this.deps.repo, {
11465
+ actor: DISPATCHER,
11466
+ type: 'ticket-preparation.creation-selected',
11467
+ payload: {
11468
+ attempt: attempt.attempt,
11469
+ ticket: attempt.ticket,
11470
+ slug,
11471
+ ...(creationKey !== undefined ? { creationKey } : {}),
11472
+ },
11473
+ })
11474
+ stage = 'create-build'
11475
+ // Tracked from the creation on: `build.created` admits the build, so
11476
+ // a work deadline that cuts anything after it must carry the start.
11477
+ record = await this.trackStart(
11478
+ (async () => {
11479
+ const created = await store
11480
+ .createBuild({
11481
+ slug,
11482
+ repo: this.deps.repo,
11483
+ ticket: ticket.ref,
11484
+ branch,
11485
+ ...(repoOrigin !== undefined ? { repoOrigin } : {}),
11486
+ ...(creationKey !== undefined ? { creationKey } : {}),
11487
+ created: {
11488
+ actor: DISPATCHER,
11489
+ type: 'build.created',
11490
+ payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
11491
+ },
11492
+ })
11493
+ .catch(async (error: unknown) => {
11494
+ // The deadline may have cut only the acknowledgement: a
11495
+ // committed `build.created` admitted the build, so resolve
11496
+ // the preparation and carry its first provision.
11497
+ if (!this.budgetSpent(this.tickOpts)) throw error
11498
+ const owned = await this.cutCreation(attempt, slug)
11499
+ if (owned === undefined) throw error
11500
+ established = true
11501
+ await this.scoped(() => this.preparationResolved(attempt, 'owned')).catch(
11502
+ (resolution: unknown) => rethrowAuthorityLapse(resolution),
11503
+ )
11504
+ return this.carryCutFirstDispatch(owned.slug, error)
11505
+ })
11506
+ established = true
11507
+ await this.preparationResolved(attempt, 'owned').catch((error: unknown) =>
11508
+ this.carryCutFirstDispatch(created.slug, error),
11509
+ )
11510
+ return created
11511
+ })(),
10904
11512
  )
10905
- // Accepted dispatches: durable boundaries recorded. A deferred outcome
10906
- // means the remote provisioning continuation owns the rest.
10907
- if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1
11513
+ settle({ outcome: 'started', slug: record.slug })
11514
+ } catch (error) {
11515
+ // A lapse is not a preparation failure: the successor recovers the
11516
+ // intended attempt through `recoverTicketPreparations`.
11517
+ rethrowAuthorityLapse(error)
11518
+ // Settlement and completion errors after successful creation cannot
11519
+ // release the claim. A later tick settles the retained creation identity.
11520
+ if (established) throw error
11521
+ // The work deadline cut the preparation before `build.created`: carry
11522
+ // the attempt, which resumes first next invocation from its durable
11523
+ // boundaries. Its `workDeadlineAt` stamp is the backstop when this
11524
+ // hint write is lost.
11525
+ if (this.budgetSpent(this.tickOpts)) {
11526
+ await this.notePreparationCarry(
11527
+ attempt.attempt,
11528
+ ticket.ref,
11529
+ `the work deadline cut its preparation (${stage})`,
11530
+ ).catch(() => {})
11531
+ this.pass.carry(input.part, ticket.ref.id)
11532
+ return 'carried'
11533
+ }
11534
+ return this.failPreparation(attempt, stage, error)
11535
+ }
11536
+ const outcome = await this.trackStart(
11537
+ this.attemptDispatchCompletion(record, launched, report, {
11538
+ ticket,
11539
+ body,
11540
+ ...(authoredSession !== undefined ? { authoredSession } : {}),
11541
+ ...createdSeed,
11542
+ }).catch((error: unknown) => this.carryCutFirstDispatch(record.slug, error)),
11543
+ )
11544
+ // Accepted dispatches: durable boundaries recorded. A deferred outcome
11545
+ // means the remote provisioning continuation owns the rest.
11546
+ if (outcome === 'completed' || outcome === 'deferred') report.dispatched += 1
11547
+ return 'started'
11548
+ }
11549
+
11550
+ /** A real preparation failure (SPEC §6.3): record it, then recover the
11551
+ * attempt at once, handing a confirmed claim back. Always throws. */
11552
+ private async failPreparation(
11553
+ attempt: TicketPreparation,
11554
+ stage: string,
11555
+ error: unknown,
11556
+ ): Promise<never> {
11557
+ const errors: unknown[] = [error]
11558
+ attempt.error =
11559
+ (error instanceof Error ? error.message : String(error)).slice(0, 4000) ||
11560
+ 'unknown preparation failure'
11561
+ attempt.stage = stage
11562
+ try {
11563
+ await this.store.appendRepo(this.deps.repo, {
11564
+ actor: DISPATCHER,
11565
+ type: 'ticket-preparation.failed',
11566
+ payload: {
11567
+ attempt: attempt.attempt,
11568
+ ticket: attempt.ticket,
11569
+ stage,
11570
+ claimed: attempt.claimed,
11571
+ handback: attempt.handback ?? attempt.readyState,
11572
+ error: attempt.error,
11573
+ },
11574
+ })
11575
+ } catch (diagnosticError) {
11576
+ errors.push(diagnosticError)
10908
11577
  }
10909
- if (checkpoint !== undefined && scanSuccessful && !this.outOfBudget(opts)) {
10910
- await this.completeScan(checkpoint, report, waiting)
10911
- // The only other place this tick authorizes deferred admissions.
10912
- if (claimLoopCompleted) this.claimsEvaluated = true
11578
+ try {
11579
+ await this.recoverTicketPreparation(attempt)
11580
+ } catch (recoveryError) {
11581
+ errors.push(recoveryError)
10913
11582
  }
11583
+ throw new AggregateError(
11584
+ errors,
11585
+ `ticket preparation failed (${stage}): ${errors.map(String).join('; ')}`,
11586
+ )
11587
+ }
11588
+
11589
+ /** Append an attempt's `intended`, stamped with the work deadline in a
11590
+ * bounded pass, with the admitted level (`attempt.level`). `claimDeferred`
11591
+ * journals an admission made without a claim call. */
11592
+ private async appendIntended(attempt: TicketPreparation, claimDeferred = false): Promise<void> {
11593
+ const deadline = this.tickOpts.deadlineAt
11594
+ const workDeadlineAt = deadline !== undefined ? new Date(deadline).toISOString() : undefined
11595
+ await this.store.appendRepo(this.deps.repo, {
11596
+ actor: DISPATCHER,
11597
+ type: 'ticket-preparation.intended',
11598
+ payload: {
11599
+ attempt: attempt.attempt,
11600
+ ticket: attempt.ticket,
11601
+ readyState: attempt.readyState,
11602
+ claimedState: attempt.claimedState,
11603
+ ...(workDeadlineAt !== undefined ? { workDeadlineAt } : {}),
11604
+ ...(claimDeferred ? { claimDeferred: true as const } : {}),
11605
+ // Admission's level travels with the stamp, so a carried attempt
11606
+ // resumes at the level it was admitted at.
11607
+ ...(workDeadlineAt !== undefined && attempt.level !== undefined
11608
+ ? { level: attempt.level }
11609
+ : {}),
11610
+ },
11611
+ })
11612
+ if (workDeadlineAt !== undefined) attempt.workDeadlineAt = workDeadlineAt
11613
+ if (claimDeferred) attempt.claimDeferred = true
11614
+ else delete attempt.claimDeferred
11615
+ }
11616
+
11617
+ /** Whether a bounded pass has too little time left before its work
11618
+ * deadline to start a ticket preparation. Pure clock arithmetic. */
11619
+ private preparationWontFit(): boolean {
11620
+ const deadline = this.tickOpts.deadlineAt
11621
+ return (
11622
+ deadline !== undefined && deadline - this.deps.clock().getTime() < this.preparationEstimateMs
11623
+ )
11624
+ }
11625
+
11626
+ /** Journal intake's admission of a ticket it has no time to prepare: one
11627
+ * `intended` with `claimDeferred` and no tracker call (#1431). The
11628
+ * unresolved attempt withholds the ticket from later scans, and the next
11629
+ * invocation claims and prepares it first. True when the admission was
11630
+ * journaled. */
11631
+ private deferPreparation(attempt: TicketPreparation, part: PassStagePart): Promise<boolean> {
11632
+ return this.trackStart(
11633
+ (async () => {
11634
+ const remaining = Math.max(0, (this.tickOpts.deadlineAt ?? 0) - this.deps.clock().getTime())
11635
+ try {
11636
+ await this.appendIntended(attempt, true)
11637
+ } catch (error) {
11638
+ rethrowAuthorityLapse(error)
11639
+ if (this.budgetSpent(this.tickOpts)) return false
11640
+ throw error
11641
+ }
11642
+ await this.notePreparationCarry(
11643
+ attempt.attempt,
11644
+ attempt.ticket,
11645
+ `${remaining} ms remain but a ticket preparation needs about ${this.preparationEstimateMs} ms`,
11646
+ )
11647
+ this.pass.carry(part, attempt.ticket.id)
11648
+ return true
11649
+ })(),
11650
+ )
10914
11651
  }
10915
11652
 
10916
11653
  /** Builds whose ticket resolves to `target` under the repository's