@defrex/autobuild 1.7.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +316 -47
  3. package/docs/answering-blocked-builds.md +44 -3
  4. package/docs/architecture.md +62 -7
  5. package/docs/cli.md +1 -0
  6. package/docs/configuration-overview.md +1 -1
  7. package/docs/configuration.md +49 -9
  8. package/docs/dispatcher.md +1 -1
  9. package/docs/integration-overview.md +2 -2
  10. package/docs/integration-tree.md +7 -4
  11. package/docs/merge-policy.md +78 -6
  12. package/docs/migration-1.0.md +4 -2
  13. package/docs/operating.md +3 -2
  14. package/docs/operator-api.md +26 -5
  15. package/docs/operator-surfaces.md +10 -0
  16. package/docs/plugin-authoring.md +1 -1
  17. package/docs/remote-store-protocol.md +9 -1
  18. package/docs/restacking.md +23 -4
  19. package/docs/ticket-dependencies.md +9 -4
  20. package/docs/tickets.md +1 -1
  21. package/docs/troubleshooting.md +1 -1
  22. package/package.json +3 -3
  23. package/packages/core/src/cli/attention.ts +1 -0
  24. package/packages/core/src/cli/build-control.ts +65 -7
  25. package/packages/core/src/cli/context.ts +55 -14
  26. package/packages/core/src/cli/dashboard/actions.ts +13 -4
  27. package/packages/core/src/cli/dashboard/landing-display.ts +32 -8
  28. package/packages/core/src/cli/dashboard/model.ts +61 -8
  29. package/packages/core/src/cli/dashboard/render.ts +28 -3
  30. package/packages/core/src/cli/dashboard/tree.ts +9 -1
  31. package/packages/core/src/cli/help.ts +69 -7
  32. package/packages/core/src/cli/landings.ts +1 -1
  33. package/packages/core/src/cli/main.ts +60 -9
  34. package/packages/core/src/cli/publication-settlement.ts +10 -0
  35. package/packages/core/src/cli/status.ts +178 -12
  36. package/packages/core/src/cli/terminals.ts +197 -4
  37. package/packages/core/src/cli/wait.ts +1 -0
  38. package/packages/core/src/cli/watch.ts +71 -0
  39. package/packages/core/src/config/landing.ts +12 -0
  40. package/packages/core/src/config/path-selectors.ts +68 -0
  41. package/packages/core/src/config/schema.ts +40 -58
  42. package/packages/core/src/events/catalog.ts +17 -3
  43. package/packages/core/src/events/compatibility.ts +2 -1
  44. package/packages/core/src/events/head-paths-limits.ts +25 -0
  45. package/packages/core/src/events/payloads.ts +315 -20
  46. package/packages/core/src/events/policy.ts +21 -0
  47. package/packages/core/src/events/repository.ts +30 -1
  48. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +247 -6
  49. package/packages/core/src/kernel/consent-revocation.ts +72 -0
  50. package/packages/core/src/kernel/dispatch-capacity.ts +19 -8
  51. package/packages/core/src/kernel/engine.ts +48 -8
  52. package/packages/core/src/kernel/head-paths-state.ts +63 -0
  53. package/packages/core/src/kernel/head-paths.ts +401 -0
  54. package/packages/core/src/kernel/landing-policy-identity.ts +20 -0
  55. package/packages/core/src/kernel/landing-policy.ts +55 -2
  56. package/packages/core/src/kernel/landing-readiness.ts +104 -9
  57. package/packages/core/src/kernel/landing-state.ts +44 -4
  58. package/packages/core/src/kernel/leaf-restack-base.ts +34 -0
  59. package/packages/core/src/kernel/leaf-restack-state.ts +22 -2
  60. package/packages/core/src/kernel/log-index.ts +27 -1
  61. package/packages/core/src/kernel/node-polling.ts +13 -3
  62. package/packages/core/src/kernel/node-restack-state.ts +8 -1
  63. package/packages/core/src/kernel/node-restack-transaction.ts +45 -0
  64. package/packages/core/src/kernel/read-deferrals.ts +3 -1
  65. package/packages/core/src/kernel/read-facts.ts +28 -1
  66. package/packages/core/src/kernel/reducer-registry.ts +22 -1
  67. package/packages/core/src/kernel/reducer.ts +316 -17
  68. package/packages/core/src/kernel/target-observation.ts +2 -5
  69. package/packages/core/src/kernel/terminal-guard.ts +52 -3
  70. package/packages/core/src/kernel/ticket-handbacks.ts +40 -0
  71. package/packages/core/src/kernel/ticket-preparation.ts +12 -1
  72. package/packages/core/src/kernel/ticket-wait.ts +345 -0
  73. package/packages/core/src/kernel/verify-applicability.ts +9 -19
  74. package/packages/core/src/ontology.ts +1 -0
  75. package/packages/core/src/operator/annotations.ts +6 -0
  76. package/packages/core/src/operator/index.ts +3 -0
  77. package/packages/core/src/operator/protocol.ts +15 -2
  78. package/packages/core/src/operator/registry.ts +97 -5
  79. package/packages/core/src/operator/repository-events.ts +67 -0
  80. package/packages/core/src/ports/tickets/fake.ts +5 -0
  81. package/packages/core/src/ports/types.ts +3 -2
  82. package/packages/core/src/processes/build-execution-state.ts +30 -1
  83. package/packages/core/src/processes/build-runner.ts +150 -18
  84. package/packages/core/src/processes/dispatcher.ts +739 -97
  85. package/packages/core/src/processes/execution-no-progress.ts +22 -2
  86. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  87. package/packages/core/src/processes/publication-state.ts +6 -1
  88. package/packages/core/src/store/digest.ts +41 -2
  89. package/packages/core/src/store/reduced-reads.ts +4 -1
  90. package/packages/core/src/store/reducer-value-shapes.json +10108 -8432
  91. package/packages/core/src/store/remote/client.ts +28 -2
  92. package/packages/core/src/store/remote/protocol.ts +11 -1
  93. package/packages/core/src/store/remote/released-clients.json +22 -0
  94. package/packages/core/src/store/remote/released-reducer-values/1.8.0.json +29043 -0
  95. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  96. package/packages/core/src/store/repo-state-events.ts +2 -0
  97. package/packages/core/src/store/types.ts +16 -0
  98. package/packages/core/src/testing/reduced-read-budget.ts +347 -0
  99. package/skills/code-review/SKILL.md +8 -0
  100. package/skills/finalize/SKILL.md +4 -0
  101. package/skills/guide/SKILL.md +125 -26
  102. package/skills/guide/references/integration-tree.md +7 -4
  103. package/skills/guide/references/merge-policy.md +78 -6
  104. package/skills/guide/references/migration-1.0.md +4 -2
  105. package/skills/guide/references/operator-api.md +26 -5
  106. package/skills/guide/references/plugin-authoring.md +1 -1
  107. package/skills/guide/references/remote-store-protocol.md +9 -1
  108. package/skills/guide/references/restacking.md +23 -4
  109. package/skills/guide/references/ticket-dependencies.md +9 -4
  110. package/skills/implement/SKILL.md +15 -1
  111. package/skills/operate/SKILL.md +104 -13
  112. package/skills/plan/SKILL.md +17 -2
  113. package/skills/plan-review/SKILL.md +8 -0
  114. package/skills/reconcile/SKILL.md +21 -5
  115. package/skills/tickets/SKILL.md +5 -4
  116. package/templates/hosted-service/package.json +2 -2
@@ -1,4 +1,11 @@
1
1
  import { proveTargetLineage } from '../kernel/target-lineage'
2
+ import {
3
+ computeHeadPaths,
4
+ headPathsFor,
5
+ headPathsWrite,
6
+ readHeadPaths,
7
+ type HeadPathsArtifact,
8
+ } from '../kernel/head-paths'
2
9
  import {
3
10
  isRepositoryAuthorityLapse,
4
11
  RepositoryAuthorityLapsed,
@@ -55,6 +62,7 @@ import {
55
62
  MixedVersionDeferral,
56
63
  } from '../kernel/mixed-version'
57
64
  import { guardForge, ForgeCooldown } from '../kernel/guarded-forge'
65
+ import { leafLandingDeclineReason } from '../kernel/landing-readiness'
58
66
  import {
59
67
  escalationsBeyondJanitor,
60
68
  janitorBlocked,
@@ -82,7 +90,18 @@ import {
82
90
  slotRequest,
83
91
  type CapacityBuild,
84
92
  } from '../kernel/dispatch-capacity'
93
+ import {
94
+ openTicketWait,
95
+ pendingWaitRequest,
96
+ ticketWaitRelease,
97
+ waitParked,
98
+ waitReleasedText,
99
+ waitResumeDue,
100
+ waitUnresolvableQuestion,
101
+ } from '../kernel/ticket-wait'
102
+ import { changeBlockers } from '../ports/tickets/operations'
85
103
  import { evaluateLandingPolicy } from '../kernel/landing-policy'
104
+ import { landingPolicyIdentity } from '../kernel/landing-policy-identity'
86
105
  import {
87
106
  landingAuthorized,
88
107
  nativeLandingApplied,
@@ -181,14 +200,21 @@ import type { Config } from '../config/schema'
181
200
  import { DISPATCHER, KERNEL, agentActor } from '../events/envelope'
182
201
  import { isRemoteWorkspace } from '../events/workspace-remote'
183
202
  import type { AbEvent, EventWrite } from '../events/catalog'
184
- import type { EventPayload, PinnedAsset } from '../events/payloads'
203
+ import type { AbortDestination, EventPayload, PinnedAsset } from '../events/payloads'
204
+ import type { RepositoryEventPayload } from '../events/repository'
205
+ import { handbackIdentity } from '../kernel/ticket-handbacks'
185
206
  import type { IdSource } from '../ids'
186
207
  import { recordAutoMergeDeferralObservation } from '../kernel/auto-merge'
187
208
  import type { AutoMergeDefaultFact } from '../kernel/auto-merge-default'
188
209
  import { decideNextFromFacts, landingRestackDue } from '../kernel/engine'
189
210
  import { composeBuildConfig } from '../config/live'
190
211
  import { profileConflictDiagnostic, selectProfile } from '../config/profiles'
191
- import { BUILD_EFFECTIVE_CONFIG_ARTIFACT, parseEffectiveBuildConfig } from './build-execution-state'
212
+ import {
213
+ BUILD_EFFECTIVE_CONFIG_ARTIFACT,
214
+ EffectivePipelineUnreadable,
215
+ parseEffectiveBuildConfig,
216
+ readEffectivePipeline,
217
+ } from './build-execution-state'
192
218
  import {
193
219
  DEFAULT_MAX_HARVEST_RECOVERY_ATTEMPTS,
194
220
  decideHarvestControl,
@@ -214,7 +240,14 @@ import {
214
240
  nodeIssueLinksSyncPending,
215
241
  } from '../kernel/node-issue-links'
216
242
  import type { Exec, ExecResult } from '../ports/workspace/git-worktree'
217
- import type { ArtifactMeta, BuildDigest, BuildRecord, BuildStore, Clock } from '../store/types'
243
+ import type {
244
+ ArtifactMeta,
245
+ BuildDigest,
246
+ BuildDigestTicketWait,
247
+ BuildRecord,
248
+ BuildStore,
249
+ Clock,
250
+ } from '../store/types'
218
251
  import { creationBuildSlug } from '../kernel/build-creation'
219
252
  import { preparePinnedAssets } from '../store/ticket-assets'
220
253
  import { resolveRepoOrigin } from '../cli/repo-state'
@@ -873,7 +906,10 @@ export class Dispatcher {
873
906
  return nodeTicketObservationKey(state, await this.nodePollingChildren(slug))
874
907
  }
875
908
  private async nodePollingChildren(slug: string, refresh = false) {
876
- const children: { slug: string; state: Pick<BuildState, 'pollingActivity'> }[] = []
909
+ const children: {
910
+ slug: string
911
+ state: Pick<BuildState, 'pollingActivity'>
912
+ }[] = []
877
913
  for (const { record, digest } of await this.repoBuildDigests()) {
878
914
  if (record.slug === slug) continue
879
915
  // The digest names every node a build ever targeted, so a build it does
@@ -981,23 +1017,29 @@ export class Dispatcher {
981
1017
  }
982
1018
  }
983
1019
  if (pinned === undefined) {
984
- let artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
985
- if (artifact === null) {
986
- this.sweepPins.delete(slug)
987
- return decideNextFromFacts(state, log, this.deps.config)
988
- }
989
- revision = artifact.meta.revision
1020
+ let latest: Awaited<ReturnType<typeof readEffectivePipeline>>
990
1021
  try {
991
- pinned = parseEffectiveBuildConfig(artifact)
1022
+ latest = await readEffectivePipeline(this.store, slug)
992
1023
  } catch (error) {
1024
+ if (!(error instanceof EffectivePipelineUnreadable)) throw error
1025
+ revision = error.revision
993
1026
  this.sweepPins.delete(slug)
994
1027
  if (this.deps.repairBuildConfig === undefined) throw error
995
1028
  await this.deps.repairBuildConfig(slug)
996
- artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
997
- if (artifact === null) throw new Error('configuration repair deposited no pipeline')
998
- revision = artifact.meta.revision
999
- pinned = parseEffectiveBuildConfig(artifact)
1029
+ try {
1030
+ latest = await readEffectivePipeline(this.store, slug)
1031
+ } catch (retry) {
1032
+ if (retry instanceof EffectivePipelineUnreadable) revision = retry.revision
1033
+ throw retry
1034
+ }
1035
+ if (latest === null) throw new Error('configuration repair deposited no pipeline')
1036
+ }
1037
+ if (latest === null) {
1038
+ this.sweepPins.delete(slug)
1039
+ return decideNextFromFacts(state, log, this.deps.config)
1000
1040
  }
1041
+ revision = latest.revision
1042
+ pinned = latest.config
1001
1043
  if (cacheable) {
1002
1044
  // A concurrent deposit may have advanced the revision after the probe:
1003
1045
  // label the bytes with the full response's revision, never the probe's.
@@ -1203,7 +1245,9 @@ export class Dispatcher {
1203
1245
  // A frozen or non-writable message falls through to a wrapper.
1204
1246
  }
1205
1247
  }
1206
- return new AggregateError([error], `${String(error)}; ${lines}`, { cause: error })
1248
+ return new AggregateError([error], `${String(error)}; ${lines}`, {
1249
+ cause: error,
1250
+ })
1207
1251
  }
1208
1252
 
1209
1253
  private async runTick(opts: TickOpts): Promise<TickReport> {
@@ -1257,6 +1301,8 @@ export class Dispatcher {
1257
1301
  if (this.outOfBudget(opts)) return report
1258
1302
  await this.janitor(report, launched, opts)
1259
1303
  if (this.outOfBudget(opts)) return report
1304
+ await this.settleHandbacks()
1305
+ if (this.outOfBudget(opts)) return report
1260
1306
  await this.recoverDispatches(report, launched, paused, opts)
1261
1307
  if (this.outOfBudget(opts)) return report
1262
1308
  if (opts.resumeCurrent === true) await this.resumeCurrent(report, launched, paused, opts)
@@ -1373,7 +1419,11 @@ export class Dispatcher {
1373
1419
  await this.store.appendRepo(this.deps.repo, {
1374
1420
  actor: DISPATCHER,
1375
1421
  type: 'dispatcher.ticket-source-recovered',
1376
- payload: { source: current.source, cause: current.cause, operation: current.operation },
1422
+ payload: {
1423
+ source: current.source,
1424
+ cause: current.cause,
1425
+ operation: current.operation,
1426
+ },
1377
1427
  })
1378
1428
  }
1379
1429
  if (next !== undefined) {
@@ -1428,6 +1478,104 @@ export class Dispatcher {
1428
1478
  ).id
1429
1479
  }
1430
1480
 
1481
+ /** The ticket ref a hand-back actually moved: its current id. */
1482
+ private async handbackTicket(record: BuildRecord): Promise<TicketRef> {
1483
+ return { ...record.ticket!, id: await this.currentTicketId(record) }
1484
+ }
1485
+
1486
+ /** Report a build's committed ticket hand-back once. The journal view is
1487
+ * refreshed first, so a report whose append committed but whose
1488
+ * acknowledgement was lost is seen and never repeated. */
1489
+ private async reportBuildHandback(
1490
+ slug: string,
1491
+ payload: RepositoryEventPayload<'ticket.handed-back'>,
1492
+ ): Promise<void> {
1493
+ await this.store.ensureRepo(this.deps.repo)
1494
+ await this.store.refreshJournal()
1495
+ if (this.store.repositoryFacts().handbacks[handbackIdentity(slug)] !== undefined) return
1496
+ await this.store.appendRepo(this.deps.repo, {
1497
+ actor: DISPATCHER,
1498
+ type: 'ticket.handed-back',
1499
+ payload,
1500
+ })
1501
+ }
1502
+
1503
+ /** Prune a completed build's hand-back identity. Best effort: a failure is
1504
+ * retried by `settleHandbacks` on a later tick. */
1505
+ private async settleBuildHandback(slug: string): Promise<void> {
1506
+ try {
1507
+ await this.store.appendRepo(this.deps.repo, {
1508
+ actor: DISPATCHER,
1509
+ type: 'ticket.handback-settled',
1510
+ payload: { build: slug },
1511
+ })
1512
+ } catch (error) {
1513
+ rethrowAuthorityLapse(error)
1514
+ }
1515
+ }
1516
+
1517
+ /** Settle reported build hand-backs whose build is complete (or gone).
1518
+ * Zero reads and appends while no hand-back is open. */
1519
+ private async settleHandbacks(): Promise<void> {
1520
+ const open = Object.keys(this.store.repositoryFacts().handbacks)
1521
+ if (open.length === 0) return
1522
+ const digests = new Map(
1523
+ (await this.repoBuildDigests(true)).map(({ record, digest }) => [record.slug, digest]),
1524
+ )
1525
+ for (const identity of open) {
1526
+ const slug = identity.slice('build:'.length)
1527
+ const digest = digests.get(slug)
1528
+ if (digest === undefined || digest.terminal === 'done') await this.settleBuildHandback(slug)
1529
+ }
1530
+ }
1531
+
1532
+ /** Report a preparation attempt's committed hand-back once. */
1533
+ private async reportPreparationHandback(
1534
+ attempt: TicketPreparation,
1535
+ payload: RepositoryEventPayload<'ticket.handed-back'>,
1536
+ ): Promise<void> {
1537
+ await this.store.refreshJournal()
1538
+ if (this.store.repositoryFacts().preparation[attempt.attempt]?.reported) return
1539
+ await this.store.appendRepo(this.deps.repo, {
1540
+ actor: DISPATCHER,
1541
+ type: 'ticket.handed-back',
1542
+ payload,
1543
+ })
1544
+ }
1545
+
1546
+ /** Return a build's ticket once for a closed PR or a discard, behind the
1547
+ * `build.ticket-returned` checkpoint, then report the hand-back. */
1548
+ private async returnBuildTicket(
1549
+ record: BuildRecord,
1550
+ events: CurrentBuildFacts,
1551
+ cause: 'pr-closed' | 'discard',
1552
+ role: AbortDestination,
1553
+ comment: (state: string) => string,
1554
+ ): Promise<void> {
1555
+ if (record.ticket === undefined) return
1556
+ let checkpoint = events.latestTicketReturned
1557
+ if (!events.seenTypes.includes('build.ticket-returned')) {
1558
+ const state = role === 'ready' ? this.deps.config.tickets.readyState : this.triageState()
1559
+ const id = await this.currentTicketId(record)
1560
+ await this.deps.tickets.transition(id, state)
1561
+ await this.deps.tickets.comment(id, comment(state))
1562
+ checkpoint = await this.store.append(record.slug, {
1563
+ actor: DISPATCHER,
1564
+ type: 'build.ticket-returned',
1565
+ payload: { ticket: record.ticket, state, cause, role },
1566
+ } satisfies EventWrite<'build.ticket-returned'>)
1567
+ }
1568
+ if (checkpoint === undefined)
1569
+ throw new Error(`build ${record.slug} lost its ticket-returned checkpoint`)
1570
+ await this.reportBuildHandback(record.slug, {
1571
+ ticket: await this.handbackTicket(record),
1572
+ build: record.slug,
1573
+ cause,
1574
+ state: checkpoint.payload.state,
1575
+ role: checkpoint.payload.role ?? role,
1576
+ })
1577
+ }
1578
+
1431
1579
  private async activeTicketIdentities(refs: TicketRef[], listed: Ticket[]): Promise<Set<string>> {
1432
1580
  const key = (ref: TicketRef) => `${ref.source}:${ref.id}`
1433
1581
  const migrations = this.store.repositoryFacts().ticketMigrations
@@ -1561,7 +1709,12 @@ export class Dispatcher {
1561
1709
  startedAt,
1562
1710
  intervalMs: this.deps.config.ticketScanIntervalSeconds * 1000,
1563
1711
  }
1564
- const checkpoint = { startedAt, mode, readinessFingerprint, criteriaFingerprint }
1712
+ const checkpoint = {
1713
+ startedAt,
1714
+ mode,
1715
+ readinessFingerprint,
1716
+ criteriaFingerprint,
1717
+ }
1565
1718
  // The journal measurement alone proves deferral, so the cadence row is not read.
1566
1719
  if (ticketScanDeferredByJournal(input))
1567
1720
  return { ...checkpoint, allowClockRollback: false, due: false }
@@ -1710,7 +1863,12 @@ export class Dispatcher {
1710
1863
  this.workspaceOwner(facts.workspace)?.recovery !== undefined
1711
1864
  )
1712
1865
  return 'already-active'
1713
- if (facts.log.restack.target === undefined && facts.lastCreated !== undefined) {
1866
+ // A build leaving a ticket wait decides its resume restack against a
1867
+ // fresh observation: one forge read per wait end, no event rows.
1868
+ if (
1869
+ (facts.log.restack.target === undefined || waitResumeDue(facts.state)) &&
1870
+ facts.lastCreated !== undefined
1871
+ ) {
1714
1872
  const branch = facts.lastCreated.payload.baseBranch
1715
1873
  await this.observeTarget(slug, branch, undefined, report)
1716
1874
  }
@@ -1843,7 +2001,11 @@ export class Dispatcher {
1843
2001
  // Conservatism: an unresolvable observation (provider error) throws
1844
2002
  // and is contained below — it never reaps.
1845
2003
  if (observation.state === 'running') continue
1846
- let snapshots: { outcome: 'confirmed' | 'unknown'; deleted?: number; error?: string } = {
2004
+ let snapshots: {
2005
+ outcome: 'confirmed' | 'unknown'
2006
+ deleted?: number
2007
+ error?: string
2008
+ } = {
1847
2009
  outcome: 'unknown',
1848
2010
  error: 'provider did not report the snapshot purge',
1849
2011
  }
@@ -2634,7 +2796,9 @@ export class Dispatcher {
2634
2796
  !executionLeaseLive
2635
2797
  ) {
2636
2798
  operation = 'node cascade'
2637
- await this.prepareIntegration(record, state, report, launched, { refreshOnly: true })
2799
+ await this.prepareIntegration(record, state, report, launched, {
2800
+ refreshOnly: true,
2801
+ })
2638
2802
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
2639
2803
  await this.cascadeNode(record, state, report, launched, opts)
2640
2804
  loaded = undefined
@@ -2892,7 +3056,11 @@ export class Dispatcher {
2892
3056
  reason: string,
2893
3057
  report: TickReport,
2894
3058
  ) {
2895
- const rejection = { revision: ticket.revision, target: ticket.target ?? null, reason }
3059
+ const rejection = {
3060
+ revision: ticket.revision,
3061
+ target: ticket.target ?? null,
3062
+ reason,
3063
+ }
2896
3064
  const state = (await this.store.buildFacts(record.slug)).state
2897
3065
  if (!sameParentRejection(state.nodeRestack?.parentRejection, rejection))
2898
3066
  await this.store.append(record.slug, {
@@ -3029,7 +3197,10 @@ export class Dispatcher {
3029
3197
  await this.store.appendIfCurrent(record.slug, state.lastSeq, {
3030
3198
  actor: DISPATCHER,
3031
3199
  type: 'node.parent-cancelled',
3032
- payload: { id: request.id, reason: 'source readback does not confirm requested target' },
3200
+ payload: {
3201
+ id: request.id,
3202
+ reason: 'source readback does not confirm requested target',
3203
+ },
3033
3204
  })
3034
3205
  return
3035
3206
  }
@@ -3160,7 +3331,7 @@ export class Dispatcher {
3160
3331
  private async leafAdmission(slug: string): Promise<boolean> {
3161
3332
  const { state } = await this.store.buildFacts(slug)
3162
3333
  if (
3163
- !epilogueLeaf(state) ||
3334
+ !(epilogueLeaf(state) || waitParked(state)) ||
3164
3335
  state.pendingCommands.some(
3165
3336
  (command) => command.command === 'abort' || command.command === 'pause',
3166
3337
  )
@@ -3453,23 +3624,46 @@ export class Dispatcher {
3453
3624
  if (record.ticket !== undefined && !has('abort.ticket-returned')) {
3454
3625
  const label = 'autobuild:aborted'
3455
3626
  try {
3456
- const current = await tickets.get(await this.currentTicketId(record))
3627
+ const id = await this.currentTicketId(record)
3628
+ const current = await tickets.get(id)
3457
3629
  if (current === null) throw new Error(`ticket no longer exists in ${tickets.name}`)
3630
+ // Labels are a union-only update, so blockedBy is never touched.
3458
3631
  if (!current.labels.includes(label)) {
3459
- await tickets.update(await this.currentTicketId(record), {
3632
+ await tickets.update(id, {
3460
3633
  labels: [...current.labels, label],
3461
3634
  })
3462
3635
  }
3636
+ const requested = events.latestAbort?.payload.to ?? 'triage'
3637
+ const reason = events.latestAbort?.payload.reason?.trim() || undefined
3638
+ const missing =
3639
+ requested === 'ready' ? specConformance(current.body).missing : ([] as string[])
3640
+ const role: AbortDestination =
3641
+ requested === 'ready' && missing.length === 0 ? 'ready' : 'triage'
3463
3642
  const triageState = this.triageState()
3464
- await tickets.transition(await this.currentTicketId(record), triageState)
3643
+ const state = role === 'ready' ? this.deps.config.tickets.readyState : triageState
3644
+ // The one ticket move: straight to the destination, never via triage.
3645
+ await tickets.transition(id, state)
3465
3646
  await tickets.comment(
3466
- await this.currentTicketId(record),
3467
- `build ${record.slug} aborted — returned to ${triageState}`,
3647
+ id,
3648
+ (missing.length > 0
3649
+ ? `build ${record.slug} aborted — returned to ${state} instead of ${this.deps.config.tickets.readyState}: ` +
3650
+ 'the ticket does not conform to the spec standard (.agents/skills/ab-guide/references/spec-standard.md).\n' +
3651
+ `Missing: ${missing.join('; ')}.`
3652
+ : `build ${record.slug} aborted — returned to ${state}`) +
3653
+ (reason !== undefined ? `\nReason: ${reason}` : ''),
3468
3654
  )
3469
3655
  await append({
3470
3656
  actor: DISPATCHER,
3471
3657
  type: 'abort.ticket-returned',
3472
- payload: { ticket: record.ticket, state: triageState, label },
3658
+ payload: {
3659
+ ticket: record.ticket,
3660
+ state,
3661
+ label,
3662
+ role,
3663
+ ...(requested !== role ? { requested } : {}),
3664
+ ...(reason !== undefined ? { reason: reason.slice(0, 2000) } : {}),
3665
+ ...(missing.length > 0 ? { missing } : {}),
3666
+ },
3473
3667
  })
3474
3668
  } catch (error) {
3475
3669
  fail('ticket handback', `${tickets.name} ticket ${record.ticket.id}`, error)
@@ -3477,11 +3671,39 @@ export class Dispatcher {
3477
3671
  }
3478
3672
  }
3479
3673
 
3674
+ // Reported from the checkpoint, never a re-read of the ticket, so a
3675
+ // retry reports exactly what the committed move did.
3676
+ if (record.ticket !== undefined) {
3677
+ try {
3678
+ const returned = events.latestTicketReturned
3679
+ if (returned?.type !== 'abort.ticket-returned')
3680
+ throw new Error('abort.ticket-returned checkpoint is not readable')
3681
+ const checkpoint = returned.payload
3682
+ const role: AbortDestination =
3683
+ checkpoint.role ??
3684
+ (checkpoint.state === this.deps.config.tickets.readyState ? 'ready' : 'triage')
3685
+ await this.reportBuildHandback(record.slug, {
3686
+ ticket: await this.handbackTicket(record),
3687
+ build: record.slug,
3688
+ cause: 'abort',
3689
+ state: checkpoint.state,
3690
+ role,
3691
+ ...(checkpoint.requested !== undefined ? { requested: checkpoint.requested } : {}),
3692
+ ...(checkpoint.reason !== undefined ? { reason: checkpoint.reason } : {}),
3693
+ ...(checkpoint.missing !== undefined ? { missing: checkpoint.missing } : {}),
3694
+ })
3695
+ } catch (error) {
3696
+ fail('hand-back report', `build ${record.slug}`, error)
3697
+ return
3698
+ }
3699
+ }
3700
+
3480
3701
  await append({
3481
3702
  actor: DISPATCHER,
3482
3703
  type: 'build.completed',
3483
3704
  payload: { outcome: 'abandoned' },
3484
3705
  })
3706
+ if (record.ticket !== undefined) await this.settleBuildHandback(record.slug)
3485
3707
  await this.reclaimPrAttachments(record.slug, events)
3486
3708
  report.abandoned += 1
3487
3709
  }
@@ -3495,26 +3717,23 @@ export class Dispatcher {
3495
3717
  report: TickReport,
3496
3718
  ): Promise<void> {
3497
3719
  const store = this.store
3498
- const { tickets } = this.deps
3499
3720
  await this.releaseWorkspace(record.slug, events, 'discard')
3500
3721
  if (record.lease !== undefined) {
3501
3722
  await store.releaseLease(record.slug, record.lease.holder)
3502
3723
  }
3503
- if (record.ticket !== undefined) {
3504
- await tickets.transition(
3505
- await this.currentTicketId(record),
3506
- this.deps.config.tickets.readyState,
3507
- )
3508
- await tickets.comment(
3509
- await this.currentTicketId(record),
3510
- `build ${record.slug} was discarded during dispatch — returned to ${this.deps.config.tickets.readyState}`,
3511
- )
3512
- }
3724
+ await this.returnBuildTicket(
3725
+ record,
3726
+ events,
3727
+ 'discard',
3728
+ 'ready',
3729
+ (state) => `build ${record.slug} was discarded during dispatch — returned to ${state}`,
3730
+ )
3513
3731
  await store.append(record.slug, {
3514
3732
  actor: DISPATCHER,
3515
3733
  type: 'build.completed',
3516
3734
  payload: { outcome: 'discarded' },
3517
3735
  } satisfies EventWrite<'build.completed'>)
3736
+ if (record.ticket !== undefined) await this.settleBuildHandback(record.slug)
3518
3737
  report.discarded += 1
3519
3738
  }
3520
3739
 
@@ -3526,12 +3745,18 @@ export class Dispatcher {
3526
3745
  kind?: 'work' | 'node',
3527
3746
  ): Promise<{ sha: string; buildTrailerPresent?: boolean }> {
3528
3747
  if (kind === 'node')
3529
- await this.recoverNodeContributions(await this.repoBuildDigests(), { slug: record.slug, sha })
3748
+ await this.recoverNodeContributions(await this.repoBuildDigests(), {
3749
+ slug: record.slug,
3750
+ sha,
3751
+ })
3530
3752
  const read = this.deps.forge.readCommitMessage
3531
3753
  if (read === undefined) return { sha }
3532
3754
  try {
3533
3755
  const message = await read.call(this.deps.forge, workspacePath, sha)
3534
- return { sha, buildTrailerPresent: hasBuildTrailer(message, record.slug) }
3756
+ return {
3757
+ sha,
3758
+ buildTrailerPresent: hasBuildTrailer(message, record.slug),
3759
+ }
3535
3760
  } catch (error) {
3536
3761
  rethrowAuthorityLapse(error)
3537
3762
  await this.store.append(record.slug, {
@@ -3623,12 +3848,14 @@ export class Dispatcher {
3623
3848
  // finished after the publisher confirmed cancellation.
3624
3849
  const ready = async (candidate: BuildState): Promise<boolean> => {
3625
3850
  if (
3626
- (integration ? executionLeaseLive : candidate.sessions.open.length > 0) ||
3627
- candidate.status === 'paused' ||
3628
- candidate.status === 'done' ||
3629
- candidate.status === 'aborted' ||
3630
- escalationsBeyondJanitor(candidate).length ||
3631
- candidate.pendingCommands.length
3851
+ integration
3852
+ ? executionLeaseLive ||
3853
+ candidate.status === 'paused' ||
3854
+ candidate.status === 'done' ||
3855
+ candidate.status === 'aborted' ||
3856
+ escalationsBeyondJanitor(candidate).length ||
3857
+ candidate.pendingCommands.length
3858
+ : leafLandingDeclineReason(candidate) !== undefined
3632
3859
  )
3633
3860
  return false
3634
3861
  if (integration) {
@@ -3657,7 +3884,8 @@ export class Dispatcher {
3657
3884
  parent: current.integration.cycle.parent,
3658
3885
  cycle: current.integration.cycle.id,
3659
3886
  }
3660
- : current.pr && {
3887
+ : // The leaf candidate's shared definition is `leafLandingCandidate`.
3888
+ current.pr && {
3661
3889
  head: current.pr.headSha,
3662
3890
  parent:
3663
3891
  (await store.buildFacts(record.slug)).log.restack.completed?.targetBase ??
@@ -3692,6 +3920,15 @@ export class Dispatcher {
3692
3920
  state = current
3693
3921
  break
3694
3922
  }
3923
+ // A deferred candidate waits for its recorded changed paths: no ticket
3924
+ // read, evaluation or append until the head or the policy changes.
3925
+ const rules = this.deps.config.landing
3926
+ const policy = landingPolicyIdentity(rules)
3927
+ const deferral = current.landing?.deferral
3928
+ if (deferral?.policy === policy && sameLandingCandidate(candidate, deferral.candidate)) {
3929
+ isReady = false
3930
+ break
3931
+ }
3695
3932
  if (!record.ticket) throw new Error('Merge policy requires a readable source ticket')
3696
3933
  const ticket = await tickets.get(await this.currentTicketId(record))
3697
3934
  if (!ticket)
@@ -3713,11 +3950,53 @@ export class Dispatcher {
3713
3950
  : { kind: 'root' as const },
3714
3951
  labels: ticket.labels,
3715
3952
  }
3716
- const decision = evaluateLandingPolicy(this.deps.config.landing, input)
3953
+ // Path predicates read the head's already-reduced summary. Only a
3954
+ // reached path rule on a head beyond the preview reads the complete
3955
+ // set, once per new candidate.
3956
+ const recorded = headPathsFor(current, candidate.head)
3957
+ let decision = evaluateLandingPolicy(
3958
+ rules,
3959
+ input,
3960
+ recorded.recorded
3961
+ ? {
3962
+ recorded: true,
3963
+ complete: recorded.record.total === recorded.record.preview.length,
3964
+ paths: recorded.record.preview,
3965
+ }
3966
+ : { recorded: false },
3967
+ )
3968
+ if ('deferred' in decision && decision.deferred === 'paths-incomplete' && recorded.recorded)
3969
+ decision = evaluateLandingPolicy(rules, input, {
3970
+ recorded: true,
3971
+ complete: true,
3972
+ paths: (await readHeadPaths(store, record.slug, recorded.record)).paths,
3973
+ })
3717
3974
  if (!(await ready(current))) {
3718
3975
  isReady = false
3719
3976
  break
3720
3977
  }
3978
+ if ('deferred' in decision) {
3979
+ if (decision.deferred !== 'paths-unrecorded')
3980
+ throw new Error(
3981
+ `Merge policy evaluation stayed ${decision.deferred} on a complete path set`,
3982
+ )
3983
+ if (
3984
+ await store.appendIfCurrent(record.slug, current.lastSeq, {
3985
+ actor: DISPATCHER,
3986
+ type: 'landing.deferred',
3987
+ payload: {
3988
+ candidate,
3989
+ reason: decision.deferred,
3990
+ rule: decision.rule,
3991
+ policy,
3992
+ },
3993
+ })
3994
+ ) {
3995
+ isReady = false
3996
+ break
3997
+ }
3998
+ continue
3999
+ }
3721
4000
  if (
3722
4001
  await store.appendIfCurrent(record.slug, current.lastSeq, {
3723
4002
  actor: DISPATCHER,
@@ -3798,7 +4077,7 @@ export class Dispatcher {
3798
4077
  retained !== null &&
3799
4078
  this.workspaceOwner(retained)?.recovery !== undefined &&
3800
4079
  (events.lastExecution === 'lost' || events.lastExecution === 'stopped') &&
3801
- epilogueLeaf(events.state)
4080
+ (epilogueLeaf(events.state) || waitParked(events.state))
3802
4081
  ) {
3803
4082
  report.conflicted += 1
3804
4083
  return
@@ -4128,7 +4407,10 @@ export class Dispatcher {
4128
4407
  await store.append(record.slug, {
4129
4408
  actor: DISPATCHER,
4130
4409
  type: 'landing.native-applied',
4131
- payload: { enabled: false, ...(enableSeq !== undefined ? { enableSeq } : {}) },
4410
+ payload: {
4411
+ enabled: false,
4412
+ ...(enableSeq !== undefined ? { enableSeq } : {}),
4413
+ },
4132
4414
  })
4133
4415
  }
4134
4416
  } else if (result.kind === 'deferred' && result.reason) {
@@ -4293,19 +4575,20 @@ export class Dispatcher {
4293
4575
  } satisfies EventWrite<'pr.closed'>)
4294
4576
  }
4295
4577
  await this.releaseWorkspace(record.slug, events)
4296
- if (record.ticket) {
4297
- const triageState = this.triageState()
4298
- await tickets.transition(await this.currentTicketId(record), triageState)
4299
- await tickets.comment(
4300
- await this.currentTicketId(record),
4301
- `build ${record.slug} PR closed without merging (${pr.url}) — returned to ${triageState}`,
4302
- )
4303
- }
4578
+ await this.returnBuildTicket(
4579
+ record,
4580
+ events,
4581
+ 'pr-closed',
4582
+ 'triage',
4583
+ (state) =>
4584
+ `build ${record.slug} PR closed without merging (${pr.url}) — returned to ${state}`,
4585
+ )
4304
4586
  await store.append(record.slug, {
4305
4587
  actor: DISPATCHER,
4306
4588
  type: 'build.completed',
4307
4589
  payload: { outcome: 'closed-unmerged' },
4308
4590
  } satisfies EventWrite<'build.completed'>)
4591
+ if (record.ticket) await this.settleBuildHandback(record.slug)
4309
4592
  await this.reclaimPrAttachments(record.slug, events)
4310
4593
  report.closed += 1
4311
4594
  return
@@ -4384,7 +4667,9 @@ export class Dispatcher {
4384
4667
  // Same predicate preservation archives under: only local-git keeps
4385
4668
  // archive refs in the local repository.
4386
4669
  ...(restoration?.length
4387
- ? { restorationArchives: this.deps.forge.name === 'local-git' ? 'local' : 'remote' }
4670
+ ? {
4671
+ restorationArchives: this.deps.forge.name === 'local-git' ? 'local' : 'remote',
4672
+ }
4388
4673
  : {}),
4389
4674
  })
4390
4675
  const skipped = [
@@ -4742,7 +5027,12 @@ export class Dispatcher {
4742
5027
  ...(config.pr !== undefined ? { pr: config.pr } : {}),
4743
5028
  ...(seed?.assets !== undefined && seed.assets.length > 0 ? { assets: seed.assets } : {}),
4744
5029
  ...(seed?.issueLinks !== undefined && seed.issueLinks.length > 0
4745
- ? { issueLinks: seed.issueLinks.map(({ issue, intent }) => ({ issue, intent })) }
5030
+ ? {
5031
+ issueLinks: seed.issueLinks.map(({ issue, intent }) => ({
5032
+ issue,
5033
+ intent,
5034
+ })),
5035
+ }
4746
5036
  : {}),
4747
5037
  ...(seed?.profile !== undefined ? { profile: seed.profile } : {}),
4748
5038
  }
@@ -5002,7 +5292,10 @@ export class Dispatcher {
5002
5292
  await store.appendWithArtifacts(record.slug, [spec], (deposited) => ({
5003
5293
  actor: DISPATCHER,
5004
5294
  type: 'spec.imported' as const,
5005
- payload: { artifact: artifactRefOf(deposited), ticket: ticket!.ref },
5295
+ payload: {
5296
+ artifact: artifactRefOf(deposited),
5297
+ ticket: ticket!.ref,
5298
+ },
5006
5299
  }))
5007
5300
  }
5008
5301
  }
@@ -5163,6 +5456,239 @@ export class Dispatcher {
5163
5456
  }
5164
5457
  }
5165
5458
 
5459
+ // ── c'. Ticket waits (SPEC §11 "Ticket waits") ─────────────────────────────
5460
+
5461
+ /**
5462
+ * Validate every pending `wait.requested` against the ticket source: the
5463
+ * dispatcher holds the source for local and hosted builds alike, so a
5464
+ * build session needs no ticket credential to declare a wait. Accepted, the
5465
+ * missing blockers are added to the build's ticket and `wait.entered` parks
5466
+ * the build; refused, `wait.refused` writes nothing to the ticket and the
5467
+ * declaring phase re-runs with the reason as guidance.
5468
+ *
5469
+ * Runs from the lease sweep's per-build pass, before that build's sweep,
5470
+ * whether or not the repository is paused or accepting new work: waits are
5471
+ * bookkeeping for existing work.
5472
+ *
5473
+ * Per-tick cost: none beyond the digest listing the sweep already makes.
5474
+ * Only a build whose digest marks a pending request (`waitPending`) is read
5475
+ * further — one reduced `buildFacts` read plus its ticket-source calls. A
5476
+ * request is pending for one tick per declaration, plus retries after a
5477
+ * source failure, plus the ticks its remote commit publication takes to
5478
+ * settle (no ticket calls while it does).
5479
+ */
5480
+ private async serviceWaitRequests(record: BuildRecord, report: TickReport): Promise<void> {
5481
+ const { state } = await this.store.buildFacts(record.slug)
5482
+ const request = pendingWaitRequest(state)
5483
+ if (request === undefined || state.kind === 'node') return
5484
+ try {
5485
+ await this.serviceWaitRequest(record, state, request)
5486
+ } catch (error) {
5487
+ rethrowAuthorityLapse(error)
5488
+ // A source failure writes nothing; the request is decided next tick.
5489
+ const message =
5490
+ error instanceof Error || isForgeFailure(error) ? error.message : String(error)
5491
+ report.janitorFailed += 1
5492
+ report.janitorDiagnostics.push(
5493
+ `build ${record.slug}: ticket wait ${request.id} not checked — ${message}`,
5494
+ )
5495
+ }
5496
+ }
5497
+
5498
+ private async serviceWaitRequest(
5499
+ record: BuildRecord,
5500
+ state: BuildState,
5501
+ request: NonNullable<BuildState['waitRequest']>,
5502
+ ): Promise<void> {
5503
+ const refuse = async (
5504
+ cause: EventPayload<'wait.refused'>['cause'],
5505
+ tickets: string[],
5506
+ message: string,
5507
+ ): Promise<void> => {
5508
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
5509
+ actor: DISPATCHER,
5510
+ type: 'wait.refused',
5511
+ payload: { id: request.id, cause, tickets, message },
5512
+ })
5513
+ }
5514
+ // An implement declaration's commits are published before the wait is
5515
+ // entered. Until the settlement stage records `wait.published` the
5516
+ // request stays pending; a recorded loss refuses it.
5517
+ const publication = request.publication
5518
+ if (publication !== undefined && !publication.published) {
5519
+ if (publication.lost)
5520
+ return refuse(
5521
+ 'publication-lost',
5522
+ request.tickets,
5523
+ "publishing this build's commits before the wait failed: the publication was lost, " +
5524
+ 'so your local commits were not published; continue, or declare the wait again',
5525
+ )
5526
+ return
5527
+ }
5528
+ const tickets = this.deps.tickets
5529
+ if (!record.ticket)
5530
+ return refuse(
5531
+ 'no-source-ticket',
5532
+ request.tickets,
5533
+ 'this build has no source ticket to record blockers on; continue without waiting, or escalate',
5534
+ )
5535
+ const found: Ticket[] = []
5536
+ const unknown: string[] = []
5537
+ for (const id of request.tickets) {
5538
+ const ticket = await tickets.get(id)
5539
+ if (ticket === null) unknown.push(id)
5540
+ else found.push(ticket)
5541
+ }
5542
+ if (unknown.length)
5543
+ return refuse(
5544
+ 'unknown-ticket',
5545
+ unknown,
5546
+ `not found in the ${tickets.name} ticket source: ${unknown.join(', ')}; check the ids and declare the wait again, or continue without it`,
5547
+ )
5548
+ const ownId = await this.currentTicketId(record)
5549
+ const own = found.filter((ticket) => ticket.ref.id === ownId).map((ticket) => ticket.ref.id)
5550
+ if (own.length)
5551
+ return refuse(
5552
+ 'own-ticket',
5553
+ own,
5554
+ `${ownId} is this build's own ticket; a build cannot wait on itself`,
5555
+ )
5556
+ const rejectedState = this.rejectedState()
5557
+ const completed = found
5558
+ .filter((ticket) => ticket.resolved && !holdsState(ticket.state, rejectedState))
5559
+ .map((ticket) => ticket.ref.id)
5560
+ if (completed.length)
5561
+ return refuse(
5562
+ 'completed',
5563
+ completed,
5564
+ `already completed: ${completed.join(', ')}; continue without waiting on them`,
5565
+ )
5566
+ const canonical = [...new Map(found.map((ticket) => [ticket.ref.id, ticket.ref])).values()]
5567
+ const self = await tickets.get(ownId)
5568
+ if (self === null) throw new Error(`build ticket ${ownId} is missing from ${tickets.name}`)
5569
+ const missing = canonical
5570
+ .map((ref) => ref.id)
5571
+ .filter((id) => !(self.blockedBy ?? []).includes(id))
5572
+ if (missing.length) await changeBlockers(tickets, ownId, missing, 'block')
5573
+ const escalation = this.deps.ids('esc')
5574
+ const names = canonical.map((ref) => ref.id).join(', ')
5575
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
5576
+ actor: DISPATCHER,
5577
+ type: 'wait.entered',
5578
+ payload: {
5579
+ id: request.id,
5580
+ escalation,
5581
+ tickets: canonical.map((ref) => ({
5582
+ source: ref.source,
5583
+ id: ref.id,
5584
+ ...(ref.url !== undefined ? { url: ref.url } : {}),
5585
+ ...(ref.title !== undefined ? { title: ref.title } : {}),
5586
+ })),
5587
+ reason: request.reason,
5588
+ question:
5589
+ `Waiting on ${names} to complete: ${request.reason}. ` +
5590
+ `The wait ends when they all complete; answer to end it early, and ${request.phase} resumes with the answer.`,
5591
+ },
5592
+ })
5593
+ }
5594
+
5595
+ /**
5596
+ * End open ticket waits whose tickets settled (SPEC §11 "Ticket waits").
5597
+ * Every waited ticket completed: `wait.ended {cause: automatic}`, and the
5598
+ * build resumes ahead of new claims. Any waited ticket rejected (the
5599
+ * configured rejected role) or deleted: one `policy/wait-unresolvable`
5600
+ * escalation naming it, which the reducer reads as the wait's end. A wait
5601
+ * with tickets still pending stays in place.
5602
+ *
5603
+ * Runs once per tick from the lease sweep, before its per-build pass,
5604
+ * whether or not the repository is paused or accepting new work.
5605
+ *
5606
+ * Per-tick cost: the open waits come from the digests the sweep already
5607
+ * read (`ticketWait`), so no store read is added. With no open wait it
5608
+ * makes no call; otherwise one batched `dependencyStates` over the unique
5609
+ * waited ids. A build's reduced `buildFacts` is read only when the stage
5610
+ * is about to write for it — once per wait end. A source failure writes
5611
+ * nothing and the waits are checked again next tick.
5612
+ */
5613
+ private async releaseTicketWaits(
5614
+ entries: readonly { record: BuildRecord; digest: BuildDigest }[],
5615
+ report: TickReport,
5616
+ opts: TickOpts,
5617
+ ): Promise<void> {
5618
+ const tickets = this.deps.tickets
5619
+ const migrations = this.store.repositoryFacts().ticketMigrations
5620
+ const waiting: { record: BuildRecord; wait: BuildDigestTicketWait; ids: string[] }[] = []
5621
+ for (const { record, digest } of entries) {
5622
+ const wait = digest.ticketWait
5623
+ if (digest.terminal !== undefined || digest.kind === 'node' || wait === undefined) continue
5624
+ try {
5625
+ const ids = wait.tickets.map(
5626
+ (ref) => resolveTicketRef(migrations, ref, tickets.name, record.slug).id,
5627
+ )
5628
+ waiting.push({ record, wait, ids })
5629
+ } catch (error) {
5630
+ const message = error instanceof Error ? error.message : String(error)
5631
+ report.janitorFailed += 1
5632
+ report.janitorDiagnostics.push(
5633
+ `build ${record.slug}: ticket wait ${wait.id} not checked — ${message}`,
5634
+ )
5635
+ }
5636
+ }
5637
+ if (waiting.length === 0 || this.outOfBudget(opts)) return
5638
+ const nodes = new Map<string, DependencyNode>()
5639
+ try {
5640
+ const rejectedState = this.rejectedState()
5641
+ const states = await tickets.dependencyStates([...new Set(waiting.flatMap(({ ids }) => ids))])
5642
+ for (const state of states) nodes.set(state.id, markRejected(state, rejectedState))
5643
+ } catch (error) {
5644
+ rethrowAuthorityLapse(error)
5645
+ const message =
5646
+ error instanceof Error || isForgeFailure(error) ? error.message : String(error)
5647
+ report.janitorFailed += 1
5648
+ report.janitorDiagnostics.push(`ticket waits not checked — ${message}`)
5649
+ return
5650
+ }
5651
+ for (const { record, wait, ids } of waiting) {
5652
+ const release = ticketWaitRelease(ids, nodes)
5653
+ if (release === undefined) continue
5654
+ if (this.outOfBudget(opts)) return
5655
+ try {
5656
+ const { state } = await this.store.buildFacts(record.slug)
5657
+ const open = openTicketWait(state)
5658
+ if (open?.id !== wait.id) continue
5659
+ // A stale append is skipped; the next tick decides again.
5660
+ if (release.kind === 'complete')
5661
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
5662
+ actor: DISPATCHER,
5663
+ type: 'wait.ended',
5664
+ payload: { id: open.id, cause: 'automatic', message: waitReleasedText(ids) },
5665
+ })
5666
+ else
5667
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
5668
+ actor: DISPATCHER,
5669
+ type: 'escalation.raised',
5670
+ payload: {
5671
+ id: this.deps.ids('esc'),
5672
+ phase: open.phase,
5673
+ round: open.round,
5674
+ source: 'policy',
5675
+ policyCause: 'wait-unresolvable',
5676
+ question: waitUnresolvableQuestion(ids, release.tickets, tickets.name),
5677
+ refs: release.tickets.map((ticket) => ticket.id),
5678
+ },
5679
+ })
5680
+ } catch (error) {
5681
+ rethrowAuthorityLapse(error)
5682
+ const message =
5683
+ error instanceof Error || isForgeFailure(error) ? error.message : String(error)
5684
+ report.janitorFailed += 1
5685
+ report.janitorDiagnostics.push(
5686
+ `build ${record.slug}: ticket wait ${wait.id} not released — ${message}`,
5687
+ )
5688
+ }
5689
+ }
5690
+ }
5691
+
5166
5692
  // ── d. Lease sweep (SPEC §15.6-C) ──────────────────────────────────────────
5167
5693
 
5168
5694
  /**
@@ -5195,12 +5721,17 @@ export class Dispatcher {
5195
5721
  opts: TickOpts = {},
5196
5722
  ): Promise<void> {
5197
5723
  const now = this.deps.clock().getTime()
5724
+ const entries = await this.repoBuildDigests()
5725
+ await this.releaseTicketWaits(entries, report, opts)
5198
5726
  // Terminal builds are filtered on the digest before the lease and TTL
5199
5727
  // checks, so a zero TTL cannot fall through to a log read.
5200
- for (const record of await this.nonterminalBuilds()) {
5201
- if (launched.has(record.slug)) continue
5728
+ for (const { record, digest } of entries) {
5729
+ if (digest.terminal !== undefined) continue
5202
5730
  // Budget gate: the sweep re-attaches runners per expired build.
5203
5731
  if (this.outOfBudget(opts)) break
5732
+ if (digest.waitPending && digest.kind !== 'node')
5733
+ await this.serviceWaitRequests(record, report)
5734
+ if (launched.has(record.slug)) continue
5204
5735
  try {
5205
5736
  await this.sweepBuild(record, report, launched, paused, now)
5206
5737
  } catch (error) {
@@ -5259,7 +5790,12 @@ export class Dispatcher {
5259
5790
  if (retryIntent && state.pendingCommands.length === 0) {
5260
5791
  try {
5261
5792
  await publicationRetryGate(
5262
- { store: this.store, slug: record.slug, clock: this.deps.clock, actor: DISPATCHER },
5793
+ {
5794
+ store: this.store,
5795
+ slug: record.slug,
5796
+ clock: this.deps.clock,
5797
+ actor: DISPATCHER,
5798
+ },
5263
5799
  retryIntent.operation,
5264
5800
  retryIntent.id,
5265
5801
  )
@@ -5382,10 +5918,15 @@ export class Dispatcher {
5382
5918
  if (runs && state.kind !== 'node' && !(await this.leafAdmission(record.slug))) return
5383
5919
  // A finished parked leaf keeps its workspace until merge or close; a
5384
5920
  // stale environment is reaped only for an admitted replacement.
5921
+ // A leaf waiting on tickets, or on the dispatcher's check of its wait,
5922
+ // keeps its workspace, branch and phase work the same way.
5385
5923
  if (
5386
5924
  !runs &&
5387
5925
  state.kind !== 'node' &&
5388
- ((decision.kind === 'wait' && decision.reason === 'awaiting-pr') || epilogueLeaf(state))
5926
+ ((decision.kind === 'wait' && decision.reason === 'awaiting-pr') ||
5927
+ epilogueLeaf(state) ||
5928
+ waitParked(state) ||
5929
+ pendingWaitRequest(state) !== undefined)
5389
5930
  )
5390
5931
  return
5391
5932
  // A provider- or log-proved END in the same generation re-attaches in
@@ -5569,6 +6110,16 @@ export class Dispatcher {
5569
6110
  `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'}`,
5570
6111
  )
5571
6112
  }
6113
+ // A committed `ticket.handed-back` whose acknowledgement or resolution
6114
+ // was lost means the hand-back already happened, and a watcher may have
6115
+ // moved the ticket since. Resolve without touching the ticket.
6116
+ const handback = attempt.handback ?? attempt.readyState
6117
+ await this.store.refreshJournal()
6118
+ if (this.store.repositoryFacts().preparation[attempt.attempt]?.reported)
6119
+ return await this.preparationResolved(
6120
+ attempt,
6121
+ handback === attempt.readyState ? 'handed-back' : 'bounced',
6122
+ )
5572
6123
  const ref = resolveTicketRef(
5573
6124
  this.store.repositoryFacts().ticketMigrations,
5574
6125
  attempt.ticket,
@@ -5584,8 +6135,22 @@ export class Dispatcher {
5584
6135
  'Ticket state is unavailable; ticket unchanged. Inspect the provider record before manually retrying.',
5585
6136
  )
5586
6137
  const state = (value: string) => value.toLowerCase()
5587
- const handback = attempt.handback ?? attempt.readyState
6138
+ // Only a confirmed claim left Ready; an unconfirmed one that stayed
6139
+ // Ready was never handed back and gets no report.
6140
+ const reportHandback = async (): Promise<void> => {
6141
+ if (!attempt.claimed) return
6142
+ const ready = handback === attempt.readyState
6143
+ await this.reportPreparationHandback(attempt, {
6144
+ ticket: ref,
6145
+ attempt: attempt.attempt,
6146
+ cause: ready ? 'preparation-failed' : 'spec-bounce',
6147
+ state: handback,
6148
+ role: ready ? 'ready' : 'triage',
6149
+ ...(attempt.missing && attempt.missing.length > 0 ? { missing: attempt.missing } : {}),
6150
+ })
6151
+ }
5588
6152
  if (state(ticket.state) === state(handback)) {
6153
+ await reportHandback()
5589
6154
  await this.preparationResolved(
5590
6155
  attempt,
5591
6156
  handback === attempt.readyState ? 'handed-back' : 'bounced',
@@ -5603,6 +6168,7 @@ export class Dispatcher {
5603
6168
  `Confirmed claim but ticket externally changed to state ${ticket.state}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
5604
6169
  )
5605
6170
  await this.deps.tickets.transition(ref.id, handback)
6171
+ await reportHandback()
5606
6172
  await this.preparationResolved(
5607
6173
  attempt,
5608
6174
  handback === attempt.readyState ? 'handed-back' : 'bounced',
@@ -5793,7 +6359,10 @@ export class Dispatcher {
5793
6359
  )
5794
6360
  })
5795
6361
  const destinationHeads = new Map<string, PresenceObservation>()
5796
- const demands: { slug: string; request: EventPayload<'node.restack-requested'> }[] = []
6362
+ const demands: {
6363
+ slug: string
6364
+ request: EventPayload<'node.restack-requested'>
6365
+ }[] = []
5797
6366
  const verdicts = new Map<string, DependencyVerdict>()
5798
6367
  const failed = new Set<string>()
5799
6368
  const targetBlocked = new Set<string>()
@@ -6020,13 +6589,29 @@ export class Dispatcher {
6020
6589
  }
6021
6590
  if (!conformance.conforms) {
6022
6591
  attempt.handback = this.triageState()
6592
+ const missing = conformance.missing.length > 0 ? conformance.missing : undefined
6593
+ if (missing) attempt.missing = missing
6023
6594
  await store.appendRepo(this.deps.repo, {
6024
6595
  actor: DISPATCHER,
6025
6596
  type: 'ticket-preparation.handback-selected',
6026
- payload: { attempt: attempt.attempt, ticket: attempt.ticket, state: attempt.handback },
6597
+ payload: {
6598
+ attempt: attempt.attempt,
6599
+ ticket: attempt.ticket,
6600
+ state: attempt.handback,
6601
+ ...(missing ? { missing } : {}),
6602
+ },
6027
6603
  })
6028
6604
  stage = 'bounce'
6029
6605
  await this.bounce(ticket, conformance.missing)
6606
+ stage = 'handback-report'
6607
+ await this.reportPreparationHandback(attempt, {
6608
+ ticket: ticket.ref,
6609
+ attempt: attempt.attempt,
6610
+ cause: 'spec-bounce',
6611
+ state: attempt.handback,
6612
+ role: 'triage',
6613
+ ...(missing ? { missing } : {}),
6614
+ })
6030
6615
  await this.preparationResolved(attempt, 'bounced')
6031
6616
  report.bounced += 1
6032
6617
  report.queued -= 1
@@ -6154,7 +6739,10 @@ export class Dispatcher {
6154
6739
  ticket: Ticket,
6155
6740
  scan: TargetScan,
6156
6741
  ): Promise<
6157
- | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
6742
+ | {
6743
+ target: NonNullable<EventPayload<'build.created'>['target']>
6744
+ branch: string
6745
+ }
6158
6746
  | string
6159
6747
  | undefined
6160
6748
  > {
@@ -6502,7 +7090,12 @@ export class Dispatcher {
6502
7090
  )
6503
7091
  continue
6504
7092
  await suspendNativeLanding(
6505
- { store: this.store, forge, slug: child.record.slug, workspacePath: checkout },
7093
+ {
7094
+ store: this.store,
7095
+ forge,
7096
+ slug: child.record.slug,
7097
+ workspacePath: checkout,
7098
+ },
6506
7099
  `node:${record.slug}:${operation}`,
6507
7100
  )
6508
7101
  }
@@ -6740,6 +7333,7 @@ export class Dispatcher {
6740
7333
  head: exact.headSha,
6741
7334
  }
6742
7335
  let context: string | undefined
7336
+ let headPaths: HeadPathsArtifact | undefined
6743
7337
  await this.withKernelRepository(async (path) => {
6744
7338
  const head = await forge.rewrite!.snapshot({
6745
7339
  workspacePath: path,
@@ -6753,22 +7347,29 @@ export class Dispatcher {
6753
7347
  ref: `refs/autobuild/archive/${record.slug}/${head}`,
6754
7348
  sha: head,
6755
7349
  })
7350
+ const exec = forge.kernelExec ?? this.deps.exec
7351
+ // Snapshot fetch brings the complete head ancestry, including merge sides.
7352
+ // A parent may have advanced independently and need its own fetch.
7353
+ const parent = await exec(['git', 'cat-file', '-e', `${exact.parentSha}^{commit}`], {
7354
+ cwd: path,
7355
+ })
7356
+ if (parent.exitCode !== 0) {
7357
+ const fetched = await exec(['git', 'fetch', '--no-tags', 'origin', exact.parentSha], {
7358
+ cwd: path,
7359
+ })
7360
+ if (fetched.exitCode !== 0)
7361
+ throw new Error(`cannot fetch node verification parent: ${fetched.stderr}`)
7362
+ }
7363
+ // The cycle's candidate head is recorded once, with the cycle.
7364
+ if (!headPathsFor(current, exact.headSha).recorded)
7365
+ headPaths = await computeHeadPaths(exec, path, {
7366
+ source: 'integration',
7367
+ head: exact.headSha,
7368
+ destination: exact.parentSha,
7369
+ })
6756
7370
  if (
6757
7371
  config.verify.steps.some((step) => config.verify.stepConfigs[step]?.kind === 'agent')
6758
7372
  ) {
6759
- const exec = forge.kernelExec ?? this.deps.exec
6760
- // Snapshot fetch brings the complete head ancestry, including merge sides.
6761
- // A parent may have advanced independently and need its own fetch.
6762
- const parent = await exec(['git', 'cat-file', '-e', `${exact.parentSha}^{commit}`], {
6763
- cwd: path,
6764
- })
6765
- if (parent.exitCode !== 0) {
6766
- const fetched = await exec(['git', 'fetch', '--no-tags', 'origin', exact.parentSha], {
6767
- cwd: path,
6768
- })
6769
- if (fetched.exitCode !== 0)
6770
- throw new Error(`cannot fetch node verification parent: ${fetched.stderr}`)
6771
- }
6772
7373
  context = await prepareNodeVerificationContext(
6773
7374
  this.store,
6774
7375
  record.repo,
@@ -6779,9 +7380,21 @@ export class Dispatcher {
6779
7380
  }
6780
7381
  })
6781
7382
  if (!(await this.store.renewNodeWriter(record.slug, holder))) return
7383
+ let expectedSeq = current.lastSeq
7384
+ if (headPaths !== undefined) {
7385
+ const { artifacts, makeEvent } = headPathsWrite(headPaths, 'integration', DISPATCHER)
7386
+ const recorded = await this.store.appendWithArtifactsIfCurrent(
7387
+ record.slug,
7388
+ expectedSeq,
7389
+ artifacts,
7390
+ makeEvent,
7391
+ )
7392
+ if (!recorded) return
7393
+ expectedSeq = recorded.event.seq
7394
+ }
6782
7395
  const prepared = await this.store.appendWithArtifactsIfCurrent(
6783
7396
  record.slug,
6784
- current.lastSeq,
7397
+ expectedSeq,
6785
7398
  context === undefined ? [] : [{ kind: NODE_VERIFICATION_CONTEXT, content: context }],
6786
7399
  (deposited) => ({
6787
7400
  actor: DISPATCHER,
@@ -6790,7 +7403,12 @@ export class Dispatcher {
6790
7403
  ...cycle,
6791
7404
  config: integrationConfig(config),
6792
7405
  ...(deposited[0]
6793
- ? { context: { kind: NODE_VERIFICATION_CONTEXT, rev: deposited[0].revision } }
7406
+ ? {
7407
+ context: {
7408
+ kind: NODE_VERIFICATION_CONTEXT,
7409
+ rev: deposited[0].revision,
7410
+ },
7411
+ }
6794
7412
  : {}),
6795
7413
  },
6796
7414
  }),
@@ -6902,7 +7520,11 @@ export class Dispatcher {
6902
7520
  return
6903
7521
  throw error
6904
7522
  }
6905
- await this.store.append(record.slug, { actor: DISPATCHER, type: 'pr.opened', payload: { pr } })
7523
+ await this.store.append(record.slug, {
7524
+ actor: DISPATCHER,
7525
+ type: 'pr.opened',
7526
+ payload: { pr },
7527
+ })
6906
7528
  }
6907
7529
 
6908
7530
  /** Recover manifests after merge-observation crashes as well as before
@@ -6930,7 +7552,10 @@ export class Dispatcher {
6930
7552
  try {
6931
7553
  await this.withKernelRepository(async (path) => {
6932
7554
  const forge = this.kernelForge()
6933
- const git = { exec: forge.kernelExec ?? this.deps.exec, workspacePath: path }
7555
+ const git = {
7556
+ exec: forge.kernelExec ?? this.deps.exec,
7557
+ workspacePath: path,
7558
+ }
6934
7559
  const visiting = new Set<string>()
6935
7560
  const recover = async (slug: string): Promise<void> => {
6936
7561
  if (visiting.has(slug)) throw new Error('cyclic node contribution evidence')
@@ -7003,7 +7628,11 @@ export class Dispatcher {
7003
7628
  state.nodeRestack ??= { items: [] }
7004
7629
  state.nodeRestack.contribution = payload
7005
7630
  entry.digest.nodeContribution = payload
7006
- inputs.landings.push({ slug, sha: landing, contribution: identities })
7631
+ inputs.landings.push({
7632
+ slug,
7633
+ sha: landing,
7634
+ contribution: identities,
7635
+ })
7007
7636
  visiting.delete(slug)
7008
7637
  }
7009
7638
  for (const entry of pending) {
@@ -7143,11 +7772,17 @@ export class Dispatcher {
7143
7772
  private async presenceVerdict(
7144
7773
  ticket: Ticket,
7145
7774
  target:
7146
- | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
7775
+ | {
7776
+ target: NonNullable<EventPayload<'build.created'>['target']>
7777
+ branch: string
7778
+ }
7147
7779
  | undefined,
7148
7780
  nodes: Map<string, DependencyNode>,
7149
7781
  inputs: PresenceInputs,
7150
- demands: { slug: string; request: EventPayload<'node.restack-requested'> }[],
7782
+ demands: {
7783
+ slug: string
7784
+ request: EventPayload<'node.restack-requested'>
7785
+ }[],
7151
7786
  observations: Map<string, PresenceObservation>,
7152
7787
  ): Promise<DependencyVerdict> {
7153
7788
  const branch = target?.branch ?? this.deps.config.baseBranch
@@ -7224,9 +7859,12 @@ export class Dispatcher {
7224
7859
  ),
7225
7860
  ]
7226
7861
  if (target && missing.length) {
7227
- const path: { slug?: string; identities: string[]; branch: string; head: string }[] = [
7228
- { slug: target.target.build, ...observed },
7229
- ]
7862
+ const path: {
7863
+ slug?: string
7864
+ identities: string[]
7865
+ branch: string
7866
+ head: string
7867
+ }[] = [{ slug: target.target.build, ...observed }]
7230
7868
  const seen = new Set<string>()
7231
7869
  let slug: string | undefined = target.target.build
7232
7870
  while (slug) {
@@ -7443,7 +8081,11 @@ export class Dispatcher {
7443
8081
  } catch {
7444
8082
  return pending
7445
8083
  }
7446
- this.foreignBranchCache.set(target, { fingerprint, branch, scan: scan.generation })
8084
+ this.foreignBranchCache.set(target, {
8085
+ fingerprint,
8086
+ branch,
8087
+ scan: scan.generation,
8088
+ })
7447
8089
  }
7448
8090
  return branch === null
7449
8091
  ? pending