@defrex/autobuild 1.4.1 → 1.5.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 (201) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +440 -95
  3. package/bin/ab-dispatch-kernel.ts +1 -0
  4. package/docs/accounts.md +9 -0
  5. package/docs/agent-runtimes.md +1 -0
  6. package/docs/answering-blocked-builds.md +2 -1
  7. package/docs/architecture.md +290 -130
  8. package/docs/assets/headline-wide.png +0 -0
  9. package/docs/build-store.md +33 -3
  10. package/docs/cli.md +2 -1
  11. package/docs/configuration-overview.md +9 -0
  12. package/docs/configuration.md +166 -101
  13. package/docs/dispatcher-hosting.md +19 -3
  14. package/docs/dispatcher.md +9 -4
  15. package/docs/integration-overview.md +2 -2
  16. package/docs/integration-tree.md +91 -28
  17. package/docs/merge-policy.md +28 -9
  18. package/docs/operator-api.md +43 -18
  19. package/docs/operator-surfaces.md +1 -1
  20. package/docs/plugin-authoring.md +85 -8
  21. package/docs/remote-store-protocol.md +25 -7
  22. package/docs/remote-ticket-protocol.md +126 -12
  23. package/docs/restacking.md +20 -6
  24. package/docs/seams.md +2 -2
  25. package/docs/setup.md +19 -13
  26. package/docs/spec-standard.md +2 -1
  27. package/docs/ticket-dependencies.md +26 -8
  28. package/docs/ticket-migration.md +70 -7
  29. package/docs/ticket-sources.md +82 -5
  30. package/docs/tickets.md +34 -2
  31. package/docs/troubleshooting.md +2 -2
  32. package/docs/verification.md +5 -5
  33. package/docs/website.md +8 -0
  34. package/docs/workspaces.md +1 -1
  35. package/package.json +5 -4
  36. package/packages/core/src/accounts/hosted-readiness.ts +21 -0
  37. package/packages/core/src/cli/attention.ts +1 -0
  38. package/packages/core/src/cli/build-control.ts +36 -12
  39. package/packages/core/src/cli/connect.ts +9 -18
  40. package/packages/core/src/cli/context.ts +44 -0
  41. package/packages/core/src/cli/dashboard/configuration.ts +11 -0
  42. package/packages/core/src/cli/dashboard/model.ts +40 -10
  43. package/packages/core/src/cli/dashboard/queue.ts +21 -0
  44. package/packages/core/src/cli/dashboard/render.ts +40 -22
  45. package/packages/core/src/cli/dispatch-frontend.ts +63 -30
  46. package/packages/core/src/cli/dispatch-mode.ts +35 -16
  47. package/packages/core/src/cli/dispatch-repository-feed.ts +40 -11
  48. package/packages/core/src/cli/dispatch.ts +154 -47
  49. package/packages/core/src/cli/help.ts +59 -22
  50. package/packages/core/src/cli/init-hosted-accounts.ts +54 -0
  51. package/packages/core/src/cli/init-readiness-remote.ts +16 -3
  52. package/packages/core/src/cli/init-validation.ts +144 -42
  53. package/packages/core/src/cli/issue-links.ts +67 -0
  54. package/packages/core/src/cli/main.ts +32 -15
  55. package/packages/core/src/cli/pr-summary-publication.ts +38 -7
  56. package/packages/core/src/cli/publication-settlement.ts +36 -24
  57. package/packages/core/src/cli/repository-status.ts +201 -49
  58. package/packages/core/src/cli/status.ts +41 -3
  59. package/packages/core/src/cli/terminals.ts +37 -2
  60. package/packages/core/src/cli/ticket-editor.ts +20 -6
  61. package/packages/core/src/cli/ticket.ts +264 -46
  62. package/packages/core/src/cli/triage-count-sampler.ts +59 -0
  63. package/packages/core/src/cli/watch.ts +4 -0
  64. package/packages/core/src/config/live.ts +45 -4
  65. package/packages/core/src/config/load.ts +9 -0
  66. package/packages/core/src/config/pipeline-source.ts +6 -2
  67. package/packages/core/src/config/ready-assignee.ts +86 -0
  68. package/packages/core/src/config/schema.ts +164 -36
  69. package/packages/core/src/distribution-packaging.ts +1 -1
  70. package/packages/core/src/events/catalog.ts +5 -0
  71. package/packages/core/src/events/compatibility.ts +2 -1
  72. package/packages/core/src/events/payloads.ts +70 -0
  73. package/packages/core/src/events/policy.ts +8 -0
  74. package/packages/core/src/events/repository.ts +91 -28
  75. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +41 -0
  76. package/packages/core/src/kernel/build-identity.ts +12 -0
  77. package/packages/core/src/kernel/change-presence.ts +139 -6
  78. package/packages/core/src/kernel/dispatch-capacity.ts +80 -14
  79. package/packages/core/src/kernel/dispatch-status.ts +10 -1
  80. package/packages/core/src/kernel/dispatch-upgrade.ts +104 -5
  81. package/packages/core/src/kernel/engine.ts +4 -2
  82. package/packages/core/src/kernel/finalize-pr-rejection.ts +95 -0
  83. package/packages/core/src/kernel/generators/repository-journals.ts +15 -1
  84. package/packages/core/src/kernel/harvest.ts +4 -1
  85. package/packages/core/src/kernel/integration-completeness.ts +104 -17
  86. package/packages/core/src/kernel/integration-landing.ts +17 -0
  87. package/packages/core/src/kernel/integration-state.ts +17 -0
  88. package/packages/core/src/kernel/issue-keywords.ts +202 -0
  89. package/packages/core/src/kernel/janitor-failure.ts +11 -0
  90. package/packages/core/src/kernel/kernel-git.ts +87 -0
  91. package/packages/core/src/kernel/landing-readiness.ts +25 -17
  92. package/packages/core/src/kernel/log-index.ts +1 -1
  93. package/packages/core/src/kernel/node-issue-links.ts +142 -0
  94. package/packages/core/src/kernel/node-parent.ts +6 -0
  95. package/packages/core/src/kernel/node-restack-transaction.ts +2 -0
  96. package/packages/core/src/kernel/pr-summary.ts +24 -0
  97. package/packages/core/src/kernel/read-deferrals.ts +75 -12
  98. package/packages/core/src/kernel/read-facts.ts +32 -1
  99. package/packages/core/src/kernel/reconcile-restack.ts +1 -1
  100. package/packages/core/src/kernel/reducer-registry.ts +31 -1
  101. package/packages/core/src/kernel/reducer.ts +90 -2
  102. package/packages/core/src/kernel/ticket-preparation.ts +12 -0
  103. package/packages/core/src/kernel/verify-budget.ts +43 -0
  104. package/packages/core/src/operator/index.ts +3 -1
  105. package/packages/core/src/operator/presentation.ts +3 -0
  106. package/packages/core/src/operator/protocol.ts +38 -2
  107. package/packages/core/src/operator/query.ts +66 -29
  108. package/packages/core/src/operator/registry.ts +47 -26
  109. package/packages/core/src/operator/tickets.ts +77 -10
  110. package/packages/core/src/plugin-sdk/index.ts +13 -0
  111. package/packages/core/src/plugins/manifest.ts +1 -1
  112. package/packages/core/src/plugins/registry.ts +1 -0
  113. package/packages/core/src/ports/forge/contract.ts +69 -0
  114. package/packages/core/src/ports/forge/create.ts +5 -0
  115. package/packages/core/src/ports/forge/fake.ts +184 -3
  116. package/packages/core/src/ports/forge/git-rewrite.ts +4 -2
  117. package/packages/core/src/ports/forge/github.ts +175 -38
  118. package/packages/core/src/ports/forge/local-git.ts +14 -0
  119. package/packages/core/src/ports/forge/readiness.ts +10 -0
  120. package/packages/core/src/ports/forge-failure.ts +43 -0
  121. package/packages/core/src/ports/runner/claude.ts +7 -1
  122. package/packages/core/src/ports/runner/codex.ts +7 -2
  123. package/packages/core/src/ports/runner/native-cli-fixture.ts +2 -1
  124. package/packages/core/src/ports/runner/pi.ts +7 -1
  125. package/packages/core/src/ports/runner/runtime.ts +3 -0
  126. package/packages/core/src/ports/runner/start-prompt.ts +37 -0
  127. package/packages/core/src/ports/tickets/contract.ts +320 -7
  128. package/packages/core/src/ports/tickets/create.ts +72 -17
  129. package/packages/core/src/ports/tickets/fake.ts +18 -0
  130. package/packages/core/src/ports/tickets/file-codec.ts +20 -0
  131. package/packages/core/src/ports/tickets/file.ts +43 -1
  132. package/packages/core/src/ports/tickets/github-fake.ts +1123 -0
  133. package/packages/core/src/ports/tickets/github-issues.ts +431 -0
  134. package/packages/core/src/ports/tickets/github-validators.ts +194 -0
  135. package/packages/core/src/ports/tickets/github.ts +2029 -0
  136. package/packages/core/src/ports/tickets/hosted-index.ts +34 -3
  137. package/packages/core/src/ports/tickets/issue-links.ts +86 -0
  138. package/packages/core/src/ports/tickets/lifecycle.ts +60 -4
  139. package/packages/core/src/ports/tickets/linear.ts +66 -6
  140. package/packages/core/src/ports/tickets/migration.ts +290 -68
  141. package/packages/core/src/ports/tickets/operations.ts +98 -12
  142. package/packages/core/src/ports/tickets/priority.ts +55 -0
  143. package/packages/core/src/ports/tickets/remote-protocol.ts +195 -29
  144. package/packages/core/src/ports/tickets/remote.ts +188 -13
  145. package/packages/core/src/ports/tickets/revision.ts +22 -1
  146. package/packages/core/src/ports/tickets/states.ts +43 -0
  147. package/packages/core/src/ports/tickets/tree.ts +58 -12
  148. package/packages/core/src/ports/tickets/update.ts +12 -2
  149. package/packages/core/src/ports/types.ts +194 -11
  150. package/packages/core/src/ports/workspace/commit-preservation.ts +135 -13
  151. package/packages/core/src/ports/workspace/git-worktree.ts +3 -1
  152. package/packages/core/src/ports/workspace/vercel-sandbox.ts +132 -27
  153. package/packages/core/src/processes/build-runner.ts +99 -21
  154. package/packages/core/src/processes/dispatcher.ts +1080 -533
  155. package/packages/core/src/processes/execution-no-progress.ts +5 -0
  156. package/packages/core/src/processes/harvest-runner.ts +17 -8
  157. package/packages/core/src/processes/harvest.ts +5 -8
  158. package/packages/core/src/processes/tick-publication.ts +12 -2
  159. package/packages/core/src/processes/ticket-scan-schedule.ts +78 -0
  160. package/packages/core/src/processes/workspace-preservation.ts +37 -2
  161. package/packages/core/src/runtime-identity.ts +10 -2
  162. package/packages/core/src/scenarios/harness.ts +4 -0
  163. package/packages/core/src/store/adapter.ts +7 -1
  164. package/packages/core/src/store/contract.ts +83 -2
  165. package/packages/core/src/store/digest.ts +32 -1
  166. package/packages/core/src/store/reducer-value-shapes.json +4187 -3391
  167. package/packages/core/src/store/remote/protocol.ts +2 -0
  168. package/packages/core/src/store/remote/released-clients.json +22 -0
  169. package/packages/core/src/store/remote/released-reducer-values/1.5.0.json +26924 -0
  170. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  171. package/packages/core/src/store/repo-state-events.ts +2 -0
  172. package/packages/core/src/store/types.ts +5 -0
  173. package/packages/core/src/testing/dispatch-read-budget.ts +729 -123
  174. package/packages/core/src/testing/index.ts +18 -1
  175. package/packages/core/src/testing/presence-history.ts +79 -0
  176. package/packages/core/src/testing/reduced-read-budget.ts +1197 -31
  177. package/packages/core/src/testing/upgrade-generations.ts +77 -0
  178. package/skills/code-review/SKILL.md +4 -3
  179. package/skills/finalize/SKILL.md +18 -2
  180. package/skills/guide/SKILL.md +382 -139
  181. package/skills/guide/references/accounts.md +9 -0
  182. package/skills/guide/references/integration-tree.md +91 -28
  183. package/skills/guide/references/merge-policy.md +28 -9
  184. package/skills/guide/references/operator-api.md +43 -18
  185. package/skills/guide/references/plugin-authoring.md +85 -8
  186. package/skills/guide/references/remote-store-protocol.md +25 -7
  187. package/skills/guide/references/remote-ticket-protocol.md +126 -12
  188. package/skills/guide/references/restacking.md +20 -6
  189. package/skills/guide/references/setup.md +19 -13
  190. package/skills/guide/references/spec-standard.md +2 -1
  191. package/skills/guide/references/ticket-dependencies.md +26 -8
  192. package/skills/guide/references/ticket-migration.md +70 -7
  193. package/skills/harvest-review/SKILL.md +4 -3
  194. package/skills/implement/SKILL.md +20 -1
  195. package/skills/operate/SKILL.md +103 -28
  196. package/skills/plan/SKILL.md +1 -1
  197. package/skills/reconcile/SKILL.md +5 -4
  198. package/skills/spec/SKILL.md +15 -2
  199. package/skills/tickets/SKILL.md +114 -37
  200. package/templates/autobuild.toml +5 -0
  201. package/templates/hosted-service/package.json +2 -2
@@ -7,10 +7,14 @@ import {
7
7
  type MissingAccountCredential,
8
8
  } from '../accounts/availability'
9
9
 
10
- import { WorkspaceFenceUnknown, preserveWorkspaceBeforeRelease } from './workspace-preservation'
10
+ import { preserveWorkspaceBeforeRelease, supersedeRestorationHeads } from './workspace-preservation'
11
11
  import { WorkspaceCleanupRequired } from '../ports/types'
12
+ import type { OpenHarvestExecution } from './harvest-execution-state'
12
13
  import { ArtifactMetaUnsupportedError } from '../store/artifact-meta'
13
- import type { TicketPreparation } from '../kernel/ticket-preparation'
14
+ import {
15
+ abandonedPreparationDiagnostic,
16
+ type TicketPreparation,
17
+ } from '../kernel/ticket-preparation'
14
18
  import { sampleTargetDistance } from '../kernel/target-distance'
15
19
  import { capturedBuildConfig } from './verify-cycle-config'
16
20
  import { publicationRetryGate } from '../kernel/publication-retry'
@@ -27,6 +31,7 @@ import {
27
31
  nodeTicketObservationKey,
28
32
  } from '../kernel/node-polling'
29
33
  import { reportIntegrationFailures } from '../kernel/integration-attention'
34
+ import { ticketScanDeferredByJournal, ticketScanSchedule } from './ticket-scan-schedule'
30
35
  import {
31
36
  resolveTicketRef,
32
37
  migrationIdentity,
@@ -45,14 +50,21 @@ import {
45
50
  MixedVersionDeferral,
46
51
  } from '../kernel/mixed-version'
47
52
  import { guardForge, ForgeCooldown } from '../kernel/guarded-forge'
48
- import { recordJanitorFailure } from '../kernel/janitor-failure'
53
+ import { janitorDeferral, recordJanitorFailure } from '../kernel/janitor-failure'
54
+ import { KernelGitUnavailable, kernelGitUnavailableDetail } from '../kernel/kernel-git'
49
55
  import { isForgeFailure } from '../ports/forge-failure'
50
56
  import {
51
57
  ForgeRequestDeferred,
52
58
  withForgeRequestContext,
53
59
  forgeRequestContext,
54
60
  } from '../ports/forge-request-context'
55
- import { dispatchCapacity, nodeCapacity, type CapacityBuild } from '../kernel/dispatch-capacity'
61
+ import {
62
+ dispatchCapacity,
63
+ intakeCapacity,
64
+ nodeCapacity,
65
+ slotRequest,
66
+ type CapacityBuild,
67
+ } from '../kernel/dispatch-capacity'
56
68
  import { evaluateLandingPolicy } from '../kernel/landing-policy'
57
69
  import {
58
70
  landingAuthorized,
@@ -74,6 +86,7 @@ import {
74
86
  integrationFailed,
75
87
  integrationVerified,
76
88
  integrationHeadVerified,
89
+ integrationAdmissible,
77
90
  } from '../kernel/integration-state'
78
91
  import {
79
92
  normalizeIdentities,
@@ -82,12 +95,16 @@ import {
82
95
  presenceInputs,
83
96
  confirmedLandings,
84
97
  presenceWitness,
85
- projectPresence,
86
- presenceEvidence,
98
+ answers,
99
+ compactProbe,
100
+ projectProbe,
101
+ probeEvidence,
87
102
  destinationAliases,
88
103
  ownedContribution,
89
104
  type ChangeIdentity,
90
105
  type PresenceInputs,
106
+ type PresenceProbe,
107
+ type PresenceWitness,
91
108
  } from '../kernel/change-presence'
92
109
  import { landIntoNode, settleClosedNode, preflightNodeLanding } from '../kernel/node-landing'
93
110
  import { mkdtemp, rm } from 'node:fs/promises'
@@ -95,11 +112,13 @@ import { tmpdir } from 'node:os'
95
112
  import { join } from 'node:path'
96
113
  import { runNodeTransaction } from '../kernel/node-restack-transaction'
97
114
  import { hasBuildTrailer } from '../kernel/build-identity'
115
+ import { digestNodeTargets } from '../store/digest'
98
116
  import { readBuildDigests, readForgeHealth } from '../store/reduced-reads'
99
117
  import { readBuildSelector, readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
100
118
  import { ensureExecutionProgress } from './execution-no-progress'
101
119
  import { ticketIdentity } from '../ports/tickets/identity'
102
- import { ticketLifecycle } from '../ports/tickets/lifecycle'
120
+ import { holdsState, ticketLifecycle } from '../ports/tickets/lifecycle'
121
+ import { urgentFirst } from '../ports/tickets/priority'
103
122
  import { ensureDispatchBudget } from './dispatch-failure-budget'
104
123
  import type { TicketSourceDegradation } from '../kernel/ticket-source-health'
105
124
  /**
@@ -163,13 +182,20 @@ import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution
163
182
  import type {
164
183
  DependencyState,
165
184
  Forge,
185
+ IssueLink,
166
186
  Ticket,
167
187
  TicketSource,
168
188
  WorkspaceProvider,
169
189
  WorkspaceProvisionResult,
170
190
  } from '../ports/types'
171
191
  import { NoCommitsBetweenBranchesError, TicketSourceRateLimitError } from '../ports/types'
172
- import type { Exec } from '../ports/workspace/git-worktree'
192
+ import { issueLinksForForge } from '../kernel/issue-keywords'
193
+ import {
194
+ contributedIssueLinks,
195
+ nodeIssueLinksForForge,
196
+ nodeIssueLinksSyncPending,
197
+ } from '../kernel/node-issue-links'
198
+ import type { Exec, ExecResult } from '../ports/workspace/git-worktree'
173
199
  import type { ArtifactMeta, BuildDigest, BuildRecord, BuildStore, Clock } from '../store/types'
174
200
  import { preparePinnedAssets } from '../store/ticket-assets'
175
201
  import { resolveRepoOrigin } from '../cli/repo-state'
@@ -196,13 +222,15 @@ import { settlePublicationFactsBeforeRelease } from './publication-loss'
196
222
  *
197
223
  * The only per-source difference left is the *label* default. Linear has no
198
224
  * `ready/` directory, so a label is the only thing that can mark a ticket
199
- * dispatchable: the historical `["autobuild"]` default. The file tracker's gate
225
+ * dispatchable: the historical `["autobuild"]` default. GitHub shares it, so
226
+ * an issue anyone can file still needs the opt-in label. The file tracker's gate
200
227
  * is otherwise the directory, so it defaults to no label gate. Plugin sources
201
228
  * likewise receive no host-imposed label convention. An explicit
202
229
  * `readyLabels` wins for every source.
203
230
  *
204
- * `[tickets].readyAssignee` (Linear only) adds a third conjunctive gate: the
205
- * ticket must be assigned to that user.
231
+ * `[tickets].readyAssignee` adds a third conjunctive gate for any source: the
232
+ * ticket must be assigned to that user. Only sources declaring the capability
233
+ * get this far (`config/ready-assignee.ts`).
206
234
  */
207
235
  export function readyCriteria(config: Config): {
208
236
  labels: string[]
@@ -210,14 +238,12 @@ export function readyCriteria(config: Config): {
210
238
  assignee?: string
211
239
  } {
212
240
  const { readyLabels, readyState, readyAssignee } = config.tickets
213
- if (config.tickets.source === 'linear') {
214
- return {
215
- labels: readyLabels ?? ['autobuild'],
216
- state: readyState,
217
- ...(readyAssignee !== undefined ? { assignee: readyAssignee } : {}),
218
- }
241
+ const source = config.tickets.source
242
+ return {
243
+ labels: readyLabels ?? (source === 'github' || source === 'linear' ? ['autobuild'] : []),
244
+ state: readyState,
245
+ ...(readyAssignee !== undefined ? { assignee: readyAssignee } : {}),
219
246
  }
220
- return { labels: readyLabels ?? [], state: readyState }
221
247
  }
222
248
 
223
249
  /**
@@ -260,6 +286,33 @@ export function defaultProposalState(config: Config): string {
260
286
  // decision here means one tested implementation instead of one per adapter,
261
287
  // and no adapter's state taxonomy leaks upward.
262
288
 
289
+ /** A cached dependency fact with the configured rejected role applied. */
290
+ export type DependencyNode = DependencyState & { rejected?: boolean }
291
+
292
+ /**
293
+ * Apply the configured rejected role over the source's native completion
294
+ * fact: a blocker in the rejected state never resolves, even where the
295
+ * source natively counts it complete (Linear's canceled). An unset role
296
+ * changes nothing. Moving the ticket out of the state restores ordinary
297
+ * gating, because every scan reads the current state afresh.
298
+ */
299
+ export function markRejected(node: DependencyState, rejectedState?: string): DependencyNode {
300
+ return node.exists && holdsState(node.state, rejectedState)
301
+ ? { ...node, resolved: false, rejected: true }
302
+ : node
303
+ }
304
+
305
+ /** One destination's in-tick presence answers and the probe behind them. */
306
+ interface PresenceObservation {
307
+ branch: string
308
+ destination: string
309
+ head: string
310
+ identities: ChangeIdentity[]
311
+ probe: PresenceProbe
312
+ /** Questions asked this tick. A reused durable probe may cover more, but
313
+ * only these seed a re-compaction, so questions never accumulate across ticks. */
314
+ asked: ChangeIdentity[]
315
+ }
263
316
  export interface DependencyVerdict {
264
317
  /** Unresolved blocker ids — nonempty means DO NOT dispatch. */
265
318
  unresolved: string[]
@@ -278,7 +331,7 @@ export interface DependencyVerdict {
278
331
  function findCycle(
279
332
  from: string,
280
333
  path: string[],
281
- nodes: Map<string, DependencyState>,
334
+ nodes: Map<string, DependencyNode>,
282
335
  explored: Set<string>,
283
336
  ): string[] | null {
284
337
  const node = nodes.get(from)
@@ -313,7 +366,7 @@ function findCycle(
313
366
  export function analyzeDependencies(
314
367
  ticketId: string,
315
368
  blockedBy: string[],
316
- nodes: Map<string, DependencyState>,
369
+ nodes: Map<string, DependencyNode>,
317
370
  ): DependencyVerdict {
318
371
  const unresolved: string[] = []
319
372
  const diagnostics: string[] = []
@@ -333,6 +386,11 @@ export function analyzeDependencies(
333
386
  )
334
387
  continue
335
388
  }
389
+ if (node.rejected) {
390
+ unresolved.push(blockerId)
391
+ diagnostics.push(`ticket ${ticketId} blocked by ${blockerId}, which was rejected`)
392
+ continue
393
+ }
336
394
  // A resolved blocker imposes nothing, and its own history is irrelevant —
337
395
  // never walked, so a cycle *behind* completed work is not a diagnostic.
338
396
  if (node.resolved) continue
@@ -399,7 +457,8 @@ export interface TickReport {
399
457
  discarded: number
400
458
  /** Contained build janitor and ticket-preparation recovery failures this pass. */
401
459
  janitorFailed: number
402
- /** One actionable line per contained failure, attributed by build or attempt. */
460
+ /** One actionable line per contained failure or abandoned ticket preparation,
461
+ * attributed by build, ticket or attempt. */
403
462
  janitorDiagnostics: string[]
404
463
  /** Ordinary-tick recovery completed an interrupted post-creation dispatch. */
405
464
  recovered: number
@@ -506,6 +565,12 @@ export function emptyTickReport(): TickReport {
506
565
  // ── Dispatcher ───────────────────────────────────────────────────────────────
507
566
 
508
567
  const DEFAULT_SLUG_NAMING_TIMEOUT_MS = 10_000
568
+ /** Bound on -2/-3/… candidates one claim may probe for a free slug. */
569
+ const MAX_SLUG_CANDIDATES = 100
570
+ /** Body of the comment dispatch posts on every claimed ticket. The
571
+ * foreign-target diagnostic parses it to find another store's node branch. */
572
+ const dispatchCommentBody = (slug: string) => `build ${slug} dispatched`
573
+ const DISPATCH_COMMENT = /^build ([a-z0-9][a-z0-9-]*) dispatched$/
509
574
  /** Heartbeat cadence of a background provisioning continuation's execution
510
575
  * lease. A dead provisioner is therefore adopted within one lease TTL. */
511
576
  const PROVISION_HEARTBEAT_MS = 15_000
@@ -519,6 +584,14 @@ export type DispatchOutcome = 'completed' | 'deferred' | 'parked' | 'failed'
519
584
  /** One tracked background provisioning continuation (process-local). Its
520
585
  * durable residue is the `workspace.provision-started` marker plus the
521
586
  * execution lease it claims and heartbeats. */
587
+ /** Per-admission-scan inputs for target-node resolution: the ready listing's
588
+ * ids and the memoized foreign-target verdicts, one per distinct target. */
589
+ interface TargetScan {
590
+ listed: ReadonlySet<string>
591
+ foreign: Map<string, Promise<string>>
592
+ generation: number
593
+ }
594
+
522
595
  interface ProvisionContinuation {
523
596
  readonly slug: string
524
597
  readonly instance: string
@@ -654,11 +727,14 @@ export interface DispatcherDeps {
654
727
  authorSpec?: (ticket: Ticket) => Promise<string | null>
655
728
  /** Start the repository-scoped observation workflow without awaiting it.
656
729
  * The owner must single-flight and track the promise; Dispatcher invokes
657
- * this after ready-ticket dispatch, independent of drain/build capacity. */
730
+ * this after ready-ticket dispatch, independent of drain/build capacity.
731
+ * Withheld while a foreign, provider-observable hosted-harvest execution is
732
+ * still open: its guest owns the run's open session. */
658
733
  startHarvest?: () => void
659
734
  /** Optional one-shot judgment over the final conforming spec. The dispatcher
660
735
  * supplies cancellation and treats every absence/failure/invalid result as a
661
- * local deterministic fallback, so naming can never prevent build creation. */
736
+ * local deterministic fallback, so a failed proposal never prevents build
737
+ * creation. Slug deduplication (`uniqueSlug`) can still fail the claim. */
662
738
  nameSlug?: (spec: string, signal: AbortSignal) => Promise<string | null>
663
739
  /** Settle pending publication for `slug` after durable proof that the
664
740
  * guest execution ended. Supplied by the DispatchLoop; the settlement stage
@@ -683,6 +759,12 @@ function openWorkspace(events: CurrentBuildFacts): OpenBuildWorkspace | null {
683
759
  return events.workspace
684
760
  }
685
761
 
762
+ /** The open workspace is the one a provider flagged `cleanup-required`: it
763
+ * must be reaped and replaced, never launched into. */
764
+ function cleanupRequiredWorkspace(events: CurrentBuildFacts): boolean {
765
+ return events.workspace !== null && events.latestWorkspace?.type === 'workspace.cleanup-required'
766
+ }
767
+
686
768
  /** The build's base branch, from its own `build.created` fact (§15.3);
687
769
  * falls back to the repo config for logs missing one. */
688
770
  function baseBranchOf(events: CurrentBuildFacts, config: Config): string {
@@ -747,6 +829,21 @@ export class Dispatcher {
747
829
  }
748
830
  >()
749
831
  private readonly nodePollingTickReads = new Map<string, Promise<BuildState>>()
832
+ /** Per-process cache of the foreign-target branch-arm lookup (AUT-1106),
833
+ * keyed by target ticket id and invalidated by the target ticket's revision
834
+ * and foreign dispatch-comment slugs. `scan` is the admission scan that last
835
+ * consulted the entry; entries older than the previous scan are dropped. */
836
+ private readonly foreignBranchCache = new Map<
837
+ string,
838
+ { fingerprint: string; branch: string | null; scan: number }
839
+ >()
840
+ private foreignScanGeneration = 0
841
+ /** Last full in-memory witness per sampled destination, replaced on head
842
+ * moves, so a long-running dispatcher walks Git at most once per head. */
843
+ private readonly presenceWitnesses = new Map<
844
+ string,
845
+ { branch: string; head: string; witness: PresenceWitness }
846
+ >()
750
847
 
751
848
  private async integrationClaimKey(slug: string, state: BuildState): Promise<string> {
752
849
  return nodeTicketObservationKey(state, await this.nodePollingChildren(slug))
@@ -755,6 +852,9 @@ export class Dispatcher {
755
852
  const children: { slug: string; state: Pick<BuildState, 'pollingActivity'> }[] = []
756
853
  for (const { record, digest } of await this.repoBuildDigests()) {
757
854
  if (record.slug === slug) continue
855
+ // The digest names every node a build ever targeted, so a build it does
856
+ // not name can never be this node's child and needs no facts read.
857
+ if (!digestNodeTargets(digest).includes(slug)) continue
758
858
  const known = this.nodePollingBuilds.get(record.slug)
759
859
  // Only node relationships can move. Unrelated known work never needs
760
860
  // another full-facts read, even while it is running.
@@ -792,22 +892,29 @@ export class Dispatcher {
792
892
  }
793
893
 
794
894
  private observeIntegration(slug: string, publication = false) {
795
- return observeIntegration(this.store, this.deps.tickets, slug, () => {
796
- if (publication) {
797
- this.integrationPublicationInputs ??= integrationObservationInputs(
895
+ const rejectedState = this.rejectedState()
896
+ return observeIntegration(
897
+ this.store,
898
+ this.deps.tickets,
899
+ slug,
900
+ () => {
901
+ if (publication) {
902
+ this.integrationPublicationInputs ??= integrationObservationInputs(
903
+ this.store,
904
+ this.deps.tickets,
905
+ this.deps.repo,
906
+ )
907
+ return this.integrationPublicationInputs
908
+ }
909
+ this.integrationInputs ??= integrationObservationInputs(
798
910
  this.store,
799
911
  this.deps.tickets,
800
912
  this.deps.repo,
801
913
  )
802
- return this.integrationPublicationInputs
803
- }
804
- this.integrationInputs ??= integrationObservationInputs(
805
- this.store,
806
- this.deps.tickets,
807
- this.deps.repo,
808
- )
809
- return this.integrationInputs
810
- })
914
+ return this.integrationInputs
915
+ },
916
+ rejectedState === undefined ? {} : { rejectedState },
917
+ )
811
918
  }
812
919
 
813
920
  // Disposable parsed pins only. Current facts, live policy and cycle captures
@@ -918,7 +1025,7 @@ export class Dispatcher {
918
1025
  private get doneState(): string {
919
1026
  return (
920
1027
  this.deps.opts?.doneState ??
921
- (this.deps.config.tickets.source === 'hosted'
1028
+ (this.deps.config.tickets.source === 'hosted' || this.deps.config.tickets.source === 'github'
922
1029
  ? ticketLifecycle(this.deps.config.tickets).done
923
1030
  : undefined) ??
924
1031
  'Done'
@@ -932,10 +1039,15 @@ export class Dispatcher {
932
1039
  private readonly continuations = new Map<string, ProvisionContinuation>()
933
1040
 
934
1041
  // Batched confirmed landing evidence is shared across nodes for this tick.
935
- // Only durable availability facts authorize the shortcut after restart.
1042
+ // Only durable availability facts authorize the shortcut after restart. The
1043
+ // batch includes mixed-version deferred builds' durable landing facts so its
1044
+ // fingerprint matches the one the node transaction records.
936
1045
  private availabilityLandings?: ReturnType<typeof confirmedLandings>
937
1046
  private availabilityLandingKey?: string
938
1047
  private availabilityEntries?: ReturnType<Dispatcher['repoBuildDigests']>
1048
+ /** Set once kernel Git proved unable to run this tick; later node work in
1049
+ * the same tick defers on it without spawning again. */
1050
+ private kernelGitUnavailable?: KernelGitUnavailable
939
1051
 
940
1052
  /** The incremental repository view every stage reads and writes through
941
1053
  * (AUT-647): `deps.store` itself when the caller already wrapped it. */
@@ -991,6 +1103,8 @@ export class Dispatcher {
991
1103
 
992
1104
  lastForgeRequests?: import('../ports/forge-telemetry').ForgeRequestCounts
993
1105
  async tick(opts: TickOpts = {}): Promise<TickReport> {
1106
+ this.kernelGitUnavailable = undefined
1107
+ this.tickAbandonments = []
994
1108
  this.availabilityEntries = undefined
995
1109
  this.availabilityLandings = undefined
996
1110
  this.availabilityLandingKey = undefined
@@ -1025,13 +1139,38 @@ export class Dispatcher {
1025
1139
  ? this.deps.forge.withReadScope(() => this.runTick(opts))
1026
1140
  : this.runTick(opts))
1027
1141
  if (stop || this.deps.config.forge === 'local-git') report.forgeRequests = counts()
1142
+ report.janitorDiagnostics.push(...this.tickAbandonments)
1028
1143
  return report
1144
+ } catch (error) {
1145
+ throw this.withTickAbandonments(error)
1029
1146
  } finally {
1147
+ this.tickAbandonments = []
1030
1148
  if (stop || this.deps.config.forge === 'local-git') this.lastForgeRequests = counts()
1031
1149
  stop?.()
1032
1150
  }
1033
1151
  }
1034
1152
 
1153
+ /** Ticket preparations durably abandoned during the current tick. Drained
1154
+ * once by `tick()` into its report or its rejection, so later ticks never
1155
+ * repeat them. At most 8 recoveries plus one inline abandonment per tick. */
1156
+ private tickAbandonments: string[] = []
1157
+
1158
+ /** A failed tick still reports the attempts it abandoned. The rejection
1159
+ * keeps its type: the lines are appended to a writable message in place. */
1160
+ private withTickAbandonments(error: unknown): unknown {
1161
+ if (this.tickAbandonments.length === 0) return error
1162
+ const lines = `abandoned ticket preparations this tick: ${this.tickAbandonments.join('; ')}`
1163
+ if (error instanceof Error) {
1164
+ try {
1165
+ error.message = `${error.message}; ${lines}`
1166
+ return error
1167
+ } catch {
1168
+ // A frozen or non-writable message falls through to a wrapper.
1169
+ }
1170
+ }
1171
+ return new AggregateError([error], `${String(error)}; ${lines}`, { cause: error })
1172
+ }
1173
+
1035
1174
  private async runTick(opts: TickOpts): Promise<TickReport> {
1036
1175
  this.integrationInputs = undefined
1037
1176
  this.integrationPublicationInputs = undefined
@@ -1086,6 +1225,10 @@ export class Dispatcher {
1086
1225
  if (this.outOfBudget(opts)) return report
1087
1226
  await this.leaseSweep(report, launched, paused, opts)
1088
1227
  if (this.outOfBudget(opts)) return report
1228
+ // Nodes with a durable verification request take freed slots before
1229
+ // intake, whether or not idle node polling visited them this tick.
1230
+ await this.admitWaitingNodes(report, launched, opts)
1231
+ if (this.outOfBudget(opts)) return report
1089
1232
  if (opts.acceptNewWork !== false) {
1090
1233
  await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1091
1234
  }
@@ -1106,6 +1249,11 @@ export class Dispatcher {
1106
1249
  return this.deps.opts?.triageState ?? defaultTriageState(this.deps.config)
1107
1250
  }
1108
1251
 
1252
+ /** The configured rejected role's state, read from live config each time. */
1253
+ private rejectedState(): string | undefined {
1254
+ return ticketLifecycle(this.deps.config.tickets).rejected
1255
+ }
1256
+
1109
1257
  /** This repository's builds paired with their digests, from one record
1110
1258
  * listing and one digest read — the tick loops' per-build event reads start
1111
1259
  * from here so a settled terminal build costs none. Records are read before
@@ -1360,34 +1508,21 @@ export class Dispatcher {
1360
1508
  const readinessFingerprint = hash(digest)
1361
1509
  const criteriaFingerprint = hash(readyCriteria(this.deps.config))
1362
1510
  const startedAt = this.deps.clock().toISOString()
1363
- const previous = this.latestScan()
1364
- const cached = await this.store.getScanCadence(this.deps.repo)
1365
- // Outcomes always come from the reduction. This row only acknowledges their cadence.
1366
- const valid =
1367
- previous !== undefined &&
1368
- cached !== null &&
1369
- cached.scanSeq === this.store.repositoryFacts().scanSeq &&
1370
- cached.mode === previous.mode &&
1371
- cached.readinessFingerprint === previous.readinessFingerprint &&
1372
- cached.criteriaFingerprint === previous.criteriaFingerprint &&
1373
- Number.isFinite(Date.parse(cached.startedAt))
1374
- const baseline = valid ? cached : previous
1375
- const elapsed =
1376
- baseline === undefined ? Infinity : Date.parse(startedAt) - Date.parse(baseline.startedAt)
1377
- return {
1378
- startedAt,
1511
+ const input = {
1512
+ previous: this.latestScan(),
1513
+ previousSeq: this.store.repositoryFacts().scanSeq,
1379
1514
  mode,
1380
1515
  readinessFingerprint,
1381
1516
  criteriaFingerprint,
1382
- allowClockRollback: elapsed < 0,
1383
- due:
1384
- previous === undefined ||
1385
- elapsed < 0 ||
1386
- elapsed >= this.deps.config.ticketScanIntervalSeconds * 1000 ||
1387
- previous.readinessFingerprint !== readinessFingerprint ||
1388
- previous.criteriaFingerprint !== criteriaFingerprint ||
1389
- (mode === 'admission' && previous.mode === 'observation'),
1517
+ startedAt,
1518
+ intervalMs: this.deps.config.ticketScanIntervalSeconds * 1000,
1390
1519
  }
1520
+ const checkpoint = { startedAt, mode, readinessFingerprint, criteriaFingerprint }
1521
+ // The journal measurement alone proves deferral, so the cadence row is not read.
1522
+ if (ticketScanDeferredByJournal(input))
1523
+ return { ...checkpoint, allowClockRollback: false, due: false }
1524
+ const cached = await this.store.getScanCadence(this.deps.repo)
1525
+ return { ...checkpoint, ...ticketScanSchedule(input, cached) }
1391
1526
  }
1392
1527
 
1393
1528
  private async completeScan(
@@ -1490,8 +1625,11 @@ export class Dispatcher {
1490
1625
  return
1491
1626
  }
1492
1627
  // Bounded subset (AUT-489): the harvest reducer consumes durable types only.
1493
- const state = this.store.repositoryFacts().harvest
1494
- if (decideHarvestControl(state, this.maxHarvestRecoveryAttempts).kind !== 'park') {
1628
+ const facts = this.store.repositoryFacts()
1629
+ // A live guest owns its open session; launching would judge that session
1630
+ // as runner loss and start a duplicate guest beside it.
1631
+ if (this.liveForeignHarvestExecution(facts.openHarvest)) return
1632
+ if (decideHarvestControl(facts.harvest, this.maxHarvestRecoveryAttempts).kind !== 'park') {
1495
1633
  start()
1496
1634
  }
1497
1635
  }
@@ -1519,10 +1657,25 @@ export class Dispatcher {
1519
1657
  if (launched.has(slug)) return 'already-active'
1520
1658
  launched.add(slug)
1521
1659
  const facts = (await readBuildFacts(this.store, slug)).value
1660
+ // Callers reap and reprovision a flagged workspace; an agent never starts
1661
+ // in an environment a provider flagged `cleanup-required`.
1662
+ if (
1663
+ facts.workspace !== null &&
1664
+ cleanupRequiredWorkspace(facts) &&
1665
+ this.workspaceOwner(facts.workspace)?.recovery !== undefined
1666
+ )
1667
+ return 'already-active'
1522
1668
  if (facts.log.restack.target === undefined && facts.lastCreated !== undefined) {
1523
1669
  const branch = facts.lastCreated.payload.baseBranch
1524
1670
  await this.observeTarget(slug, branch, undefined, report)
1525
1671
  }
1672
+ return this.startRunner(slug, report)
1673
+ }
1674
+
1675
+ /** The one guarded runner start. Every dispatcher path that starts a runner
1676
+ * goes through here, so the no-progress policy cannot depend on which path
1677
+ * runs. */
1678
+ private async startRunner(slug: string, report: TickReport): Promise<LaunchRunnerResult> {
1526
1679
  if (
1527
1680
  !(await ensureExecutionProgress(
1528
1681
  this.store,
@@ -1591,10 +1744,12 @@ export class Dispatcher {
1591
1744
  * owning provider. `lost`/`ended` reaps the disposable environment and
1592
1745
  * journals the close fact with the snapshot purge outcome; `running`
1593
1746
  * leaves it — the guest is the live supervisor and holds the adopted
1594
- * repository lease, and the next pass reaps it after it ends. The run
1595
- * itself needs no settlement here: an interrupted run stays open in the
1596
- * journal and the next threshold-triggered harvest resumes it under the
1597
- * repository lease. */
1747
+ * repository lease, and the next pass reaps it after it ends. Until the
1748
+ * release is journaled, an open observable execution also suppresses
1749
+ * harvest launch (`liveForeignHarvestExecution`). The run itself needs no
1750
+ * settlement here: an interrupted run stays open in the journal, and the
1751
+ * next launch after the release records its interrupted session and
1752
+ * resumes it under the repository lease. */
1598
1753
  private async settleHarvestExecutions(opts: TickOpts = {}): Promise<void> {
1599
1754
  const active = this.deps.activeHarvestExecutions?.() ?? new Set<string>()
1600
1755
  const facts = this.store.repositoryFacts()
@@ -1681,6 +1836,22 @@ export class Dispatcher {
1681
1836
  }
1682
1837
  }
1683
1838
 
1839
+ /** A foreign hosted-harvest execution still open after this tick's
1840
+ * settlement, and observable by its owning provider: the guest is the live
1841
+ * supervisor of its run, so no launch (and so no runner-loss judgment on
1842
+ * its open session) may happen until settlement journals its release. An
1843
+ * unobservable execution never blocks — settlement could never release it. */
1844
+ private liveForeignHarvestExecution(open: readonly OpenHarvestExecution[]): boolean {
1845
+ if (open.length === 0) return false
1846
+ const active = this.deps.activeHarvestExecutions?.() ?? new Set<string>()
1847
+ return open.some(
1848
+ (execution) =>
1849
+ !active.has(execution.execution) &&
1850
+ execution.commandId !== undefined &&
1851
+ this.executionOwner(execution.provider)?.harvestExecution?.observe !== undefined,
1852
+ )
1853
+ }
1854
+
1684
1855
  /** Durable idle settlement for operator sandboxes (AUT-340), staged after
1685
1856
  * harvest settlement: every journal-live environment whose latest evidence
1686
1857
  * is older than `[orchestrator].sandbox.idleMinutes` is stopped through the
@@ -1981,6 +2152,9 @@ export class Dispatcher {
1981
2152
  remote: workspaces.publication !== undefined,
1982
2153
  branch: handle.branch,
1983
2154
  base: handle.base,
2155
+ ...(handle.restorationSkipped?.length
2156
+ ? { restorationSkipped: handle.restorationSkipped }
2157
+ : {}),
1984
2158
  },
1985
2159
  } satisfies EventWrite<'workspace.provisioned'>)
1986
2160
  // Release before the launch: the launcher re-claims the lease under the
@@ -1999,7 +2173,7 @@ export class Dispatcher {
1999
2173
  const queued = (await readBuildFacts(store, slug)).value.state.status === 'queued'
2000
2174
  boundary = input.tail === 'dispatch' || queued ? 'dispatch' : 'launch'
2001
2175
  if (boundary === 'dispatch') await this.completeDispatchBoundaries(record, input.seed)
2002
- else if (this.accountsAvailable()) await this.deps.launchRunner(slug)
2176
+ else if (this.accountsAvailable()) await this.startRunner(slug, emptyTickReport())
2003
2177
  } catch (error) {
2004
2178
  // Dispatch boundaries own their failure facts and exhaustion repair.
2005
2179
  // A failed tail read/write leaves durable unfinished work for the next
@@ -2482,11 +2656,7 @@ export class Dispatcher {
2482
2656
  forge: this.deps.forge,
2483
2657
  })
2484
2658
  } catch (error) {
2485
- if (
2486
- error instanceof ForgeRequestDeferred ||
2487
- (isForgeFailure(error) && error.details.kind === 'rate-limited')
2488
- )
2489
- throw error
2659
+ if (janitorDeferral(error)) throw error
2490
2660
  if (facts.log.restack.distance?.count != null)
2491
2661
  report.janitorDiagnostics.push(
2492
2662
  `build ${record.slug}: target distance failed — ${error instanceof Error ? error.message : String(error)}`,
@@ -2535,7 +2705,10 @@ export class Dispatcher {
2535
2705
  }
2536
2706
  await completeNodePoll()
2537
2707
  } catch (error) {
2538
- if (error instanceof ForgeRequestDeferred) {
2708
+ // The guarded forge already recorded a classified rate limit as repository
2709
+ // degradation; like the cooldown that follows it, it neither starts nor ages
2710
+ // this build's janitor episode.
2711
+ if (janitorDeferral(error)) {
2539
2712
  attempted = false
2540
2713
  return
2541
2714
  }
@@ -2584,11 +2757,7 @@ export class Dispatcher {
2584
2757
  })
2585
2758
  return true
2586
2759
  } catch (error) {
2587
- if (
2588
- error instanceof ForgeRequestDeferred ||
2589
- (isForgeFailure(error) && error.details.kind === 'rate-limited')
2590
- )
2591
- throw error
2760
+ if (janitorDeferral(error)) throw error
2592
2761
  report.janitorDiagnostics.push(
2593
2762
  `build ${record.slug}: node read priming failed — ${error instanceof Error || isForgeFailure(error) ? error.message : String(error)}`,
2594
2763
  )
@@ -2891,6 +3060,46 @@ export class Dispatcher {
2891
3060
  return builds
2892
3061
  }
2893
3062
 
3063
+ /** Admit every node awaiting verification that has a slot, in slug order,
3064
+ * through the janitor's own admission path. Independent of `acceptNewWork`:
3065
+ * node admission is existing work, never intake. */
3066
+ private async admitWaitingNodes(
3067
+ report: TickReport,
3068
+ launched: Set<string>,
3069
+ opts: TickOpts,
3070
+ ): Promise<void> {
3071
+ if (
3072
+ !(await this.repoBuildDigests()).some(
3073
+ ({ digest }) => digest.kind === 'node' && digest.terminal === undefined,
3074
+ )
3075
+ )
3076
+ return
3077
+ const now = this.deps.clock()
3078
+ const waiting = (await this.capacityBuilds())
3079
+ .filter((build) => slotRequest(build, now) === 'verification')
3080
+ .sort((a, b) => (a.record.slug < b.record.slug ? -1 : a.record.slug > b.record.slug ? 1 : 0))
3081
+ for (const { record, state } of waiting) {
3082
+ if (this.outOfBudget(opts)) return
3083
+ if (
3084
+ launched.has(record.slug) ||
3085
+ this.hasLiveExecutionLease(record) ||
3086
+ !state.nodeOpened ||
3087
+ (state.janitor && Date.parse(state.janitor.nextAttemptAt) > now.getTime())
3088
+ )
3089
+ continue
3090
+ await withForgeRequestContext({ build: record.slug }, async () => {
3091
+ try {
3092
+ if (!(await this.nodeHasCapacity(record.slug))) return
3093
+ await this.prepareIntegration(record, state, report, launched)
3094
+ } catch (error) {
3095
+ report.janitorDiagnostics.push(
3096
+ `build ${record.slug}: node admission failed — ${String(error)}`,
3097
+ )
3098
+ }
3099
+ })
3100
+ }
3101
+ }
3102
+
2894
3103
  private async nodeHasCapacity(slug: string): Promise<boolean> {
2895
3104
  const builds = await this.capacityBuilds()
2896
3105
  return (
@@ -2913,6 +3122,25 @@ export class Dispatcher {
2913
3122
  /** Complete abort cleanup as an ordered checkpointed saga. External effects
2914
3123
  * are idempotent; a fact after each one prevents already-settled work from
2915
3124
  * repeating on later ticks. `build.completed` is deliberately last. */
3125
+ /** Record a landed child's effective issue links on its target node, once
3126
+ * per child (SPEC "Forge issue links"). Reduced reads only: the child's
3127
+ * refreshed state and the node's union, never any child history. */
3128
+ private async recordNodeIssueLinks(slug: string): Promise<void> {
3129
+ const state = (await this.store.buildFacts(slug)).state
3130
+ if (state.target === undefined) return
3131
+ const issueLinks = contributedIssueLinks(state)
3132
+ if (issueLinks.length === 0) return
3133
+ const node = (await this.store.buildFacts(state.target.build)).state
3134
+ // Every contributing child gets its own fact, even when the union does
3135
+ // not change; the recorded set is the durable retry evidence.
3136
+ if (node.nodeIssueLinks?.builds.includes(slug)) return
3137
+ await this.store.append(state.target.build, {
3138
+ actor: DISPATCHER,
3139
+ type: 'node.issue-links-recorded',
3140
+ payload: { build: slug, issueLinks },
3141
+ } satisfies EventWrite<'node.issue-links-recorded'>)
3142
+ }
3143
+
2916
3144
  private async cleanupAborted(
2917
3145
  record: BuildRecord,
2918
3146
  events: CurrentBuildFacts,
@@ -3033,6 +3261,9 @@ export class Dispatcher {
3033
3261
  }
3034
3262
  }
3035
3263
 
3264
+ // A child the forge reports merged still carries its links up to its node.
3265
+ if (events.state.prState === 'merged') await this.recordNodeIssueLinks(record.slug)
3266
+
3036
3267
  try {
3037
3268
  const released = await this.releaseWorkspace(record.slug, events, 'abort')
3038
3269
  if (released !== undefined)
@@ -3251,6 +3482,21 @@ export class Dispatcher {
3251
3482
  throw new Error('node-target native auto-merge cancellation unconfirmed')
3252
3483
  nativeCancelled = true
3253
3484
  }
3485
+ // Keep a node PR's keyword lines on its set (refs-only into a parent). A
3486
+ // pure comparison with the last confirmed readback: no forge call while
3487
+ // nothing changed.
3488
+ const issueLinksPending =
3489
+ integration && prState.state === 'open' && !executionLeaseLive
3490
+ ? nodeIssueLinksSyncPending(state, forge)
3491
+ : undefined
3492
+ if (issueLinksPending) {
3493
+ await forge.updatePrIssueLinks!(workspacePath, pr.number, issueLinksPending)
3494
+ await store.append(record.slug, {
3495
+ actor: DISPATCHER,
3496
+ type: 'node.issue-links-published',
3497
+ payload: { pr: pr.number, issueLinks: issueLinksPending },
3498
+ } satisfies EventWrite<'node.issue-links-published'>)
3499
+ }
3254
3500
  // Converge native state on every poll, including paused and unready builds.
3255
3501
  // A replacement publication invalidates readiness, even if a stale enable
3256
3502
  // finished after the publisher confirmed cancellation.
@@ -3599,17 +3845,24 @@ export class Dispatcher {
3599
3845
  sameLandingCandidate(native.candidate, state.landing?.decision?.candidate)
3600
3846
  ? native.retry
3601
3847
  : undefined)
3848
+ const acknowledged = nativeLandingApplied(state.landing) && !state.landing?.nativeEnablePending
3849
+ // SPEC §15.7: an armed, acknowledged request gets the forge's identity
3850
+ // readback on every eligible poll. No consent read or event while it matches.
3851
+ const maintain =
3852
+ acknowledged &&
3853
+ prState.state === 'open' &&
3854
+ prState.nativeAutoMerge === true &&
3855
+ !nativeCancelled &&
3856
+ isReady
3602
3857
  if (
3603
3858
  !integration &&
3604
3859
  !nodeTarget &&
3605
3860
  prState.state === 'open' &&
3606
3861
  landingAuthorized(state.landing) &&
3607
- (prState.nativeAutoMerge === false ||
3608
- !nativeLandingApplied(state.landing) ||
3609
- !!state.landing?.nativeEnablePending) &&
3862
+ (prState.nativeAutoMerge === false || !acknowledged || maintain) &&
3610
3863
  (!retry || Date.parse(retry.after) <= this.deps.clock().getTime()) &&
3611
3864
  commandSeq !== undefined &&
3612
- (await canApply())
3865
+ (maintain || (await canApply()))
3613
3866
  ) {
3614
3867
  const decision = state.landing!.decision!
3615
3868
  // The provider checks eligibility immediately before mutating. Inspection
@@ -3640,103 +3893,116 @@ export class Dispatcher {
3640
3893
  },
3641
3894
  })
3642
3895
  }
3643
- const result =
3644
- prState.nativeAutoMerge === true && !nativeCancelled
3645
- ? { kind: 'applied' as const }
3646
- : await forge
3647
- .setAutoMerge(workspacePath, pr.number, true, {
3648
- buildSlug: record.slug,
3649
- baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
3650
- canApply: async () => {
3651
- if (!(await canApply())) return false
3652
- if (enableSeq === undefined)
3653
- enableSeq = (
3654
- await store.append(record.slug, {
3655
- actor: DISPATCHER,
3656
- type: 'landing.native-enable-started',
3657
- payload: {},
3658
- })
3659
- ).seq
3660
- return true
3661
- },
3662
- })
3663
- .catch(async (error: unknown) => {
3664
- if (isForgeFailure(error)) {
3665
- const attempt = (retry?.attempt ?? 0) + 1
3666
- await store.append(record.slug, {
3667
- actor: DISPATCHER,
3668
- type: 'landing.application-failed',
3669
- payload: {
3670
- candidate: decision.candidate,
3671
- decisionSeq: decision.seq,
3672
- ...(state.landing?.command ? { commandSeq: state.landing.command.seq } : {}),
3673
- message: error.message,
3674
- attempt,
3675
- after: new Date(
3676
- Math.max(
3677
- this.deps.clock().getTime() +
3678
- Math.min(300_000, 30_000 * 2 ** Math.min(attempt - 1, 4)),
3679
- error.details.kind === 'rate-limited'
3680
- ? Date.parse(error.details.resetAt)
3681
- : 0,
3682
- ),
3683
- ).toISOString(),
3684
- },
3685
- })
3686
- // An uncertain enable stays pending. Never spend another request during a limit.
3687
- throw error
3688
- }
3689
- await settleFailedEnable()
3690
- throw error
3691
- })
3692
- // Only an attempt that reached the mutation guard needs cancellation.
3693
- // Persist retry timing with its receipt so restart cannot reset backoff.
3694
- if (result.kind !== 'applied') await settleFailedEnable()
3695
- if (result.kind === 'applied') {
3696
- const latest = (await store.buildFacts(record.slug)).state
3697
- if (await canApply()) {
3698
- if (
3699
- latest.landing?.nativeEnablePending ||
3700
- latest.landing?.native?.enabled !== true ||
3701
- latest.landing.native.decisionSeq !== decision.seq ||
3702
- latest.landing.native.commandSeq !== latest.landing.command?.seq
3703
- )
3896
+ // An enabled request counts as applied only after the forge confirms
3897
+ // its method and identity message; a mismatch is repaired under consent.
3898
+ const result = await forge
3899
+ .setAutoMerge(workspacePath, pr.number, true, {
3900
+ buildSlug: record.slug,
3901
+ baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
3902
+ ...issueLinksForForge(state, forge),
3903
+ canApply: async () => {
3904
+ if (!(await canApply())) return false
3905
+ if (enableSeq === undefined)
3906
+ enableSeq = (
3907
+ await store.append(record.slug, {
3908
+ actor: DISPATCHER,
3909
+ type: 'landing.native-enable-started',
3910
+ payload: {},
3911
+ })
3912
+ ).seq
3913
+ return true
3914
+ },
3915
+ })
3916
+ .catch(async (error: unknown) => {
3917
+ if (isForgeFailure(error)) {
3918
+ const attempt = (retry?.attempt ?? 0) + 1
3704
3919
  await store.append(record.slug, {
3705
3920
  actor: DISPATCHER,
3706
- type: 'landing.native-applied',
3921
+ type: 'landing.application-failed',
3707
3922
  payload: {
3708
- enabled: true,
3709
- ...(enableSeq !== undefined ? { enableSeq } : {}),
3710
3923
  candidate: decision.candidate,
3711
3924
  decisionSeq: decision.seq,
3712
- ...(latest.landing?.command ? { commandSeq: latest.landing.command.seq } : {}),
3925
+ ...(state.landing?.command ? { commandSeq: state.landing.command.seq } : {}),
3926
+ message: error.message,
3927
+ attempt,
3928
+ after: new Date(
3929
+ Math.max(
3930
+ this.deps.clock().getTime() +
3931
+ Math.min(300_000, 30_000 * 2 ** Math.min(attempt - 1, 4)),
3932
+ error.details.kind === 'rate-limited' ? Date.parse(error.details.resetAt) : 0,
3933
+ ),
3934
+ ).toISOString(),
3713
3935
  },
3714
3936
  })
3715
- } else {
3716
- // Enable may have won after cancellation. Repair immediately, and
3717
- // again on the next poll if this process dies at this boundary.
3718
- const cancelled = await forge.setAutoMerge(workspacePath, pr.number, false)
3719
- if (cancelled.kind === 'applied')
3720
- await store.append(record.slug, {
3721
- actor: DISPATCHER,
3722
- type: 'landing.native-applied',
3723
- payload: { enabled: false, ...(enableSeq !== undefined ? { enableSeq } : {}) },
3724
- })
3725
- }
3726
- } else if (result.kind === 'deferred' && result.reason) {
3727
- await recordAutoMergeDeferralObservation(
3728
- store,
3729
- record.slug,
3730
- result.reason,
3731
- pr.number,
3732
- commandSeq,
3733
- this.deps.ids('obs'),
3734
- )
3735
- } else if (result.kind === 'ungated' && prState.mergeable === true && (await canApply())) {
3736
- await forge.squashMerge(workspacePath, pr.number, result.headSha, {
3737
- buildSlug: record.slug,
3738
- baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
3937
+ // An uncertain enable stays pending. Never spend another request during a limit.
3938
+ throw error
3939
+ }
3940
+ await settleFailedEnable()
3941
+ throw error
3739
3942
  })
3943
+ if (maintain && enableSeq === undefined) {
3944
+ // Quiet maintenance: no consent check passed, so nothing was mutated.
3945
+ // A vanished request is reconciled by the next poll's PR read.
3946
+ if (result.kind === 'deferred' && result.reason)
3947
+ await recordAutoMergeDeferralObservation(
3948
+ store,
3949
+ record.slug,
3950
+ result.reason,
3951
+ pr.number,
3952
+ commandSeq,
3953
+ this.deps.ids('obs'),
3954
+ )
3955
+ } else {
3956
+ // Only an attempt that reached the mutation guard needs cancellation.
3957
+ // Persist retry timing with its receipt so restart cannot reset backoff.
3958
+ if (result.kind !== 'applied') await settleFailedEnable()
3959
+ if (result.kind === 'applied') {
3960
+ const latest = (await store.buildFacts(record.slug)).state
3961
+ if (await canApply()) {
3962
+ if (
3963
+ latest.landing?.nativeEnablePending ||
3964
+ latest.landing?.native?.enabled !== true ||
3965
+ latest.landing.native.decisionSeq !== decision.seq ||
3966
+ latest.landing.native.commandSeq !== latest.landing.command?.seq
3967
+ )
3968
+ await store.append(record.slug, {
3969
+ actor: DISPATCHER,
3970
+ type: 'landing.native-applied',
3971
+ payload: {
3972
+ enabled: true,
3973
+ ...(enableSeq !== undefined ? { enableSeq } : {}),
3974
+ candidate: decision.candidate,
3975
+ decisionSeq: decision.seq,
3976
+ ...(latest.landing?.command ? { commandSeq: latest.landing.command.seq } : {}),
3977
+ },
3978
+ })
3979
+ } else {
3980
+ // Enable may have won after cancellation. Repair immediately, and
3981
+ // again on the next poll if this process dies at this boundary.
3982
+ const cancelled = await forge.setAutoMerge(workspacePath, pr.number, false)
3983
+ if (cancelled.kind === 'applied')
3984
+ await store.append(record.slug, {
3985
+ actor: DISPATCHER,
3986
+ type: 'landing.native-applied',
3987
+ payload: { enabled: false, ...(enableSeq !== undefined ? { enableSeq } : {}) },
3988
+ })
3989
+ }
3990
+ } else if (result.kind === 'deferred' && result.reason) {
3991
+ await recordAutoMergeDeferralObservation(
3992
+ store,
3993
+ record.slug,
3994
+ result.reason,
3995
+ pr.number,
3996
+ commandSeq,
3997
+ this.deps.ids('obs'),
3998
+ )
3999
+ } else if (result.kind === 'ungated' && prState.mergeable === true && (await canApply())) {
4000
+ await forge.squashMerge(workspacePath, pr.number, result.headSha, {
4001
+ buildSlug: record.slug,
4002
+ baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
4003
+ ...issueLinksForForge(state, forge),
4004
+ })
4005
+ }
3740
4006
  }
3741
4007
  }
3742
4008
 
@@ -3851,6 +4117,9 @@ export class Dispatcher {
3851
4117
  payload: await this.mergeEvidence(record, workspacePath, prState.sha, state.kind),
3852
4118
  } satisfies EventWrite<'pr.merged'>)
3853
4119
  }
4120
+ // Before the child can become terminal, so a complete node already
4121
+ // folds every landed child's links; the node log dedupes a retry.
4122
+ await this.recordNodeIssueLinks(record.slug)
3854
4123
  await this.releaseWorkspace(record.slug, events)
3855
4124
  if (record.ticket) {
3856
4125
  await tickets.transition(await this.currentTicketId(record), this.doneState)
@@ -3958,11 +4227,21 @@ export class Dispatcher {
3958
4227
  input: Parameters<WorkspaceProvider['provision']>[0],
3959
4228
  ) {
3960
4229
  const facts = (await readBuildFacts(this.store, slug)).value
4230
+ const { restoration, superseded } = supersedeRestorationHeads(
4231
+ facts.workspacePreservation?.payload.heads,
4232
+ facts.replacedHeads,
4233
+ )
3961
4234
  try {
3962
- return await this.deps.workspaces.provision({
4235
+ const handle = await this.deps.workspaces.provision({
3963
4236
  ...input,
3964
- restoration: facts.workspacePreservation?.payload.heads,
4237
+ restoration,
4238
+ ...(facts.replacedHeads.length ? { restorationReplaced: facts.replacedHeads } : {}),
3965
4239
  })
4240
+ const skipped = [
4241
+ ...superseded.map((sha) => ({ sha, reason: 'superseded' as const })),
4242
+ ...(handle.restorationSkipped ?? []).filter((skip) => !superseded.includes(skip.sha)),
4243
+ ]
4244
+ return skipped.length ? { ...handle, restorationSkipped: skipped } : handle
3966
4245
  } catch (error) {
3967
4246
  if (error instanceof WorkspaceCleanupRequired) {
3968
4247
  await this.store.append(slug, {
@@ -4045,9 +4324,9 @@ export class Dispatcher {
4045
4324
  const recovery = this.workspaceOwner(open)?.recovery
4046
4325
  if (recovery === undefined) return false
4047
4326
  // Last-chance settlement boundary (AUT-328): record the pending
4048
- // publication's fate BEFORE the destructive reap. The guard's append
4049
- // failure propagates — a stale workspace with an unrecorded pending
4050
- // request is never reaped (the next tick retries).
4327
+ // publication's fate BEFORE the destructive reap. A guard failure is
4328
+ // recorded against the build — a stale workspace with an unrecorded
4329
+ // pending request is never reaped (the next tick retries).
4051
4330
  try {
4052
4331
  await preserveWorkspaceBeforeRelease({
4053
4332
  store: this.store,
@@ -4069,7 +4348,12 @@ export class Dispatcher {
4069
4348
  // Keep this generation and its pending work until forge recovery,
4070
4349
  // while allowing the sweep to supervise the remaining builds.
4071
4350
  if (error instanceof ForgeRequestDeferred) return false
4072
- if (!(error instanceof WorkspaceFenceUnknown)) throw error
4351
+ // A repository-wide forge cooldown or version deferral is not this
4352
+ // build's failure; the tick-level handlers own it.
4353
+ if (error instanceof ForgeCooldown || error instanceof MixedVersionDeferral) throw error
4354
+ // Any other preservation or settlement failure (an unknown fence, a
4355
+ // checkout that could not be inspected) retains the workspace and its
4356
+ // pending work and is attributed to this build, never to the tick.
4073
4357
  await this.recordInfrastructureFailure(slug, events, {
4074
4358
  provider: open.provider,
4075
4359
  workspaceRef: open.ref,
@@ -4248,8 +4532,9 @@ export class Dispatcher {
4248
4532
 
4249
4533
  // ── b. Interrupted dispatch recovery ───────────────────────────────────────
4250
4534
 
4251
- /** The claim-time `build.created` payload. Assets are omitted when the ticket
4252
- * had none, so a no-asset build's log is exactly what it was before. */
4535
+ /** The claim-time `build.created` payload. Assets and issue links are
4536
+ * omitted when the ticket had none, so such a build's log is exactly what it
4537
+ * was before. */
4253
4538
  private buildCreatedPayload(
4254
4539
  ticket: TicketRef,
4255
4540
  repo: string,
@@ -4258,6 +4543,7 @@ export class Dispatcher {
4258
4543
  autoMergeUser?: string
4259
4544
  autoMergeDefaultSeq?: number
4260
4545
  assets?: PinnedAsset[]
4546
+ issueLinks?: IssueLink[]
4261
4547
  kind?: 'work' | 'node'
4262
4548
  target?: EventPayload<'build.created'>['target']
4263
4549
  baseBranch?: string
@@ -4277,6 +4563,9 @@ export class Dispatcher {
4277
4563
  : {}),
4278
4564
  ...(config.pr !== undefined ? { pr: config.pr } : {}),
4279
4565
  ...(seed?.assets !== undefined && seed.assets.length > 0 ? { assets: seed.assets } : {}),
4566
+ ...(seed?.issueLinks !== undefined && seed.issueLinks.length > 0
4567
+ ? { issueLinks: seed.issueLinks.map(({ issue, intent }) => ({ issue, intent })) }
4568
+ : {}),
4280
4569
  }
4281
4570
  }
4282
4571
 
@@ -4340,7 +4629,13 @@ export class Dispatcher {
4340
4629
  await store.appendIfCurrent(record.slug, 0, {
4341
4630
  actor: DISPATCHER,
4342
4631
  type: 'build.created',
4343
- payload: this.buildCreatedPayload(record.ticket, record.repo, { ...seed, assets }),
4632
+ payload: this.buildCreatedPayload(record.ticket, record.repo, {
4633
+ ...seed,
4634
+ assets,
4635
+ ...(seed?.ticket.issueLinks !== undefined
4636
+ ? { issueLinks: seed.ticket.issueLinks }
4637
+ : {}),
4638
+ }),
4344
4639
  })
4345
4640
  events = (await readBuildFacts(store, record.slug)).value
4346
4641
  if (events.created === undefined) {
@@ -4353,6 +4648,23 @@ export class Dispatcher {
4353
4648
  return this.completeDispatchBoundaries(record, seed, report, launched)
4354
4649
 
4355
4650
  stage = 'workspace'
4651
+ const flagged = openWorkspace(events)
4652
+ if (
4653
+ flagged !== null &&
4654
+ cleanupRequiredWorkspace(events) &&
4655
+ this.workspaceOwner(flagged)?.recovery !== undefined
4656
+ ) {
4657
+ // A retry never launches into a flagged environment: release it, then
4658
+ // provision the next generation below. A live lease means a foreign
4659
+ // continuation still owns the build.
4660
+ if (this.hasLiveExecutionLease(record)) return 'parked'
4661
+ if (!(await this.reapStaleWorkspace(record.slug, events, 'replacement'))) {
4662
+ // The failure is already durable against this build.
4663
+ launched.add(record.slug)
4664
+ return 'parked'
4665
+ }
4666
+ events = (await readBuildFacts(store, record.slug)).value
4667
+ }
4356
4668
  if (openWorkspace(events) === null) {
4357
4669
  if (this.deps.workspaces.recovery !== undefined) {
4358
4670
  // Recovery-capable provider: durable marker + tracked background
@@ -4390,6 +4702,9 @@ export class Dispatcher {
4390
4702
  remote: this.deps.workspaces.publication !== undefined,
4391
4703
  branch: handle.branch,
4392
4704
  base: handle.base,
4705
+ ...(handle.restorationSkipped?.length
4706
+ ? { restorationSkipped: handle.restorationSkipped }
4707
+ : {}),
4393
4708
  },
4394
4709
  } satisfies EventWrite<'workspace.provisioned'>)
4395
4710
  events = (await readBuildFacts(store, record.slug)).value
@@ -4515,7 +4830,7 @@ export class Dispatcher {
4515
4830
  if (record.ticket !== undefined && !events.commentPosted) {
4516
4831
  await this.deps.tickets.comment(
4517
4832
  await this.currentTicketId(record),
4518
- `build ${record.slug} dispatched`,
4833
+ dispatchCommentBody(record.slug),
4519
4834
  )
4520
4835
  await store.append(record.slug, {
4521
4836
  actor: DISPATCHER,
@@ -4543,7 +4858,7 @@ export class Dispatcher {
4543
4858
  return 'parked'
4544
4859
  }
4545
4860
  if (!this.accountsAvailable()) return 'parked'
4546
- if (launched === undefined) await this.deps.launchRunner(record.slug)
4861
+ if (launched === undefined) await this.startRunner(record.slug, report ?? emptyTickReport())
4547
4862
  else await this.launch(record.slug, launched, report)
4548
4863
  if (authored && report !== undefined) report.authored += 1
4549
4864
  return 'completed'
@@ -4704,209 +5019,236 @@ export class Dispatcher {
4704
5019
  if (launched.has(record.slug)) continue
4705
5020
  // Budget gate: the sweep re-attaches runners per expired build.
4706
5021
  if (this.outOfBudget(opts)) break
4707
- if (record.lease) {
4708
- if (new Date(record.lease.expiresAt).getTime() > now) continue // healthy
4709
- }
4710
- const facts = await this.store.buildFacts(record.slug)
4711
- const state = facts.state
4712
- if (mixedVersionDeferred(state)) {
4713
- await deferMixedVersion(this.store, record.slug)
4714
- continue
4715
- }
4716
- if (
4717
- (state.status === 'queued' && state.discardRequest !== undefined) ||
4718
- heldByRepositoryPause(state, paused)
4719
- ) {
4720
- continue
4721
- }
4722
- if (
4723
- state.status === 'queued' &&
4724
- !state.pendingCommands.some((command) => command.command === 'abort') &&
4725
- !(await this.dispatchBudget(record.slug))
4726
- )
4727
- continue
4728
- const pendingRewrite = facts.publication.latestUncompletedRequest()?.payload
4729
- const retryIntent =
4730
- pendingRewrite?.operation === 'reconcile' && pendingRewrite.rewrite
4731
- ? { operation: 'reconcile' as const, id: pendingRewrite.rewrite.id }
4732
- : facts.log.restack.intent
4733
- ? { operation: 'restack' as const, id: facts.log.restack.intent.id }
4734
- : undefined
4735
- // Publication waits must not prevent a replacement runner from
4736
- // acknowledging controls, including abort on an exhausted episode.
4737
- if (retryIntent && state.pendingCommands.length === 0) {
4738
- try {
4739
- await publicationRetryGate(
4740
- { store: this.store, slug: record.slug, clock: this.deps.clock, actor: DISPATCHER },
4741
- retryIntent.operation,
4742
- retryIntent.id,
4743
- )
4744
- } catch (error) {
4745
- if (error instanceof ForgeRequestDeferred) continue
4746
- throw error
4747
- }
5022
+ try {
5023
+ await this.sweepBuild(record, report, launched, paused, now)
5024
+ } catch (error) {
5025
+ // Per-build containment: one build's failure never stops the sweep
5026
+ // from advancing the others. Workspace failures are already durable
5027
+ // against the build; a repository-wide cooldown still ends the tick.
5028
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
5029
+ if (error instanceof ForgeCooldown) throw error
5030
+ const message =
5031
+ error instanceof Error || isForgeFailure(error) ? error.message : String(error)
5032
+ report.janitorFailed += 1
5033
+ report.janitorDiagnostics.push(`build ${record.slug}: lease sweep failed — ${message}`)
4748
5034
  }
4749
- const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
4750
- if (decision === undefined) continue
4751
- if (state.status === 'done' || state.status === 'aborted') continue
4752
- const orphanEligible = (state: BuildState) =>
4753
- !paused &&
4754
- state.status === 'running' &&
4755
- (state.kind !== 'node' || integrationCurrent(state)) &&
4756
- state.sessions.open.some((session) => session.suspensionCause === undefined)
4757
- const provedEnded =
4758
- facts.open === null &&
4759
- (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch')
4760
- const cleanup = state.verifyStage.cleanupExecutionSeq
4761
- if (
4762
- !record.lease &&
4763
- now - new Date(record.updatedAt).getTime() < this.leaseTtlMs &&
4764
- facts.lastExecution !== 'relaunch' &&
4765
- !(cleanup !== undefined && state.verifyStage.executionSeq <= cleanup) &&
4766
- !(provedEnded && (decision.kind !== 'wait' || orphanEligible(state)))
4767
- )
4768
- continue // preserve first-claim grace, but never postpone proved-ended work
5035
+ }
5036
+ }
4769
5037
 
4770
- if (
4771
- state.kind === 'node' &&
4772
- (!integrationCurrent(state) || facts.workspace === null) &&
4773
- decision.kind !== 'wait'
4774
- )
4775
- continue // cascade owns node runner admission
4776
- // Raw history, read at most once and only by a branch that acts on it.
4777
- let loaded: CurrentBuildFacts | undefined
4778
- const history = async (): Promise<CurrentBuildFacts> => {
4779
- loaded ??= (await readBuildFacts(this.store, record.slug)).value
4780
- return loaded
4781
- }
4782
- // Liveness gate (durable supervision): a recorded execution the provider
4783
- // observes as RUNNING is left completely alone — no settle, no reap, no
4784
- // replacement, no re-attach. This is the change that stops a supervisor
4785
- // restart from replacing a healthy environment generation. A provider-
4786
- // proved end settles first (completion facts, lease release, publication)
4787
- // and then falls through to the normal decision; a provider-proved loss
4788
- // falls through to the existing stale path below.
4789
- let orphanRecoveryDue = orphanEligible(state) && facts.open === null
4790
- const foreignExecution = facts.open
4791
- // A provider- or log-proved end in the same generation re-attaches in
4792
- // place: the guest finished its work, the workspace is still the
4793
- // build's, and replacing the environment would discard a healthy
4794
- // generation. Only an unproven stale lease or a proved loss reaps.
4795
- // A start that later found the open workspace missing is a proved loss
4796
- // too: the recorded end no longer vouches for an environment that is
4797
- // gone, and re-attaching would fail against the same ref forever.
4798
- const failure = state.infrastructureFailure
4799
- const workspaceMissing =
4800
- failure?.cause === 'missing' &&
4801
- failure.operation === 'start' &&
4802
- failure.workspaceRef === facts.workspace?.ref
4803
- let endedInPlace =
4804
- (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch') &&
4805
- !workspaceMissing
4806
- if (
4807
- foreignExecution !== null &&
4808
- foreignExecution.commandId !== undefined &&
4809
- !launched.has(record.slug)
4810
- ) {
4811
- const owner = this.executionOwner(foreignExecution.provider)
4812
- const execution = owner?.buildExecution
4813
- if (execution?.observe !== undefined) {
4814
- const settlement = await settleOpenExecution(
4815
- {
4816
- store: this.store,
4817
- execution,
4818
- ...(this.settlePublication !== undefined
4819
- ? { settlePublication: this.settlePublication }
4820
- : {}),
4821
- },
4822
- record.slug,
4823
- foreignExecution,
4824
- )
4825
- if (settlement === 'running') continue
4826
- // Unknown liveness is never proof that an open execution is dead.
4827
- // Settlement may itself raise provider attention. Revalidate cleanup
4828
- // eligibility from the advanced canonical state before admission.
4829
- orphanRecoveryDue = orphanEligible((await this.store.buildFacts(record.slug)).state)
4830
- if (settlement === 'settled') {
4831
- report.settled += 1
4832
- endedInPlace = true
4833
- }
4834
- }
5038
+ /** One build's lease-sweep pass; `leaseSweep` contains its failures. */
5039
+ private async sweepBuild(
5040
+ record: BuildRecord,
5041
+ report: TickReport,
5042
+ launched: Set<string>,
5043
+ paused: boolean,
5044
+ now: number,
5045
+ ): Promise<void> {
5046
+ if (record.lease) {
5047
+ if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
5048
+ }
5049
+ const facts = await this.store.buildFacts(record.slug)
5050
+ const state = facts.state
5051
+ if (mixedVersionDeferred(state)) {
5052
+ await deferMixedVersion(this.store, record.slug)
5053
+ return
5054
+ }
5055
+ if (
5056
+ (state.status === 'queued' && state.discardRequest !== undefined) ||
5057
+ heldByRepositoryPause(state, paused)
5058
+ ) {
5059
+ return
5060
+ }
5061
+ if (
5062
+ state.status === 'queued' &&
5063
+ !state.pendingCommands.some((command) => command.command === 'abort') &&
5064
+ !(await this.dispatchBudget(record.slug))
5065
+ )
5066
+ return
5067
+ const pendingRewrite = facts.publication.latestUncompletedRequest()?.payload
5068
+ const retryIntent =
5069
+ pendingRewrite?.operation === 'reconcile' && pendingRewrite.rewrite
5070
+ ? { operation: 'reconcile' as const, id: pendingRewrite.rewrite.id }
5071
+ : facts.log.restack.intent
5072
+ ? { operation: 'restack' as const, id: facts.log.restack.intent.id }
5073
+ : undefined
5074
+ // Publication waits must not prevent a replacement runner from
5075
+ // acknowledging controls, including abort on an exhausted episode.
5076
+ if (retryIntent && state.pendingCommands.length === 0) {
5077
+ try {
5078
+ await publicationRetryGate(
5079
+ { store: this.store, slug: record.slug, clock: this.deps.clock, actor: DISPATCHER },
5080
+ retryIntent.operation,
5081
+ retryIntent.id,
5082
+ )
5083
+ } catch (error) {
5084
+ if (error instanceof ForgeRequestDeferred) return
5085
+ throw error
4835
5086
  }
4836
- const publicationRecoveryDue =
4837
- state.status !== 'paused' &&
4838
- state.status !== 'blocked' &&
4839
- (facts.publication.pending() || facts.publication.abandonedPending())
4840
- const open = facts.workspace
4841
- // A provider- or log-proved END in the same generation re-attaches in
4842
- // place: the guest finished its work, the workspace is still the
4843
- // build's, and replacing the environment would discard a healthy
4844
- // generation. Only an unproven stale lease or a proved loss reaps.
4845
- if (open !== null && this.workspaceOwner(open)?.recovery !== undefined && !endedInPlace) {
4846
- const parked = decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue
4847
- const reason =
4848
- state.status === 'paused'
4849
- ? ('pause' as const)
4850
- : state.status === 'blocked'
4851
- ? ('blocked' as const)
4852
- : ('replacement' as const)
4853
- const reaped = await this.reapStaleWorkspace(record.slug, await history(), reason)
4854
- if (!reaped) continue
4855
- if (!parked) {
4856
- // Recovery-capable provider: reap inline (bounded), then kick the
4857
- // same background continuation — it provisions and launches without
4858
- // blocking this tick. Local providers never enter this branch.
4859
- const kicked = await this.ensureProvisionContinuation(record, await history(), 'launch')
4860
- if (kicked === 'kicked') {
4861
- report.provisioning += 1
4862
- report.swept += 1
4863
- }
4864
- continue
5087
+ }
5088
+ const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
5089
+ if (decision === undefined) return
5090
+ if (state.status === 'done' || state.status === 'aborted') return
5091
+ const orphanEligible = (state: BuildState) =>
5092
+ !paused &&
5093
+ state.status === 'running' &&
5094
+ (state.kind !== 'node' || integrationCurrent(state)) &&
5095
+ state.sessions.open.some((session) => session.suspensionCause === undefined)
5096
+ const provedEnded =
5097
+ facts.open === null &&
5098
+ (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch')
5099
+ const cleanup = state.verifyStage.cleanupExecutionSeq
5100
+ if (
5101
+ !record.lease &&
5102
+ now - new Date(record.updatedAt).getTime() < this.leaseTtlMs &&
5103
+ facts.lastExecution !== 'relaunch' &&
5104
+ !(cleanup !== undefined && state.verifyStage.executionSeq <= cleanup) &&
5105
+ !(provedEnded && (decision.kind !== 'wait' || orphanEligible(state)))
5106
+ )
5107
+ return // preserve first-claim grace, but never postpone proved-ended work
5108
+
5109
+ if (
5110
+ state.kind === 'node' &&
5111
+ (!integrationCurrent(state) || facts.workspace === null) &&
5112
+ decision.kind !== 'wait'
5113
+ )
5114
+ return // cascade owns node runner admission
5115
+ // Raw history, read at most once and only by a branch that acts on it.
5116
+ let loaded: CurrentBuildFacts | undefined
5117
+ const history = async (): Promise<CurrentBuildFacts> => {
5118
+ loaded ??= (await readBuildFacts(this.store, record.slug)).value
5119
+ return loaded
5120
+ }
5121
+ // Liveness gate (durable supervision): a recorded execution the provider
5122
+ // observes as RUNNING is left completely alone — no settle, no reap, no
5123
+ // replacement, no re-attach. This is the change that stops a supervisor
5124
+ // restart from replacing a healthy environment generation. A provider-
5125
+ // proved end settles first (completion facts, lease release, publication)
5126
+ // and then falls through to the normal decision; a provider-proved loss
5127
+ // falls through to the existing stale path below.
5128
+ let orphanRecoveryDue = orphanEligible(state) && facts.open === null
5129
+ const foreignExecution = facts.open
5130
+ // A provider- or log-proved end in the same generation re-attaches in
5131
+ // place: the guest finished its work, the workspace is still the
5132
+ // build's, and replacing the environment would discard a healthy
5133
+ // generation. Only an unproven stale lease or a proved loss reaps.
5134
+ // A start that later found the open workspace missing is a proved loss
5135
+ // too: the recorded end no longer vouches for an environment that is
5136
+ // gone, and re-attaching would fail against the same ref forever.
5137
+ const failure = state.infrastructureFailure
5138
+ const workspaceMissing =
5139
+ failure?.cause === 'missing' &&
5140
+ failure.operation === 'start' &&
5141
+ failure.workspaceRef === facts.workspace?.ref
5142
+ let endedInPlace =
5143
+ (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch') &&
5144
+ !workspaceMissing
5145
+ if (
5146
+ foreignExecution !== null &&
5147
+ foreignExecution.commandId !== undefined &&
5148
+ !launched.has(record.slug)
5149
+ ) {
5150
+ const owner = this.executionOwner(foreignExecution.provider)
5151
+ const execution = owner?.buildExecution
5152
+ if (execution?.observe !== undefined) {
5153
+ const settlement = await settleOpenExecution(
5154
+ {
5155
+ store: this.store,
5156
+ execution,
5157
+ ...(this.settlePublication !== undefined
5158
+ ? { settlePublication: this.settlePublication }
5159
+ : {}),
5160
+ },
5161
+ record.slug,
5162
+ foreignExecution,
5163
+ )
5164
+ if (settlement === 'running') return
5165
+ // Unknown liveness is never proof that an open execution is dead.
5166
+ // Settlement may itself raise provider attention. Revalidate cleanup
5167
+ // eligibility from the advanced canonical state before admission.
5168
+ orphanRecoveryDue = orphanEligible((await this.store.buildFacts(record.slug)).state)
5169
+ if (settlement === 'settled') {
5170
+ report.settled += 1
5171
+ endedInPlace = true
4865
5172
  }
4866
5173
  }
4867
- // Reachable via the reap block above: when the wait decision is parked
4868
- // (no publication recovery due) the `if (!parked)` arm continues, but the
4869
- // parked arm falls through here after a successful reap. Without this
4870
- // guard the tick would reach the unconditional `launch` below and start a
4871
- // fresh runner for a paused or blocked build whose workspace was just
4872
- // reaped. Every other path that reaches this line with a wait decision
4873
- // already continued earlier.
4874
- if (decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue) continue
4875
- if (
4876
- facts.workspace === null &&
4877
- this.deps.workspaces.recovery !== undefined &&
4878
- (await history()).workspaceGenerations > 0
4879
- ) {
5174
+ }
5175
+ const publicationRecoveryDue =
5176
+ state.status !== 'paused' &&
5177
+ state.status !== 'blocked' &&
5178
+ (facts.publication.pending() || facts.publication.abandonedPending())
5179
+ const open = facts.workspace
5180
+ // A flagged `cleanup-required` workspace never re-attaches in place: it
5181
+ // is reaped and replaced by the next generation.
5182
+ if (endedInPlace && open !== null && cleanupRequiredWorkspace(await history()))
5183
+ endedInPlace = false
5184
+ // A provider- or log-proved END in the same generation re-attaches in
5185
+ // place: the guest finished its work, the workspace is still the
5186
+ // build's, and replacing the environment would discard a healthy
5187
+ // generation. Only an unproven stale lease or a proved loss reaps.
5188
+ if (open !== null && this.workspaceOwner(open)?.recovery !== undefined && !endedInPlace) {
5189
+ const parked = decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue
5190
+ const reason =
5191
+ state.status === 'paused'
5192
+ ? ('pause' as const)
5193
+ : state.status === 'blocked'
5194
+ ? ('blocked' as const)
5195
+ : ('replacement' as const)
5196
+ const reaped = await this.reapStaleWorkspace(record.slug, await history(), reason)
5197
+ if (!reaped) return
5198
+ if (!parked) {
5199
+ // Recovery-capable provider: reap inline (bounded), then kick the
5200
+ // same background continuation — it provisions and launches without
5201
+ // blocking this tick. Local providers never enter this branch.
4880
5202
  const kicked = await this.ensureProvisionContinuation(record, await history(), 'launch')
4881
5203
  if (kicked === 'kicked') {
4882
5204
  report.provisioning += 1
4883
5205
  report.swept += 1
4884
- continue
4885
5206
  }
4886
- // In-flight or foreign-live: whoever owns the marker completes the
4887
- // boundaries and the launch; this tick performs neither.
4888
- continue
5207
+ return
4889
5208
  }
4890
- try {
4891
- const result = await this.launch(record.slug, launched, report)
4892
- if (result === 'scheduled') report.swept += 1
4893
- } catch (error) {
4894
- // Launchers normally record provider failures themselves. Preserve
4895
- // durable attention if orphan cleanup fails before that boundary,
4896
- // without counting an already-recorded failure twice.
4897
- if (orphanRecoveryDue && open !== null) {
4898
- const current = (await readBuildFacts(this.store, record.slug)).value
4899
- if (current.infrastructureCount === facts.infrastructureCount)
4900
- await this.recordInfrastructureFailure(record.slug, current, {
4901
- provider: open.provider,
4902
- workspaceRef: open.ref,
4903
- operation: 'start',
4904
- error,
4905
- cleanupPending: false,
4906
- })
4907
- }
4908
- throw error
5209
+ }
5210
+ // Reachable via the reap block above: when the wait decision is parked
5211
+ // (no publication recovery due) the `if (!parked)` arm continues, but the
5212
+ // parked arm falls through here after a successful reap. Without this
5213
+ // guard the tick would reach the unconditional `launch` below and start a
5214
+ // fresh runner for a paused or blocked build whose workspace was just
5215
+ // reaped. Every other path that reaches this line with a wait decision
5216
+ // already continued earlier.
5217
+ if (decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue) return
5218
+ if (
5219
+ facts.workspace === null &&
5220
+ this.deps.workspaces.recovery !== undefined &&
5221
+ (await history()).workspaceGenerations > 0
5222
+ ) {
5223
+ const kicked = await this.ensureProvisionContinuation(record, await history(), 'launch')
5224
+ if (kicked === 'kicked') {
5225
+ report.provisioning += 1
5226
+ report.swept += 1
5227
+ return
4909
5228
  }
5229
+ // In-flight or foreign-live: whoever owns the marker completes the
5230
+ // boundaries and the launch; this tick performs neither.
5231
+ return
5232
+ }
5233
+ try {
5234
+ const result = await this.launch(record.slug, launched, report)
5235
+ if (result === 'scheduled') report.swept += 1
5236
+ } catch (error) {
5237
+ // Launchers normally record provider failures themselves. Preserve
5238
+ // durable attention if orphan cleanup fails before that boundary,
5239
+ // without counting an already-recorded failure twice.
5240
+ if (orphanRecoveryDue && open !== null) {
5241
+ const current = (await readBuildFacts(this.store, record.slug)).value
5242
+ if (current.infrastructureCount === facts.infrastructureCount)
5243
+ await this.recordInfrastructureFailure(record.slug, current, {
5244
+ provider: open.provider,
5245
+ workspaceRef: open.ref,
5246
+ operation: 'start',
5247
+ error,
5248
+ cleanupPending: false,
5249
+ })
5250
+ }
5251
+ throw error
4910
5252
  }
4911
5253
  }
4912
5254
 
@@ -4956,6 +5298,14 @@ export class Dispatcher {
4956
5298
  })
4957
5299
  }
4958
5300
 
5301
+ /** Durably abandon an attempt, then queue its one operator diagnostic for
5302
+ * this tick. No line exists unless the resolution was appended. */
5303
+ private async abandonPreparation(attempt: TicketPreparation, reason: string): Promise<void> {
5304
+ const recorded = reason.slice(0, 4000)
5305
+ await this.preparationResolved(attempt, 'abandoned', recorded)
5306
+ this.tickAbandonments.push(abandonedPreparationDiagnostic(attempt, recorded))
5307
+ }
5308
+
4959
5309
  private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
4960
5310
  try {
4961
5311
  // A rejected create can have committed. Unavailable or conflicting readback
@@ -4972,9 +5322,8 @@ export class Dispatcher {
4972
5322
  created.payload.ticket?.source !== attempt.ticket.source ||
4973
5323
  created.payload.ticket?.id !== attempt.ticket.id
4974
5324
  )
4975
- return await this.preparationResolved(
5325
+ return await this.abandonPreparation(
4976
5326
  attempt,
4977
- 'abandoned',
4978
5327
  `Conflicting build ownership at ${attempt.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
4979
5328
  )
4980
5329
  await this.preparationResolved(attempt, 'owned')
@@ -4989,15 +5338,10 @@ export class Dispatcher {
4989
5338
  )
4990
5339
  const ticket = await this.deps.tickets.get(ref.id)
4991
5340
  if (!ticket)
4992
- return await this.preparationResolved(
4993
- attempt,
4994
- 'abandoned',
4995
- 'Ticket no longer exists; ticket unchanged.',
4996
- )
5341
+ return await this.abandonPreparation(attempt, 'Ticket no longer exists; ticket unchanged.')
4997
5342
  if (ticket.state === undefined)
4998
- return await this.preparationResolved(
5343
+ return await this.abandonPreparation(
4999
5344
  attempt,
5000
- 'abandoned',
5001
5345
  'Ticket state is unavailable; ticket unchanged. Inspect the provider record before manually retrying.',
5002
5346
  )
5003
5347
  const state = (value: string) => value.toLowerCase()
@@ -5009,11 +5353,15 @@ export class Dispatcher {
5009
5353
  )
5010
5354
  return
5011
5355
  }
5012
- if (!attempt.claimed || state(ticket.state) !== state(attempt.claimedState))
5013
- return await this.preparationResolved(
5356
+ if (!attempt.claimed)
5357
+ return await this.abandonPreparation(
5358
+ attempt,
5359
+ `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'}`,
5360
+ )
5361
+ if (state(ticket.state) !== state(attempt.claimedState))
5362
+ return await this.abandonPreparation(
5014
5363
  attempt,
5015
- 'abandoned',
5016
- `Uncertain claim or externally changed ticket state ${ticket.state}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
5364
+ `Confirmed claim but ticket externally changed to state ${ticket.state}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
5017
5365
  )
5018
5366
  await this.deps.tickets.transition(ref.id, handback)
5019
5367
  await this.preparationResolved(
@@ -5075,11 +5423,13 @@ export class Dispatcher {
5075
5423
  // pending work are live, only waiting on a human. Capacity is per repo
5076
5424
  // (§16.1) — another repo's builds never consume this repo's slots.
5077
5425
  const capacityBuilds = await this.capacityBuilds()
5078
- const active = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock()).occupied
5426
+ // A node awaiting verification reserves its slot ahead of new claims until
5427
+ // `admitWaitingNodes` gives it one; this only ever lowers the claim budget.
5428
+ const projection = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock())
5079
5429
  const activeRefs: TicketRef[] = capacityBuilds
5080
5430
  .filter(({ state }) => state.status !== 'done' && state.status !== 'aborted')
5081
5431
  .flatMap(({ record }) => (record.ticket ? [record.ticket] : []))
5082
- let capacity = config.capacity - active
5432
+ let capacity = intakeCapacity(projection)
5083
5433
 
5084
5434
  // The ready scan runs even at full capacity: `queued` is the operator's
5085
5435
  // standing queue-depth report and must stay honest exactly when the
@@ -5101,19 +5451,14 @@ export class Dispatcher {
5101
5451
  creation,
5102
5452
  ]),
5103
5453
  )
5104
- const ready = listing.tickets.filter(
5454
+ const eligible = listing.tickets.filter(
5105
5455
  (ticket) =>
5106
5456
  !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
5107
- !Object.values(this.store.repositoryFacts().preparation).some((attempt) => {
5108
- const ref = resolveTicketRef(
5109
- this.store.repositoryFacts().ticketMigrations,
5110
- attempt.ticket,
5111
- this.deps.tickets.name,
5112
- attempt.slug ?? attempt.attempt,
5113
- )
5114
- return ref.source === ticket.ref.source && ref.id === ticket.ref.id
5115
- }),
5457
+ !this.preparing(ticket.ref.source, ticket.ref.id),
5116
5458
  )
5459
+ // Urgent first, each class in source order (stable). Every gate below is
5460
+ // unchanged; a source without the priority capability is all normal.
5461
+ const ready = this.deps.tickets.priority ? urgentFirst(eligible) : eligible
5117
5462
  report.invalidTickets += listing.diagnostics.length
5118
5463
  report.ticketDiagnostics.push(...listing.diagnostics)
5119
5464
  report.queued = ready.length
@@ -5153,15 +5498,20 @@ export class Dispatcher {
5153
5498
  }
5154
5499
  // One dependency-node cache per scan: blockers are commonly shared across
5155
5500
  // the ready set. Never reuse ticket or dependency objects between scans.
5156
- const nodes = new Map<string, DependencyState>(
5501
+ const rejectedState = this.rejectedState()
5502
+ const nodes = new Map<string, DependencyNode>(
5157
5503
  listing.tickets.map((ticket) => [
5158
5504
  ticket.ref.id,
5159
- {
5160
- id: ticket.ref.id,
5161
- exists: true,
5162
- resolved: ticket.resolved,
5163
- blockedBy: [...(ticket.blockedBy ?? [])],
5164
- },
5505
+ markRejected(
5506
+ {
5507
+ id: ticket.ref.id,
5508
+ exists: true,
5509
+ resolved: ticket.resolved,
5510
+ ...(ticket.state !== undefined ? { state: ticket.state } : {}),
5511
+ blockedBy: [...(ticket.blockedBy ?? [])],
5512
+ },
5513
+ rejectedState,
5514
+ ),
5165
5515
  ]),
5166
5516
  )
5167
5517
 
@@ -5194,19 +5544,32 @@ export class Dispatcher {
5194
5544
  (build.digest.kind !== 'node' || build.digest.mergedSha !== undefined)
5195
5545
  )
5196
5546
  })
5197
- const destinationHeads = new Map<
5198
- string,
5199
- { branch: string; destination: string; head: string; identities: string[] }
5200
- >()
5547
+ const destinationHeads = new Map<string, PresenceObservation>()
5201
5548
  const demands: { slug: string; request: EventPayload<'node.restack-requested'> }[] = []
5202
5549
  const verdicts = new Map<string, DependencyVerdict>()
5203
5550
  const failed = new Set<string>()
5204
5551
  const targetBlocked = new Set<string>()
5205
5552
  const preflightTargets = new Map<string, string>()
5553
+ const generation = ++this.foreignScanGeneration
5554
+ for (const [id, entry] of this.foreignBranchCache)
5555
+ if (entry.scan < generation - 1) this.foreignBranchCache.delete(id)
5556
+ const targetScan: TargetScan = {
5557
+ listed: new Set(listing.tickets.map((ticket) => ticket.ref.id)),
5558
+ foreign: new Map(),
5559
+ generation,
5560
+ }
5206
5561
  for (const ticket of ready) {
5207
5562
  if (this.outOfBudget(opts)) return
5208
5563
  if (withheld.has(ticket.ref.id)) continue
5209
- const target = await this.resolveNodeTarget(ticket)
5564
+ let target: Awaited<ReturnType<Dispatcher['resolveNodeTarget']>>
5565
+ try {
5566
+ target = await this.resolveNodeTarget(ticket, targetScan)
5567
+ } catch (error) {
5568
+ if (error instanceof TicketSourceRateLimitError) {
5569
+ await this.sourceFailure(error, 'dependency-check')
5570
+ }
5571
+ throw error
5572
+ }
5210
5573
  if (typeof target === 'string') {
5211
5574
  targetBlocked.add(ticket.ref.id)
5212
5575
  report.dependencyBlocked += 1
@@ -5215,7 +5578,12 @@ export class Dispatcher {
5215
5578
  }
5216
5579
  preflightTargets.set(ticket.ref.id, JSON.stringify(target))
5217
5580
  if (this.outOfBudget(opts)) return
5218
- if ((!hasNodes && ticket.blockersResolved === true) || (ticket.blockedBy ?? []).length === 0)
5581
+ // The listing fact cannot see role names, so a configured rejected role
5582
+ // takes the batched dependency read instead of trusting it.
5583
+ if (
5584
+ (!hasNodes && rejectedState === undefined && ticket.blockersResolved === true) ||
5585
+ (ticket.blockedBy ?? []).length === 0
5586
+ )
5219
5587
  continue
5220
5588
  let verdict: DependencyVerdict
5221
5589
  try {
@@ -5274,6 +5642,7 @@ export class Dispatcher {
5274
5642
  }
5275
5643
  verdicts.set(ticket.ref.id, verdict)
5276
5644
  }
5645
+ await this.recordDestinationPresence(destinationHeads)
5277
5646
  if (this.outOfBudget(opts)) return
5278
5647
  if (failed.size === 0) {
5279
5648
  await this.sourceCondition(undefined, 'dependency-check')
@@ -5313,7 +5682,7 @@ export class Dispatcher {
5313
5682
  if (failed.has(ticket.ref.id) || targetBlocked.has(ticket.ref.id)) continue
5314
5683
  if ((verdicts.get(ticket.ref.id)?.unresolved.length ?? 0) > 0) continue
5315
5684
 
5316
- const target = await this.resolveNodeTarget(ticket)
5685
+ const target = await this.resolveNodeTarget(ticket, targetScan)
5317
5686
  if (typeof target === 'string') {
5318
5687
  report.dependencyBlocked += 1
5319
5688
  report.dependencyDiagnostics.push(`ticket ${ticket.ref.id}: ${target}`)
@@ -5416,8 +5785,9 @@ export class Dispatcher {
5416
5785
 
5417
5786
  stage = 'naming'
5418
5787
  const baseSlug = await this.chooseSlugBase(ticket.title, body)
5419
- const slug = await this.uniqueSlug(baseSlug)
5420
- const branch = `${ticket.kind === 'node' ? 'ab-node' : 'ab'}/${slug}`
5788
+ const prefix = ticket.kind === 'node' ? 'ab-node' : 'ab'
5789
+ const slug = await this.uniqueSlug(baseSlug, prefix)
5790
+ const branch = `${prefix}/${slug}`
5421
5791
  const repoOrigin = await this.resolveRepoOriginOnce()
5422
5792
  createdSeed = {
5423
5793
  ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
@@ -5432,6 +5802,9 @@ export class Dispatcher {
5432
5802
  ? { autoMergeDefaultSeq: autoMergeSeedFact.seq }
5433
5803
  : {}),
5434
5804
  assets,
5805
+ // Frozen from the same claimed ticket sample as the body (SPEC
5806
+ // "Forge issue links"); later ticket edits never reach this build.
5807
+ ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
5435
5808
  }
5436
5809
  // `build.created` rides with the record so the pinned assets and the
5437
5810
  // record exist together or not at all.
@@ -5513,6 +5886,7 @@ export class Dispatcher {
5513
5886
  */
5514
5887
  private async resolveNodeTarget(
5515
5888
  ticket: Ticket,
5889
+ scan: TargetScan,
5516
5890
  ): Promise<
5517
5891
  | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
5518
5892
  | string
@@ -5526,7 +5900,8 @@ export class Dispatcher {
5526
5900
  return `integration requires forge ${forge.name} capabilities createNodeBranch, compareBranches and remoteBranchSha; upgrade the plugin`
5527
5901
  if (ticket.target === undefined) return undefined
5528
5902
  const migrations = this.store.repositoryFacts().ticketMigrations
5529
- const entries = (await this.repoBuildDigests())
5903
+ const all = await this.repoBuildDigests()
5904
+ const entries = all
5530
5905
  .filter(
5531
5906
  ({ record }) =>
5532
5907
  record.ticket &&
@@ -5552,7 +5927,7 @@ export class Dispatcher {
5552
5927
  const latest = entries[0]
5553
5928
  if (latest && entries[1]?.record.createdAt === latest.record.createdAt)
5554
5929
  return `target node ${ticket.target} has ambiguous build generations at ${latest.record.createdAt}`
5555
- if (!latest) return `target node ${ticket.target} is not yet claimed`
5930
+ if (!latest) return this.foreignTargetDiagnostic(ticket.target, ticket.ref.source, all, scan)
5556
5931
  const { record, digest } = latest
5557
5932
  if (digest.kind !== 'node') return `target ${ticket.target} is not a node`
5558
5933
  if (digest.terminal || digest.prClosed || digest.merged)
@@ -5625,23 +6000,66 @@ export class Dispatcher {
5625
6000
  private async kernelRepository(root: string): Promise<string> {
5626
6001
  const checkout = this.deps.checkout ?? this.deps.repo
5627
6002
  if (!this.deps.repoOrigin) return checkout
6003
+ if (this.kernelGitUnavailable) throw this.kernelGitUnavailable
5628
6004
  // Origin-mode CLI wiring supplies a scratch checkout path too. Only an
5629
6005
  // actual Git repository can provide the kernel's local object database.
5630
6006
  if (this.deps.checkout) {
5631
- const probe = await this.deps.exec(['git', 'rev-parse', '--git-dir'], { cwd: checkout })
5632
- if (probe.exitCode === 0) return checkout
6007
+ const probe = await this.kernelGit(() =>
6008
+ this.deps.exec(['git', 'rev-parse', '--git-dir'], { cwd: checkout }),
6009
+ )
6010
+ if (probe.exitCode === 0) {
6011
+ await this.kernelGitRecovered()
6012
+ return checkout
6013
+ }
5633
6014
  }
5634
6015
  const path = join(root, 'repository.git')
5635
- const clone = await (this.deps.forge.kernelExec ?? this.deps.exec)(
5636
- ['git', 'clone', '--bare', this.deps.repoOrigin, path],
5637
- {
5638
- cwd: root,
5639
- },
6016
+ const clone = await this.kernelGit(() =>
6017
+ (this.deps.forge.kernelExec ?? this.deps.exec)(
6018
+ ['git', 'clone', '--bare', this.deps.repoOrigin!, path],
6019
+ { cwd: root },
6020
+ ),
5640
6021
  )
5641
6022
  if (clone.exitCode !== 0) throw new Error(clone.stderr)
6023
+ await this.kernelGitRecovered()
5642
6024
  return path
5643
6025
  }
5644
6026
 
6027
+ /** Run one kernel Git command, turning "Git cannot execute" into the
6028
+ * repository-level condition: one durable `dispatcher.kernel-git-unavailable`
6029
+ * per outage (read from the already-advanced repository projection, so a
6030
+ * fresh process does not repeat it) and a deferral for the node work. */
6031
+ private async kernelGit(run: () => Promise<ExecResult>): Promise<ExecResult> {
6032
+ let detail: string | undefined
6033
+ let result: ExecResult | undefined
6034
+ try {
6035
+ result = await run()
6036
+ detail = kernelGitUnavailableDetail({ result })
6037
+ } catch (error) {
6038
+ detail = kernelGitUnavailableDetail({ error })
6039
+ if (detail === undefined) throw error
6040
+ }
6041
+ if (detail === undefined) return result!
6042
+ this.kernelGitUnavailable = new KernelGitUnavailable('git', detail)
6043
+ if (this.store.repositoryFacts().kernelGit === undefined) {
6044
+ await this.store.ensureRepo(this.deps.repo)
6045
+ await this.store.appendRepo(this.deps.repo, {
6046
+ actor: DISPATCHER,
6047
+ type: 'dispatcher.kernel-git-unavailable',
6048
+ payload: { executable: 'git', detail },
6049
+ })
6050
+ }
6051
+ throw this.kernelGitUnavailable
6052
+ }
6053
+
6054
+ private async kernelGitRecovered(): Promise<void> {
6055
+ if (this.store.repositoryFacts().kernelGit === undefined) return
6056
+ await this.store.appendRepo(this.deps.repo, {
6057
+ actor: DISPATCHER,
6058
+ type: 'dispatcher.kernel-git-recovered',
6059
+ payload: { executable: 'git' },
6060
+ })
6061
+ }
6062
+
5645
6063
  private async withKernelRepository<T>(run: (path: string) => Promise<T>): Promise<T> {
5646
6064
  const root = await mkdtemp(join(tmpdir(), 'autobuild-node-transport-'))
5647
6065
  try {
@@ -5703,7 +6121,9 @@ export class Dispatcher {
5703
6121
  forge.remoteBranchSha(state.baseBranch),
5704
6122
  forge.remoteBranchSha(record.branch),
5705
6123
  ])
5706
- this.availabilityEntries ??= this.repoBuildDigests()
6124
+ // Landing evidence must match runNodeTransaction, which reads every
6125
+ // repository build; reading a deferred digest decides nothing for it.
6126
+ this.availabilityEntries ??= this.repoBuildDigests(true)
5707
6127
  const entries = await this.availabilityEntries
5708
6128
  this.availabilityLandings ??= confirmedLandings(entries)
5709
6129
  this.availabilityLandingKey ??= restackLandingKey(this.availabilityLandings)
@@ -5915,6 +6335,9 @@ export class Dispatcher {
5915
6335
  remote: false,
5916
6336
  branch: handle.branch,
5917
6337
  base: handle.base,
6338
+ ...(handle.restorationSkipped?.length
6339
+ ? { restorationSkipped: handle.restorationSkipped }
6340
+ : {}),
5918
6341
  },
5919
6342
  })
5920
6343
  }
@@ -5963,20 +6386,7 @@ export class Dispatcher {
5963
6386
  launched: Set<string>,
5964
6387
  sampling: { refreshOnly?: boolean } = {},
5965
6388
  ): Promise<void> {
5966
- if (
5967
- state.targetRewrite ||
5968
- state.status === 'paused' ||
5969
- state.status === 'done' ||
5970
- state.status === 'aborted' ||
5971
- state.pendingCommands.length ||
5972
- state.openEscalations.length ||
5973
- state.prState === 'merged' ||
5974
- state.prState === 'closed' ||
5975
- state.integration?.intent ||
5976
- state.nodeRestack?.parentRequest ||
5977
- state.nodeRestack?.parentChange
5978
- )
5979
- return
6389
+ if (!integrationAdmissible(state)) return
5980
6390
  const forge = this.kernelForge()
5981
6391
  if (!record.branch || !state.baseBranch || !forge.compareBranches) return
5982
6392
  const comparison = await forge.compareBranches(state.baseBranch!, record.branch!)
@@ -6161,6 +6571,9 @@ export class Dispatcher {
6161
6571
  remote: false,
6162
6572
  branch: handle.branch,
6163
6573
  base: handle.base,
6574
+ ...(handle.restorationSkipped?.length
6575
+ ? { restorationSkipped: handle.restorationSkipped }
6576
+ : {}),
6164
6577
  },
6165
6578
  })
6166
6579
  }
@@ -6198,6 +6611,10 @@ export class Dispatcher {
6198
6611
  )
6199
6612
  return
6200
6613
  let pr: Awaited<ReturnType<typeof forge.openPr>>
6614
+ // A node's PR carries its set (its own links and its landed children's
6615
+ // union) from the start, refs-only into a parent; checkPr keeps it
6616
+ // current as later children land.
6617
+ const issueLinks = nodeIssueLinksForForge(state, forge)
6201
6618
  try {
6202
6619
  pr = await forge.openPr({
6203
6620
  workspacePath: this.deps.checkout ?? this.deps.repo,
@@ -6205,6 +6622,7 @@ export class Dispatcher {
6205
6622
  base: state.baseBranch,
6206
6623
  title: `Integration: ${record.ticket?.id ?? record.slug}`,
6207
6624
  body: `Integration build ${record.slug}. Target: ${state.target?.ticket.id ?? state.baseBranch}. Human merge required.`,
6625
+ ...(issueLinks ? { issueLinks } : {}),
6208
6626
  })
6209
6627
  } catch (error) {
6210
6628
  if (
@@ -6332,95 +6750,124 @@ export class Dispatcher {
6332
6750
  }
6333
6751
  }
6334
6752
 
6753
+ /** Answer `query` for one destination with bounded, query-scoped evidence.
6754
+ * A durable probe at the sampled head that covers the questions is reused
6755
+ * without Git; otherwise one fresh walk (or this process's in-memory witness
6756
+ * at the same head) is compacted. Full witnesses are never persisted. */
6335
6757
  private async sampleDestinationPresence(
6336
6758
  branch: string,
6337
6759
  destination: string,
6338
6760
  target: { target: { build: string } } | undefined,
6339
6761
  inputs: PresenceInputs,
6340
- observations: Map<
6341
- string,
6342
- { branch: string; destination: string; head: string; identities: string[] }
6343
- >,
6344
- ) {
6345
- let observed = observations.get(destination)
6346
- if (!observed) {
6347
- const forge = this.kernelForge()
6762
+ observations: Map<string, PresenceObservation>,
6763
+ query: readonly ChangeIdentity[],
6764
+ ): Promise<PresenceObservation> {
6765
+ const aliases = destinationAliases(inputs, target?.target.build)
6766
+ const entry = observations.get(destination)
6767
+ const asked = normalizeIdentities([...(entry?.asked ?? []), ...query])
6768
+ if (entry && answers(entry.probe, query, inputs.landings, aliases)) {
6769
+ entry.asked = asked
6770
+ return entry
6771
+ }
6772
+ const forge = this.kernelForge()
6773
+ let head = entry?.head
6774
+ if (head === undefined) {
6348
6775
  if (!forge.remoteBranchSha) throw new Error('forge cannot read destination head')
6349
- const head = await forge.remoteBranchSha(branch)
6350
- const aliases = destinationAliases(inputs, target?.target.build)
6776
+ head = await forge.remoteBranchSha(branch)
6777
+ }
6778
+ const cached = this.store.repositoryFacts().presence[destination]
6779
+ let probe: PresenceProbe
6780
+ if (
6781
+ cached?.head === head &&
6782
+ cached.branch === branch &&
6783
+ cached.probe &&
6784
+ answers(cached.probe as PresenceProbe, asked, inputs.landings, aliases)
6785
+ )
6786
+ probe = cached.probe as PresenceProbe
6787
+ else {
6788
+ const memo = this.presenceWitnesses.get(destination)
6789
+ const witness =
6790
+ memo?.branch === branch && memo.head === head
6791
+ ? memo.witness
6792
+ : await this.sampleDestinationWitness(branch, head, target)
6793
+ this.presenceWitnesses.set(destination, { branch, head, witness })
6794
+ probe = compactProbe(witness, asked, inputs.landings, aliases)
6795
+ }
6796
+ const identities = projectProbe(probe, inputs.landings, aliases)
6797
+ const observed = { branch, destination, head, identities, probe, asked }
6798
+ observations.set(destination, observed)
6799
+ return observed
6800
+ }
6801
+
6802
+ /** Persist each destination's final in-tick probe once, after every ticket
6803
+ * has added its questions, and only when it differs from the durable one. */
6804
+ private async recordDestinationPresence(observations: Map<string, PresenceObservation>) {
6805
+ for (const { branch, destination, head, identities, probe } of observations.values()) {
6806
+ const evidence = probeEvidence(probe, identities)
6351
6807
  const cached = this.store.repositoryFacts().presence[destination]
6352
- if (cached?.head === head && cached.branch === branch && cached.witness?.version === 1) {
6353
- const identities = projectPresence(cached.witness, inputs.landings, aliases)
6354
- const evidence = presenceEvidence(cached.witness, identities)
6355
- observed = { ...cached, identities }
6356
- if (cached.evidence !== evidence) {
6357
- await this.store.ensureRepo(this.deps.repo)
6358
- await this.store.appendRepo(this.deps.repo, {
6359
- actor: DISPATCHER,
6360
- type: 'change-presence.observed',
6361
- payload: { ...cached, identities, evidence },
6362
- })
6363
- }
6364
- } else {
6365
- if (!forge.snapshotBase && !forge.kernelExec && !forge.rewrite)
6366
- throw new Error('forge cannot snapshot destination presence')
6367
- observed = await this.withKernelRepository(async (path) => {
6368
- const destinationRef = `refs/autobuild/reconcile/${target?.target.build ?? 'presence'}/presence`
6369
- let sampled: string
6370
- if (forge.snapshotBase)
6371
- sampled = await forge.snapshotBase({
6372
- workspacePath: path,
6373
- base: branch,
6374
- destinationRef,
6375
- })
6376
- else if (target && forge.rewrite)
6377
- sampled = await forge.rewrite.snapshot({
6378
- workspacePath: path,
6379
- branch,
6380
- destinationRef,
6381
- })
6382
- else {
6383
- const exec = forge.kernelExec ?? this.deps.exec
6384
- const fetch = await exec(
6385
- [
6386
- 'git',
6387
- 'fetch',
6388
- '--no-tags',
6389
- '--no-write-fetch-head',
6390
- '--refmap=',
6391
- 'origin',
6392
- `+refs/heads/${branch}:${destinationRef}`,
6393
- ],
6394
- { cwd: path },
6395
- )
6396
- if (fetch.exitCode !== 0) throw new Error(fetch.stderr)
6397
- const resolved = await exec(
6398
- ['git', 'rev-parse', '--verify', `${destinationRef}^{commit}`],
6399
- { cwd: path },
6400
- )
6401
- if (resolved.exitCode !== 0) throw new Error(resolved.stderr)
6402
- sampled = resolved.stdout.trim()
6403
- }
6404
- if (sampled !== head) throw new Error('destination moved while sampling presence')
6405
- const witness = await presenceWitness(
6406
- { exec: forge.kernelExec ?? this.deps.exec, workspacePath: path },
6407
- head,
6408
- )
6409
- const identities = projectPresence(witness, inputs.landings, aliases)
6410
- const evidence = presenceEvidence(witness, identities)
6411
- const payload = { branch, destination, head, evidence, identities, witness }
6412
- await this.store.ensureRepo(this.deps.repo)
6413
- await this.store.appendRepo(this.deps.repo, {
6414
- actor: DISPATCHER,
6415
- type: 'change-presence.observed',
6416
- payload,
6417
- })
6418
- return payload
6808
+ if (cached?.head === head && cached.branch === branch && cached.evidence === evidence)
6809
+ continue
6810
+ await this.store.ensureRepo(this.deps.repo)
6811
+ await this.store.appendRepo(this.deps.repo, {
6812
+ actor: DISPATCHER,
6813
+ type: 'change-presence.observed',
6814
+ payload: { branch, destination, head, evidence, identities, probe },
6815
+ })
6816
+ }
6817
+ }
6818
+
6819
+ /** One snapshot of the destination at `head` and its full in-memory witness. */
6820
+ private async sampleDestinationWitness(
6821
+ branch: string,
6822
+ head: string,
6823
+ target: { target: { build: string } } | undefined,
6824
+ ): Promise<PresenceWitness> {
6825
+ const forge = this.kernelForge()
6826
+ if (!forge.snapshotBase && !forge.kernelExec && !forge.rewrite)
6827
+ throw new Error('forge cannot snapshot destination presence')
6828
+ return this.withKernelRepository(async (path) => {
6829
+ const destinationRef = `refs/autobuild/reconcile/${target?.target.build ?? 'presence'}/presence`
6830
+ let sampled: string
6831
+ if (forge.snapshotBase)
6832
+ sampled = await forge.snapshotBase({
6833
+ workspacePath: path,
6834
+ base: branch,
6835
+ destinationRef,
6419
6836
  })
6837
+ else if (target && forge.rewrite)
6838
+ sampled = await forge.rewrite.snapshot({
6839
+ workspacePath: path,
6840
+ branch,
6841
+ destinationRef,
6842
+ })
6843
+ else {
6844
+ const exec = forge.kernelExec ?? this.deps.exec
6845
+ const fetch = await exec(
6846
+ [
6847
+ 'git',
6848
+ 'fetch',
6849
+ '--no-tags',
6850
+ '--no-write-fetch-head',
6851
+ '--refmap=',
6852
+ 'origin',
6853
+ `+refs/heads/${branch}:${destinationRef}`,
6854
+ ],
6855
+ { cwd: path },
6856
+ )
6857
+ if (fetch.exitCode !== 0) throw new Error(fetch.stderr)
6858
+ const resolved = await exec(
6859
+ ['git', 'rev-parse', '--verify', `${destinationRef}^{commit}`],
6860
+ { cwd: path },
6861
+ )
6862
+ if (resolved.exitCode !== 0) throw new Error(resolved.stderr)
6863
+ sampled = resolved.stdout.trim()
6420
6864
  }
6421
- observations.set(destination, observed)
6422
- }
6423
- return observed!
6865
+ if (sampled !== head) throw new Error('destination moved while sampling presence')
6866
+ return presenceWitness(
6867
+ { exec: forge.kernelExec ?? this.deps.exec, workspacePath: path },
6868
+ head,
6869
+ )
6870
+ })
6424
6871
  }
6425
6872
 
6426
6873
  private async presenceVerdict(
@@ -6428,13 +6875,10 @@ export class Dispatcher {
6428
6875
  target:
6429
6876
  | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
6430
6877
  | undefined,
6431
- nodes: Map<string, DependencyState>,
6878
+ nodes: Map<string, DependencyNode>,
6432
6879
  inputs: PresenceInputs,
6433
6880
  demands: { slug: string; request: EventPayload<'node.restack-requested'> }[],
6434
- observations: Map<
6435
- string,
6436
- { branch: string; destination: string; head: string; identities: string[] }
6437
- >,
6881
+ observations: Map<string, PresenceObservation>,
6438
6882
  ): Promise<DependencyVerdict> {
6439
6883
  const branch = target?.branch ?? this.deps.config.baseBranch
6440
6884
  const destination = target?.target.build ?? `root:${branch}`
@@ -6452,7 +6896,13 @@ export class Dispatcher {
6452
6896
  this.deps.tickets.name,
6453
6897
  ),
6454
6898
  )
6455
- if (id === ticket.ref.id || !nodes.get(id)?.exists || build === undefined) {
6899
+ // A rejected blocker's diagnostic wins over any build it once had.
6900
+ if (
6901
+ id === ticket.ref.id ||
6902
+ !nodes.get(id)?.exists ||
6903
+ nodes.get(id)?.rejected ||
6904
+ build === undefined
6905
+ ) {
6456
6906
  fallback.push(id)
6457
6907
  continue
6458
6908
  }
@@ -6496,6 +6946,7 @@ export class Dispatcher {
6496
6946
  target,
6497
6947
  inputs,
6498
6948
  observations,
6949
+ normalizeIdentities([...required.values()].flat()),
6499
6950
  )
6500
6951
  const missing = [
6501
6952
  ...new Set(
@@ -6523,6 +6974,7 @@ export class Dispatcher {
6523
6974
  slug ? { target: { build: slug } } : undefined,
6524
6975
  inputs,
6525
6976
  observations,
6977
+ missing,
6526
6978
  )
6527
6979
  path.push({ ...(slug ? { slug } : {}), ...parent })
6528
6980
  if (missing.every((id) => path.some((entry) => entry.identities.includes(id)))) break
@@ -6568,7 +7020,7 @@ export class Dispatcher {
6568
7020
 
6569
7021
  private async loadDependencyGraph(
6570
7022
  ticket: Ticket,
6571
- nodes: Map<string, DependencyState>,
7023
+ nodes: Map<string, DependencyNode>,
6572
7024
  opts: TickOpts = {},
6573
7025
  builtTickets?: ReadonlySet<string>,
6574
7026
  ): Promise<boolean> {
@@ -6579,7 +7031,8 @@ export class Dispatcher {
6579
7031
  const uncached = frontier.filter((id) => !nodes.has(id))
6580
7032
  if (uncached.length > 0) {
6581
7033
  const states = await this.deps.tickets.dependencyStates(uncached)
6582
- for (const state of states) nodes.set(state.id, state)
7034
+ const rejectedState = this.rejectedState()
7035
+ for (const state of states) nodes.set(state.id, markRejected(state, rejectedState))
6583
7036
  }
6584
7037
  const next: string[] = []
6585
7038
  for (const id of frontier) {
@@ -6643,12 +7096,106 @@ export class Dispatcher {
6643
7096
  }
6644
7097
  }
6645
7098
 
6646
- /** Valid bounded base, deduped store-wide with -2/-3/… suffixes. */
6647
- private async uniqueSlug(base: string): Promise<string> {
6648
- let slug = base
6649
- for (let n = 2; (await this.store.getBuild(slug)) !== null; n += 1) {
6650
- slug = `${base}-${n}`
7099
+ /** Whether this store has an unresolved preparation attempt for the ticket. */
7100
+ private preparing(source: string, id: string): boolean {
7101
+ const facts = this.store.repositoryFacts()
7102
+ return Object.values(facts.preparation).some((attempt) => {
7103
+ const ref = resolveTicketRef(
7104
+ facts.ticketMigrations,
7105
+ attempt.ticket,
7106
+ this.deps.tickets.name,
7107
+ attempt.slug ?? attempt.attempt,
7108
+ )
7109
+ return ref.source === source && ref.id === id
7110
+ })
7111
+ }
7112
+
7113
+ /**
7114
+ * A target node with no build in this store is either not yet claimed or
7115
+ * being built by another store (AUT-1106). One ticket read per distinct
7116
+ * target per admission scan; the forge branch lookup runs only when the
7117
+ * target's revision or foreign dispatch-comment slugs change. Never fails
7118
+ * admission: read failures fall back to the not-yet-claimed text.
7119
+ */
7120
+ private foreignTargetDiagnostic(
7121
+ target: string,
7122
+ source: string,
7123
+ all: readonly { record: BuildRecord }[],
7124
+ scan: TargetScan,
7125
+ ): Promise<string> {
7126
+ const pending = `target node ${target} is not yet claimed`
7127
+ if (scan.listed.has(target) || this.preparing(source, target)) return Promise.resolve(pending)
7128
+ const memo = scan.foreign.get(target)
7129
+ if (memo !== undefined) return memo
7130
+ const share = 'dispatchers on one repository must share one store (ab connect)'
7131
+ const verdict = (async () => {
7132
+ let ticket: Ticket | null
7133
+ try {
7134
+ ticket = await this.deps.tickets.get(target)
7135
+ } catch (error) {
7136
+ if (error instanceof TicketSourceRateLimitError) throw error
7137
+ return pending
7138
+ }
7139
+ if (ticket === null) return pending
7140
+ const doing = ticketLifecycle(this.deps.config.tickets).doing
7141
+ if (!ticket.resolved && ticket.state?.toLowerCase() === doing.toLowerCase())
7142
+ return `target node ${target} is being built by another store: its ticket is claimed (${ticket.state}) but this store has no build for it; ${share}`
7143
+ const forge = this.deps.forge
7144
+ const exists = forge.remoteBranchExists
7145
+ if (ticket.comments === undefined || exists === undefined) return pending
7146
+ // Only a node branch this store owns is not evidence of another store:
7147
+ // separate stores may reuse a slug for unrelated tickets or prefixes.
7148
+ const owned = new Set(all.flatMap(({ record }) => record.branch ?? []))
7149
+ const slugs = [
7150
+ ...new Set(
7151
+ [...ticket.comments]
7152
+ .reverse()
7153
+ .flatMap((comment) => DISPATCH_COMMENT.exec(comment.body)?.[1] ?? [])
7154
+ .filter((slug) => !owned.has(`ab-node/${slug}`)),
7155
+ ),
7156
+ ]
7157
+ if (slugs.length === 0) return pending
7158
+ const fingerprint = `${ticket.revision}\n${[...slugs].sort().join(',')}`
7159
+ const cached = this.foreignBranchCache.get(target)
7160
+ let branch: string | null
7161
+ if (cached?.fingerprint === fingerprint) {
7162
+ cached.scan = scan.generation
7163
+ branch = cached.branch
7164
+ } else {
7165
+ branch = null
7166
+ try {
7167
+ for (const slug of slugs) {
7168
+ if (await exists.call(forge, `ab-node/${slug}`)) {
7169
+ branch = `ab-node/${slug}`
7170
+ break
7171
+ }
7172
+ }
7173
+ } catch {
7174
+ return pending
7175
+ }
7176
+ this.foreignBranchCache.set(target, { fingerprint, branch, scan: scan.generation })
7177
+ }
7178
+ return branch === null
7179
+ ? pending
7180
+ : `target node ${target} is being built by another store: its branch ${branch} exists on the remote but this store has no build for it; ${share}`
7181
+ })()
7182
+ scan.foreign.set(target, verdict)
7183
+ return verdict
7184
+ }
7185
+
7186
+ /** Valid bounded base, deduped with -2/-3/… against this store's builds and,
7187
+ * when the forge can answer, against build branches already on the remote
7188
+ * (another store's builds, AUT-1106). Claim-time only; a forge failure fails
7189
+ * the naming stage and the claim is handed back. */
7190
+ private async uniqueSlug(base: string, prefix: 'ab' | 'ab-node'): Promise<string> {
7191
+ const forge = this.deps.forge
7192
+ const exists = forge.remoteBranchExists
7193
+ for (let n = 1; n <= MAX_SLUG_CANDIDATES; n += 1) {
7194
+ const slug = n === 1 ? base : `${base}-${n}`
7195
+ if ((await this.store.getBuild(slug)) !== null) continue
7196
+ if (exists !== undefined && (await exists.call(forge, `${prefix}/${slug}`))) continue
7197
+ return slug
6651
7198
  }
6652
- return slug
7199
+ throw new Error(`no free slug for ${base} after ${MAX_SLUG_CANDIDATES} candidates`)
6653
7200
  }
6654
7201
  }