@defrex/autobuild 1.4.2 → 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 +432 -92
  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 +282 -127
  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 +163 -102
  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 +4 -3
  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 +190 -9
  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 +118 -27
  153. package/packages/core/src/processes/build-runner.ts +99 -21
  154. package/packages/core/src/processes/dispatcher.ts +822 -338
  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 +36 -1
  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 +11 -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 +1085 -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 +374 -136
  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 { 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
@@ -753,6 +829,21 @@ export class Dispatcher {
753
829
  }
754
830
  >()
755
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
+ >()
756
847
 
757
848
  private async integrationClaimKey(slug: string, state: BuildState): Promise<string> {
758
849
  return nodeTicketObservationKey(state, await this.nodePollingChildren(slug))
@@ -761,6 +852,9 @@ export class Dispatcher {
761
852
  const children: { slug: string; state: Pick<BuildState, 'pollingActivity'> }[] = []
762
853
  for (const { record, digest } of await this.repoBuildDigests()) {
763
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
764
858
  const known = this.nodePollingBuilds.get(record.slug)
765
859
  // Only node relationships can move. Unrelated known work never needs
766
860
  // another full-facts read, even while it is running.
@@ -798,22 +892,29 @@ export class Dispatcher {
798
892
  }
799
893
 
800
894
  private observeIntegration(slug: string, publication = false) {
801
- return observeIntegration(this.store, this.deps.tickets, slug, () => {
802
- if (publication) {
803
- 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(
804
910
  this.store,
805
911
  this.deps.tickets,
806
912
  this.deps.repo,
807
913
  )
808
- return this.integrationPublicationInputs
809
- }
810
- this.integrationInputs ??= integrationObservationInputs(
811
- this.store,
812
- this.deps.tickets,
813
- this.deps.repo,
814
- )
815
- return this.integrationInputs
816
- })
914
+ return this.integrationInputs
915
+ },
916
+ rejectedState === undefined ? {} : { rejectedState },
917
+ )
817
918
  }
818
919
 
819
920
  // Disposable parsed pins only. Current facts, live policy and cycle captures
@@ -924,7 +1025,7 @@ export class Dispatcher {
924
1025
  private get doneState(): string {
925
1026
  return (
926
1027
  this.deps.opts?.doneState ??
927
- (this.deps.config.tickets.source === 'hosted'
1028
+ (this.deps.config.tickets.source === 'hosted' || this.deps.config.tickets.source === 'github'
928
1029
  ? ticketLifecycle(this.deps.config.tickets).done
929
1030
  : undefined) ??
930
1031
  'Done'
@@ -938,10 +1039,15 @@ export class Dispatcher {
938
1039
  private readonly continuations = new Map<string, ProvisionContinuation>()
939
1040
 
940
1041
  // Batched confirmed landing evidence is shared across nodes for this tick.
941
- // 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.
942
1045
  private availabilityLandings?: ReturnType<typeof confirmedLandings>
943
1046
  private availabilityLandingKey?: string
944
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
945
1051
 
946
1052
  /** The incremental repository view every stage reads and writes through
947
1053
  * (AUT-647): `deps.store` itself when the caller already wrapped it. */
@@ -997,6 +1103,8 @@ export class Dispatcher {
997
1103
 
998
1104
  lastForgeRequests?: import('../ports/forge-telemetry').ForgeRequestCounts
999
1105
  async tick(opts: TickOpts = {}): Promise<TickReport> {
1106
+ this.kernelGitUnavailable = undefined
1107
+ this.tickAbandonments = []
1000
1108
  this.availabilityEntries = undefined
1001
1109
  this.availabilityLandings = undefined
1002
1110
  this.availabilityLandingKey = undefined
@@ -1031,13 +1139,38 @@ export class Dispatcher {
1031
1139
  ? this.deps.forge.withReadScope(() => this.runTick(opts))
1032
1140
  : this.runTick(opts))
1033
1141
  if (stop || this.deps.config.forge === 'local-git') report.forgeRequests = counts()
1142
+ report.janitorDiagnostics.push(...this.tickAbandonments)
1034
1143
  return report
1144
+ } catch (error) {
1145
+ throw this.withTickAbandonments(error)
1035
1146
  } finally {
1147
+ this.tickAbandonments = []
1036
1148
  if (stop || this.deps.config.forge === 'local-git') this.lastForgeRequests = counts()
1037
1149
  stop?.()
1038
1150
  }
1039
1151
  }
1040
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
+
1041
1174
  private async runTick(opts: TickOpts): Promise<TickReport> {
1042
1175
  this.integrationInputs = undefined
1043
1176
  this.integrationPublicationInputs = undefined
@@ -1092,6 +1225,10 @@ export class Dispatcher {
1092
1225
  if (this.outOfBudget(opts)) return report
1093
1226
  await this.leaseSweep(report, launched, paused, opts)
1094
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
1095
1232
  if (opts.acceptNewWork !== false) {
1096
1233
  await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1097
1234
  }
@@ -1112,6 +1249,11 @@ export class Dispatcher {
1112
1249
  return this.deps.opts?.triageState ?? defaultTriageState(this.deps.config)
1113
1250
  }
1114
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
+
1115
1257
  /** This repository's builds paired with their digests, from one record
1116
1258
  * listing and one digest read — the tick loops' per-build event reads start
1117
1259
  * from here so a settled terminal build costs none. Records are read before
@@ -1366,34 +1508,21 @@ export class Dispatcher {
1366
1508
  const readinessFingerprint = hash(digest)
1367
1509
  const criteriaFingerprint = hash(readyCriteria(this.deps.config))
1368
1510
  const startedAt = this.deps.clock().toISOString()
1369
- const previous = this.latestScan()
1370
- const cached = await this.store.getScanCadence(this.deps.repo)
1371
- // Outcomes always come from the reduction. This row only acknowledges their cadence.
1372
- const valid =
1373
- previous !== undefined &&
1374
- cached !== null &&
1375
- cached.scanSeq === this.store.repositoryFacts().scanSeq &&
1376
- cached.mode === previous.mode &&
1377
- cached.readinessFingerprint === previous.readinessFingerprint &&
1378
- cached.criteriaFingerprint === previous.criteriaFingerprint &&
1379
- Number.isFinite(Date.parse(cached.startedAt))
1380
- const baseline = valid ? cached : previous
1381
- const elapsed =
1382
- baseline === undefined ? Infinity : Date.parse(startedAt) - Date.parse(baseline.startedAt)
1383
- return {
1384
- startedAt,
1511
+ const input = {
1512
+ previous: this.latestScan(),
1513
+ previousSeq: this.store.repositoryFacts().scanSeq,
1385
1514
  mode,
1386
1515
  readinessFingerprint,
1387
1516
  criteriaFingerprint,
1388
- allowClockRollback: elapsed < 0,
1389
- due:
1390
- previous === undefined ||
1391
- elapsed < 0 ||
1392
- elapsed >= this.deps.config.ticketScanIntervalSeconds * 1000 ||
1393
- previous.readinessFingerprint !== readinessFingerprint ||
1394
- previous.criteriaFingerprint !== criteriaFingerprint ||
1395
- (mode === 'admission' && previous.mode === 'observation'),
1517
+ startedAt,
1518
+ intervalMs: this.deps.config.ticketScanIntervalSeconds * 1000,
1396
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) }
1397
1526
  }
1398
1527
 
1399
1528
  private async completeScan(
@@ -1496,8 +1625,11 @@ export class Dispatcher {
1496
1625
  return
1497
1626
  }
1498
1627
  // Bounded subset (AUT-489): the harvest reducer consumes durable types only.
1499
- const state = this.store.repositoryFacts().harvest
1500
- 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') {
1501
1633
  start()
1502
1634
  }
1503
1635
  }
@@ -1537,6 +1669,13 @@ export class Dispatcher {
1537
1669
  const branch = facts.lastCreated.payload.baseBranch
1538
1670
  await this.observeTarget(slug, branch, undefined, report)
1539
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> {
1540
1679
  if (
1541
1680
  !(await ensureExecutionProgress(
1542
1681
  this.store,
@@ -1605,10 +1744,12 @@ export class Dispatcher {
1605
1744
  * owning provider. `lost`/`ended` reaps the disposable environment and
1606
1745
  * journals the close fact with the snapshot purge outcome; `running`
1607
1746
  * leaves it — the guest is the live supervisor and holds the adopted
1608
- * repository lease, and the next pass reaps it after it ends. The run
1609
- * itself needs no settlement here: an interrupted run stays open in the
1610
- * journal and the next threshold-triggered harvest resumes it under the
1611
- * 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. */
1612
1753
  private async settleHarvestExecutions(opts: TickOpts = {}): Promise<void> {
1613
1754
  const active = this.deps.activeHarvestExecutions?.() ?? new Set<string>()
1614
1755
  const facts = this.store.repositoryFacts()
@@ -1695,6 +1836,22 @@ export class Dispatcher {
1695
1836
  }
1696
1837
  }
1697
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
+
1698
1855
  /** Durable idle settlement for operator sandboxes (AUT-340), staged after
1699
1856
  * harvest settlement: every journal-live environment whose latest evidence
1700
1857
  * is older than `[orchestrator].sandbox.idleMinutes` is stopped through the
@@ -1995,6 +2152,9 @@ export class Dispatcher {
1995
2152
  remote: workspaces.publication !== undefined,
1996
2153
  branch: handle.branch,
1997
2154
  base: handle.base,
2155
+ ...(handle.restorationSkipped?.length
2156
+ ? { restorationSkipped: handle.restorationSkipped }
2157
+ : {}),
1998
2158
  },
1999
2159
  } satisfies EventWrite<'workspace.provisioned'>)
2000
2160
  // Release before the launch: the launcher re-claims the lease under the
@@ -2013,7 +2173,7 @@ export class Dispatcher {
2013
2173
  const queued = (await readBuildFacts(store, slug)).value.state.status === 'queued'
2014
2174
  boundary = input.tail === 'dispatch' || queued ? 'dispatch' : 'launch'
2015
2175
  if (boundary === 'dispatch') await this.completeDispatchBoundaries(record, input.seed)
2016
- else if (this.accountsAvailable()) await this.deps.launchRunner(slug)
2176
+ else if (this.accountsAvailable()) await this.startRunner(slug, emptyTickReport())
2017
2177
  } catch (error) {
2018
2178
  // Dispatch boundaries own their failure facts and exhaustion repair.
2019
2179
  // A failed tail read/write leaves durable unfinished work for the next
@@ -2496,11 +2656,7 @@ export class Dispatcher {
2496
2656
  forge: this.deps.forge,
2497
2657
  })
2498
2658
  } catch (error) {
2499
- if (
2500
- error instanceof ForgeRequestDeferred ||
2501
- (isForgeFailure(error) && error.details.kind === 'rate-limited')
2502
- )
2503
- throw error
2659
+ if (janitorDeferral(error)) throw error
2504
2660
  if (facts.log.restack.distance?.count != null)
2505
2661
  report.janitorDiagnostics.push(
2506
2662
  `build ${record.slug}: target distance failed — ${error instanceof Error ? error.message : String(error)}`,
@@ -2549,7 +2705,10 @@ export class Dispatcher {
2549
2705
  }
2550
2706
  await completeNodePoll()
2551
2707
  } catch (error) {
2552
- 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)) {
2553
2712
  attempted = false
2554
2713
  return
2555
2714
  }
@@ -2598,11 +2757,7 @@ export class Dispatcher {
2598
2757
  })
2599
2758
  return true
2600
2759
  } catch (error) {
2601
- if (
2602
- error instanceof ForgeRequestDeferred ||
2603
- (isForgeFailure(error) && error.details.kind === 'rate-limited')
2604
- )
2605
- throw error
2760
+ if (janitorDeferral(error)) throw error
2606
2761
  report.janitorDiagnostics.push(
2607
2762
  `build ${record.slug}: node read priming failed — ${error instanceof Error || isForgeFailure(error) ? error.message : String(error)}`,
2608
2763
  )
@@ -2905,6 +3060,46 @@ export class Dispatcher {
2905
3060
  return builds
2906
3061
  }
2907
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
+
2908
3103
  private async nodeHasCapacity(slug: string): Promise<boolean> {
2909
3104
  const builds = await this.capacityBuilds()
2910
3105
  return (
@@ -2927,6 +3122,25 @@ export class Dispatcher {
2927
3122
  /** Complete abort cleanup as an ordered checkpointed saga. External effects
2928
3123
  * are idempotent; a fact after each one prevents already-settled work from
2929
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
+
2930
3144
  private async cleanupAborted(
2931
3145
  record: BuildRecord,
2932
3146
  events: CurrentBuildFacts,
@@ -3047,6 +3261,9 @@ export class Dispatcher {
3047
3261
  }
3048
3262
  }
3049
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
+
3050
3267
  try {
3051
3268
  const released = await this.releaseWorkspace(record.slug, events, 'abort')
3052
3269
  if (released !== undefined)
@@ -3265,6 +3482,21 @@ export class Dispatcher {
3265
3482
  throw new Error('node-target native auto-merge cancellation unconfirmed')
3266
3483
  nativeCancelled = true
3267
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
+ }
3268
3500
  // Converge native state on every poll, including paused and unready builds.
3269
3501
  // A replacement publication invalidates readiness, even if a stale enable
3270
3502
  // finished after the publisher confirmed cancellation.
@@ -3613,17 +3845,24 @@ export class Dispatcher {
3613
3845
  sameLandingCandidate(native.candidate, state.landing?.decision?.candidate)
3614
3846
  ? native.retry
3615
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
3616
3857
  if (
3617
3858
  !integration &&
3618
3859
  !nodeTarget &&
3619
3860
  prState.state === 'open' &&
3620
3861
  landingAuthorized(state.landing) &&
3621
- (prState.nativeAutoMerge === false ||
3622
- !nativeLandingApplied(state.landing) ||
3623
- !!state.landing?.nativeEnablePending) &&
3862
+ (prState.nativeAutoMerge === false || !acknowledged || maintain) &&
3624
3863
  (!retry || Date.parse(retry.after) <= this.deps.clock().getTime()) &&
3625
3864
  commandSeq !== undefined &&
3626
- (await canApply())
3865
+ (maintain || (await canApply()))
3627
3866
  ) {
3628
3867
  const decision = state.landing!.decision!
3629
3868
  // The provider checks eligibility immediately before mutating. Inspection
@@ -3654,103 +3893,116 @@ export class Dispatcher {
3654
3893
  },
3655
3894
  })
3656
3895
  }
3657
- const result =
3658
- prState.nativeAutoMerge === true && !nativeCancelled
3659
- ? { kind: 'applied' as const }
3660
- : await forge
3661
- .setAutoMerge(workspacePath, pr.number, true, {
3662
- buildSlug: record.slug,
3663
- baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
3664
- canApply: async () => {
3665
- if (!(await canApply())) return false
3666
- if (enableSeq === undefined)
3667
- enableSeq = (
3668
- await store.append(record.slug, {
3669
- actor: DISPATCHER,
3670
- type: 'landing.native-enable-started',
3671
- payload: {},
3672
- })
3673
- ).seq
3674
- return true
3675
- },
3676
- })
3677
- .catch(async (error: unknown) => {
3678
- if (isForgeFailure(error)) {
3679
- const attempt = (retry?.attempt ?? 0) + 1
3680
- await store.append(record.slug, {
3681
- actor: DISPATCHER,
3682
- type: 'landing.application-failed',
3683
- payload: {
3684
- candidate: decision.candidate,
3685
- decisionSeq: decision.seq,
3686
- ...(state.landing?.command ? { commandSeq: state.landing.command.seq } : {}),
3687
- message: error.message,
3688
- attempt,
3689
- after: new Date(
3690
- Math.max(
3691
- this.deps.clock().getTime() +
3692
- Math.min(300_000, 30_000 * 2 ** Math.min(attempt - 1, 4)),
3693
- error.details.kind === 'rate-limited'
3694
- ? Date.parse(error.details.resetAt)
3695
- : 0,
3696
- ),
3697
- ).toISOString(),
3698
- },
3699
- })
3700
- // An uncertain enable stays pending. Never spend another request during a limit.
3701
- throw error
3702
- }
3703
- await settleFailedEnable()
3704
- throw error
3705
- })
3706
- // Only an attempt that reached the mutation guard needs cancellation.
3707
- // Persist retry timing with its receipt so restart cannot reset backoff.
3708
- if (result.kind !== 'applied') await settleFailedEnable()
3709
- if (result.kind === 'applied') {
3710
- const latest = (await store.buildFacts(record.slug)).state
3711
- if (await canApply()) {
3712
- if (
3713
- latest.landing?.nativeEnablePending ||
3714
- latest.landing?.native?.enabled !== true ||
3715
- latest.landing.native.decisionSeq !== decision.seq ||
3716
- latest.landing.native.commandSeq !== latest.landing.command?.seq
3717
- )
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
3718
3919
  await store.append(record.slug, {
3719
3920
  actor: DISPATCHER,
3720
- type: 'landing.native-applied',
3921
+ type: 'landing.application-failed',
3721
3922
  payload: {
3722
- enabled: true,
3723
- ...(enableSeq !== undefined ? { enableSeq } : {}),
3724
3923
  candidate: decision.candidate,
3725
3924
  decisionSeq: decision.seq,
3726
- ...(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(),
3727
3935
  },
3728
3936
  })
3729
- } else {
3730
- // Enable may have won after cancellation. Repair immediately, and
3731
- // again on the next poll if this process dies at this boundary.
3732
- const cancelled = await forge.setAutoMerge(workspacePath, pr.number, false)
3733
- if (cancelled.kind === 'applied')
3734
- await store.append(record.slug, {
3735
- actor: DISPATCHER,
3736
- type: 'landing.native-applied',
3737
- payload: { enabled: false, ...(enableSeq !== undefined ? { enableSeq } : {}) },
3738
- })
3739
- }
3740
- } else if (result.kind === 'deferred' && result.reason) {
3741
- await recordAutoMergeDeferralObservation(
3742
- store,
3743
- record.slug,
3744
- result.reason,
3745
- pr.number,
3746
- commandSeq,
3747
- this.deps.ids('obs'),
3748
- )
3749
- } else if (result.kind === 'ungated' && prState.mergeable === true && (await canApply())) {
3750
- await forge.squashMerge(workspacePath, pr.number, result.headSha, {
3751
- buildSlug: record.slug,
3752
- 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
3753
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
+ }
3754
4006
  }
3755
4007
  }
3756
4008
 
@@ -3865,6 +4117,9 @@ export class Dispatcher {
3865
4117
  payload: await this.mergeEvidence(record, workspacePath, prState.sha, state.kind),
3866
4118
  } satisfies EventWrite<'pr.merged'>)
3867
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)
3868
4123
  await this.releaseWorkspace(record.slug, events)
3869
4124
  if (record.ticket) {
3870
4125
  await tickets.transition(await this.currentTicketId(record), this.doneState)
@@ -3972,11 +4227,21 @@ export class Dispatcher {
3972
4227
  input: Parameters<WorkspaceProvider['provision']>[0],
3973
4228
  ) {
3974
4229
  const facts = (await readBuildFacts(this.store, slug)).value
4230
+ const { restoration, superseded } = supersedeRestorationHeads(
4231
+ facts.workspacePreservation?.payload.heads,
4232
+ facts.replacedHeads,
4233
+ )
3975
4234
  try {
3976
- return await this.deps.workspaces.provision({
4235
+ const handle = await this.deps.workspaces.provision({
3977
4236
  ...input,
3978
- restoration: facts.workspacePreservation?.payload.heads,
4237
+ restoration,
4238
+ ...(facts.replacedHeads.length ? { restorationReplaced: facts.replacedHeads } : {}),
3979
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
3980
4245
  } catch (error) {
3981
4246
  if (error instanceof WorkspaceCleanupRequired) {
3982
4247
  await this.store.append(slug, {
@@ -4267,8 +4532,9 @@ export class Dispatcher {
4267
4532
 
4268
4533
  // ── b. Interrupted dispatch recovery ───────────────────────────────────────
4269
4534
 
4270
- /** The claim-time `build.created` payload. Assets are omitted when the ticket
4271
- * 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. */
4272
4538
  private buildCreatedPayload(
4273
4539
  ticket: TicketRef,
4274
4540
  repo: string,
@@ -4277,6 +4543,7 @@ export class Dispatcher {
4277
4543
  autoMergeUser?: string
4278
4544
  autoMergeDefaultSeq?: number
4279
4545
  assets?: PinnedAsset[]
4546
+ issueLinks?: IssueLink[]
4280
4547
  kind?: 'work' | 'node'
4281
4548
  target?: EventPayload<'build.created'>['target']
4282
4549
  baseBranch?: string
@@ -4296,6 +4563,9 @@ export class Dispatcher {
4296
4563
  : {}),
4297
4564
  ...(config.pr !== undefined ? { pr: config.pr } : {}),
4298
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
+ : {}),
4299
4569
  }
4300
4570
  }
4301
4571
 
@@ -4359,7 +4629,13 @@ export class Dispatcher {
4359
4629
  await store.appendIfCurrent(record.slug, 0, {
4360
4630
  actor: DISPATCHER,
4361
4631
  type: 'build.created',
4362
- 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
+ }),
4363
4639
  })
4364
4640
  events = (await readBuildFacts(store, record.slug)).value
4365
4641
  if (events.created === undefined) {
@@ -4426,6 +4702,9 @@ export class Dispatcher {
4426
4702
  remote: this.deps.workspaces.publication !== undefined,
4427
4703
  branch: handle.branch,
4428
4704
  base: handle.base,
4705
+ ...(handle.restorationSkipped?.length
4706
+ ? { restorationSkipped: handle.restorationSkipped }
4707
+ : {}),
4429
4708
  },
4430
4709
  } satisfies EventWrite<'workspace.provisioned'>)
4431
4710
  events = (await readBuildFacts(store, record.slug)).value
@@ -4551,7 +4830,7 @@ export class Dispatcher {
4551
4830
  if (record.ticket !== undefined && !events.commentPosted) {
4552
4831
  await this.deps.tickets.comment(
4553
4832
  await this.currentTicketId(record),
4554
- `build ${record.slug} dispatched`,
4833
+ dispatchCommentBody(record.slug),
4555
4834
  )
4556
4835
  await store.append(record.slug, {
4557
4836
  actor: DISPATCHER,
@@ -4579,7 +4858,7 @@ export class Dispatcher {
4579
4858
  return 'parked'
4580
4859
  }
4581
4860
  if (!this.accountsAvailable()) return 'parked'
4582
- if (launched === undefined) await this.deps.launchRunner(record.slug)
4861
+ if (launched === undefined) await this.startRunner(record.slug, report ?? emptyTickReport())
4583
4862
  else await this.launch(record.slug, launched, report)
4584
4863
  if (authored && report !== undefined) report.authored += 1
4585
4864
  return 'completed'
@@ -5019,6 +5298,14 @@ export class Dispatcher {
5019
5298
  })
5020
5299
  }
5021
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
+
5022
5309
  private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
5023
5310
  try {
5024
5311
  // A rejected create can have committed. Unavailable or conflicting readback
@@ -5035,9 +5322,8 @@ export class Dispatcher {
5035
5322
  created.payload.ticket?.source !== attempt.ticket.source ||
5036
5323
  created.payload.ticket?.id !== attempt.ticket.id
5037
5324
  )
5038
- return await this.preparationResolved(
5325
+ return await this.abandonPreparation(
5039
5326
  attempt,
5040
- 'abandoned',
5041
5327
  `Conflicting build ownership at ${attempt.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
5042
5328
  )
5043
5329
  await this.preparationResolved(attempt, 'owned')
@@ -5052,15 +5338,10 @@ export class Dispatcher {
5052
5338
  )
5053
5339
  const ticket = await this.deps.tickets.get(ref.id)
5054
5340
  if (!ticket)
5055
- return await this.preparationResolved(
5056
- attempt,
5057
- 'abandoned',
5058
- 'Ticket no longer exists; ticket unchanged.',
5059
- )
5341
+ return await this.abandonPreparation(attempt, 'Ticket no longer exists; ticket unchanged.')
5060
5342
  if (ticket.state === undefined)
5061
- return await this.preparationResolved(
5343
+ return await this.abandonPreparation(
5062
5344
  attempt,
5063
- 'abandoned',
5064
5345
  'Ticket state is unavailable; ticket unchanged. Inspect the provider record before manually retrying.',
5065
5346
  )
5066
5347
  const state = (value: string) => value.toLowerCase()
@@ -5072,11 +5353,15 @@ export class Dispatcher {
5072
5353
  )
5073
5354
  return
5074
5355
  }
5075
- if (!attempt.claimed || state(ticket.state) !== state(attempt.claimedState))
5076
- 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(
5077
5363
  attempt,
5078
- 'abandoned',
5079
- `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'}`,
5080
5365
  )
5081
5366
  await this.deps.tickets.transition(ref.id, handback)
5082
5367
  await this.preparationResolved(
@@ -5138,11 +5423,13 @@ export class Dispatcher {
5138
5423
  // pending work are live, only waiting on a human. Capacity is per repo
5139
5424
  // (§16.1) — another repo's builds never consume this repo's slots.
5140
5425
  const capacityBuilds = await this.capacityBuilds()
5141
- 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())
5142
5429
  const activeRefs: TicketRef[] = capacityBuilds
5143
5430
  .filter(({ state }) => state.status !== 'done' && state.status !== 'aborted')
5144
5431
  .flatMap(({ record }) => (record.ticket ? [record.ticket] : []))
5145
- let capacity = config.capacity - active
5432
+ let capacity = intakeCapacity(projection)
5146
5433
 
5147
5434
  // The ready scan runs even at full capacity: `queued` is the operator's
5148
5435
  // standing queue-depth report and must stay honest exactly when the
@@ -5164,19 +5451,14 @@ export class Dispatcher {
5164
5451
  creation,
5165
5452
  ]),
5166
5453
  )
5167
- const ready = listing.tickets.filter(
5454
+ const eligible = listing.tickets.filter(
5168
5455
  (ticket) =>
5169
5456
  !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
5170
- !Object.values(this.store.repositoryFacts().preparation).some((attempt) => {
5171
- const ref = resolveTicketRef(
5172
- this.store.repositoryFacts().ticketMigrations,
5173
- attempt.ticket,
5174
- this.deps.tickets.name,
5175
- attempt.slug ?? attempt.attempt,
5176
- )
5177
- return ref.source === ticket.ref.source && ref.id === ticket.ref.id
5178
- }),
5457
+ !this.preparing(ticket.ref.source, ticket.ref.id),
5179
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
5180
5462
  report.invalidTickets += listing.diagnostics.length
5181
5463
  report.ticketDiagnostics.push(...listing.diagnostics)
5182
5464
  report.queued = ready.length
@@ -5216,15 +5498,20 @@ export class Dispatcher {
5216
5498
  }
5217
5499
  // One dependency-node cache per scan: blockers are commonly shared across
5218
5500
  // the ready set. Never reuse ticket or dependency objects between scans.
5219
- const nodes = new Map<string, DependencyState>(
5501
+ const rejectedState = this.rejectedState()
5502
+ const nodes = new Map<string, DependencyNode>(
5220
5503
  listing.tickets.map((ticket) => [
5221
5504
  ticket.ref.id,
5222
- {
5223
- id: ticket.ref.id,
5224
- exists: true,
5225
- resolved: ticket.resolved,
5226
- blockedBy: [...(ticket.blockedBy ?? [])],
5227
- },
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
+ ),
5228
5515
  ]),
5229
5516
  )
5230
5517
 
@@ -5257,19 +5544,32 @@ export class Dispatcher {
5257
5544
  (build.digest.kind !== 'node' || build.digest.mergedSha !== undefined)
5258
5545
  )
5259
5546
  })
5260
- const destinationHeads = new Map<
5261
- string,
5262
- { branch: string; destination: string; head: string; identities: string[] }
5263
- >()
5547
+ const destinationHeads = new Map<string, PresenceObservation>()
5264
5548
  const demands: { slug: string; request: EventPayload<'node.restack-requested'> }[] = []
5265
5549
  const verdicts = new Map<string, DependencyVerdict>()
5266
5550
  const failed = new Set<string>()
5267
5551
  const targetBlocked = new Set<string>()
5268
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
+ }
5269
5561
  for (const ticket of ready) {
5270
5562
  if (this.outOfBudget(opts)) return
5271
5563
  if (withheld.has(ticket.ref.id)) continue
5272
- 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
+ }
5273
5573
  if (typeof target === 'string') {
5274
5574
  targetBlocked.add(ticket.ref.id)
5275
5575
  report.dependencyBlocked += 1
@@ -5278,7 +5578,12 @@ export class Dispatcher {
5278
5578
  }
5279
5579
  preflightTargets.set(ticket.ref.id, JSON.stringify(target))
5280
5580
  if (this.outOfBudget(opts)) return
5281
- 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
+ )
5282
5587
  continue
5283
5588
  let verdict: DependencyVerdict
5284
5589
  try {
@@ -5337,6 +5642,7 @@ export class Dispatcher {
5337
5642
  }
5338
5643
  verdicts.set(ticket.ref.id, verdict)
5339
5644
  }
5645
+ await this.recordDestinationPresence(destinationHeads)
5340
5646
  if (this.outOfBudget(opts)) return
5341
5647
  if (failed.size === 0) {
5342
5648
  await this.sourceCondition(undefined, 'dependency-check')
@@ -5376,7 +5682,7 @@ export class Dispatcher {
5376
5682
  if (failed.has(ticket.ref.id) || targetBlocked.has(ticket.ref.id)) continue
5377
5683
  if ((verdicts.get(ticket.ref.id)?.unresolved.length ?? 0) > 0) continue
5378
5684
 
5379
- const target = await this.resolveNodeTarget(ticket)
5685
+ const target = await this.resolveNodeTarget(ticket, targetScan)
5380
5686
  if (typeof target === 'string') {
5381
5687
  report.dependencyBlocked += 1
5382
5688
  report.dependencyDiagnostics.push(`ticket ${ticket.ref.id}: ${target}`)
@@ -5479,8 +5785,9 @@ export class Dispatcher {
5479
5785
 
5480
5786
  stage = 'naming'
5481
5787
  const baseSlug = await this.chooseSlugBase(ticket.title, body)
5482
- const slug = await this.uniqueSlug(baseSlug)
5483
- 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}`
5484
5791
  const repoOrigin = await this.resolveRepoOriginOnce()
5485
5792
  createdSeed = {
5486
5793
  ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
@@ -5495,6 +5802,9 @@ export class Dispatcher {
5495
5802
  ? { autoMergeDefaultSeq: autoMergeSeedFact.seq }
5496
5803
  : {}),
5497
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 } : {}),
5498
5808
  }
5499
5809
  // `build.created` rides with the record so the pinned assets and the
5500
5810
  // record exist together or not at all.
@@ -5576,6 +5886,7 @@ export class Dispatcher {
5576
5886
  */
5577
5887
  private async resolveNodeTarget(
5578
5888
  ticket: Ticket,
5889
+ scan: TargetScan,
5579
5890
  ): Promise<
5580
5891
  | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
5581
5892
  | string
@@ -5589,7 +5900,8 @@ export class Dispatcher {
5589
5900
  return `integration requires forge ${forge.name} capabilities createNodeBranch, compareBranches and remoteBranchSha; upgrade the plugin`
5590
5901
  if (ticket.target === undefined) return undefined
5591
5902
  const migrations = this.store.repositoryFacts().ticketMigrations
5592
- const entries = (await this.repoBuildDigests())
5903
+ const all = await this.repoBuildDigests()
5904
+ const entries = all
5593
5905
  .filter(
5594
5906
  ({ record }) =>
5595
5907
  record.ticket &&
@@ -5615,7 +5927,7 @@ export class Dispatcher {
5615
5927
  const latest = entries[0]
5616
5928
  if (latest && entries[1]?.record.createdAt === latest.record.createdAt)
5617
5929
  return `target node ${ticket.target} has ambiguous build generations at ${latest.record.createdAt}`
5618
- if (!latest) return `target node ${ticket.target} is not yet claimed`
5930
+ if (!latest) return this.foreignTargetDiagnostic(ticket.target, ticket.ref.source, all, scan)
5619
5931
  const { record, digest } = latest
5620
5932
  if (digest.kind !== 'node') return `target ${ticket.target} is not a node`
5621
5933
  if (digest.terminal || digest.prClosed || digest.merged)
@@ -5688,23 +6000,66 @@ export class Dispatcher {
5688
6000
  private async kernelRepository(root: string): Promise<string> {
5689
6001
  const checkout = this.deps.checkout ?? this.deps.repo
5690
6002
  if (!this.deps.repoOrigin) return checkout
6003
+ if (this.kernelGitUnavailable) throw this.kernelGitUnavailable
5691
6004
  // Origin-mode CLI wiring supplies a scratch checkout path too. Only an
5692
6005
  // actual Git repository can provide the kernel's local object database.
5693
6006
  if (this.deps.checkout) {
5694
- const probe = await this.deps.exec(['git', 'rev-parse', '--git-dir'], { cwd: checkout })
5695
- 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
+ }
5696
6014
  }
5697
6015
  const path = join(root, 'repository.git')
5698
- const clone = await (this.deps.forge.kernelExec ?? this.deps.exec)(
5699
- ['git', 'clone', '--bare', this.deps.repoOrigin, path],
5700
- {
5701
- cwd: root,
5702
- },
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
+ ),
5703
6021
  )
5704
6022
  if (clone.exitCode !== 0) throw new Error(clone.stderr)
6023
+ await this.kernelGitRecovered()
5705
6024
  return path
5706
6025
  }
5707
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
+
5708
6063
  private async withKernelRepository<T>(run: (path: string) => Promise<T>): Promise<T> {
5709
6064
  const root = await mkdtemp(join(tmpdir(), 'autobuild-node-transport-'))
5710
6065
  try {
@@ -5766,7 +6121,9 @@ export class Dispatcher {
5766
6121
  forge.remoteBranchSha(state.baseBranch),
5767
6122
  forge.remoteBranchSha(record.branch),
5768
6123
  ])
5769
- 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)
5770
6127
  const entries = await this.availabilityEntries
5771
6128
  this.availabilityLandings ??= confirmedLandings(entries)
5772
6129
  this.availabilityLandingKey ??= restackLandingKey(this.availabilityLandings)
@@ -5978,6 +6335,9 @@ export class Dispatcher {
5978
6335
  remote: false,
5979
6336
  branch: handle.branch,
5980
6337
  base: handle.base,
6338
+ ...(handle.restorationSkipped?.length
6339
+ ? { restorationSkipped: handle.restorationSkipped }
6340
+ : {}),
5981
6341
  },
5982
6342
  })
5983
6343
  }
@@ -6026,20 +6386,7 @@ export class Dispatcher {
6026
6386
  launched: Set<string>,
6027
6387
  sampling: { refreshOnly?: boolean } = {},
6028
6388
  ): Promise<void> {
6029
- if (
6030
- state.targetRewrite ||
6031
- state.status === 'paused' ||
6032
- state.status === 'done' ||
6033
- state.status === 'aborted' ||
6034
- state.pendingCommands.length ||
6035
- state.openEscalations.length ||
6036
- state.prState === 'merged' ||
6037
- state.prState === 'closed' ||
6038
- state.integration?.intent ||
6039
- state.nodeRestack?.parentRequest ||
6040
- state.nodeRestack?.parentChange
6041
- )
6042
- return
6389
+ if (!integrationAdmissible(state)) return
6043
6390
  const forge = this.kernelForge()
6044
6391
  if (!record.branch || !state.baseBranch || !forge.compareBranches) return
6045
6392
  const comparison = await forge.compareBranches(state.baseBranch!, record.branch!)
@@ -6224,6 +6571,9 @@ export class Dispatcher {
6224
6571
  remote: false,
6225
6572
  branch: handle.branch,
6226
6573
  base: handle.base,
6574
+ ...(handle.restorationSkipped?.length
6575
+ ? { restorationSkipped: handle.restorationSkipped }
6576
+ : {}),
6227
6577
  },
6228
6578
  })
6229
6579
  }
@@ -6261,6 +6611,10 @@ export class Dispatcher {
6261
6611
  )
6262
6612
  return
6263
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)
6264
6618
  try {
6265
6619
  pr = await forge.openPr({
6266
6620
  workspacePath: this.deps.checkout ?? this.deps.repo,
@@ -6268,6 +6622,7 @@ export class Dispatcher {
6268
6622
  base: state.baseBranch,
6269
6623
  title: `Integration: ${record.ticket?.id ?? record.slug}`,
6270
6624
  body: `Integration build ${record.slug}. Target: ${state.target?.ticket.id ?? state.baseBranch}. Human merge required.`,
6625
+ ...(issueLinks ? { issueLinks } : {}),
6271
6626
  })
6272
6627
  } catch (error) {
6273
6628
  if (
@@ -6395,95 +6750,124 @@ export class Dispatcher {
6395
6750
  }
6396
6751
  }
6397
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. */
6398
6757
  private async sampleDestinationPresence(
6399
6758
  branch: string,
6400
6759
  destination: string,
6401
6760
  target: { target: { build: string } } | undefined,
6402
6761
  inputs: PresenceInputs,
6403
- observations: Map<
6404
- string,
6405
- { branch: string; destination: string; head: string; identities: string[] }
6406
- >,
6407
- ) {
6408
- let observed = observations.get(destination)
6409
- if (!observed) {
6410
- 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) {
6411
6775
  if (!forge.remoteBranchSha) throw new Error('forge cannot read destination head')
6412
- const head = await forge.remoteBranchSha(branch)
6413
- 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)
6414
6807
  const cached = this.store.repositoryFacts().presence[destination]
6415
- if (cached?.head === head && cached.branch === branch && cached.witness?.version === 1) {
6416
- const identities = projectPresence(cached.witness, inputs.landings, aliases)
6417
- const evidence = presenceEvidence(cached.witness, identities)
6418
- observed = { ...cached, identities }
6419
- if (cached.evidence !== evidence) {
6420
- await this.store.ensureRepo(this.deps.repo)
6421
- await this.store.appendRepo(this.deps.repo, {
6422
- actor: DISPATCHER,
6423
- type: 'change-presence.observed',
6424
- payload: { ...cached, identities, evidence },
6425
- })
6426
- }
6427
- } else {
6428
- if (!forge.snapshotBase && !forge.kernelExec && !forge.rewrite)
6429
- throw new Error('forge cannot snapshot destination presence')
6430
- observed = await this.withKernelRepository(async (path) => {
6431
- const destinationRef = `refs/autobuild/reconcile/${target?.target.build ?? 'presence'}/presence`
6432
- let sampled: string
6433
- if (forge.snapshotBase)
6434
- sampled = await forge.snapshotBase({
6435
- workspacePath: path,
6436
- base: branch,
6437
- destinationRef,
6438
- })
6439
- else if (target && forge.rewrite)
6440
- sampled = await forge.rewrite.snapshot({
6441
- workspacePath: path,
6442
- branch,
6443
- destinationRef,
6444
- })
6445
- else {
6446
- const exec = forge.kernelExec ?? this.deps.exec
6447
- const fetch = await exec(
6448
- [
6449
- 'git',
6450
- 'fetch',
6451
- '--no-tags',
6452
- '--no-write-fetch-head',
6453
- '--refmap=',
6454
- 'origin',
6455
- `+refs/heads/${branch}:${destinationRef}`,
6456
- ],
6457
- { cwd: path },
6458
- )
6459
- if (fetch.exitCode !== 0) throw new Error(fetch.stderr)
6460
- const resolved = await exec(
6461
- ['git', 'rev-parse', '--verify', `${destinationRef}^{commit}`],
6462
- { cwd: path },
6463
- )
6464
- if (resolved.exitCode !== 0) throw new Error(resolved.stderr)
6465
- sampled = resolved.stdout.trim()
6466
- }
6467
- if (sampled !== head) throw new Error('destination moved while sampling presence')
6468
- const witness = await presenceWitness(
6469
- { exec: forge.kernelExec ?? this.deps.exec, workspacePath: path },
6470
- head,
6471
- )
6472
- const identities = projectPresence(witness, inputs.landings, aliases)
6473
- const evidence = presenceEvidence(witness, identities)
6474
- const payload = { branch, destination, head, evidence, identities, witness }
6475
- await this.store.ensureRepo(this.deps.repo)
6476
- await this.store.appendRepo(this.deps.repo, {
6477
- actor: DISPATCHER,
6478
- type: 'change-presence.observed',
6479
- payload,
6480
- })
6481
- 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,
6836
+ })
6837
+ else if (target && forge.rewrite)
6838
+ sampled = await forge.rewrite.snapshot({
6839
+ workspacePath: path,
6840
+ branch,
6841
+ destinationRef,
6482
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()
6483
6864
  }
6484
- observations.set(destination, observed)
6485
- }
6486
- 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
+ })
6487
6871
  }
6488
6872
 
6489
6873
  private async presenceVerdict(
@@ -6491,13 +6875,10 @@ export class Dispatcher {
6491
6875
  target:
6492
6876
  | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
6493
6877
  | undefined,
6494
- nodes: Map<string, DependencyState>,
6878
+ nodes: Map<string, DependencyNode>,
6495
6879
  inputs: PresenceInputs,
6496
6880
  demands: { slug: string; request: EventPayload<'node.restack-requested'> }[],
6497
- observations: Map<
6498
- string,
6499
- { branch: string; destination: string; head: string; identities: string[] }
6500
- >,
6881
+ observations: Map<string, PresenceObservation>,
6501
6882
  ): Promise<DependencyVerdict> {
6502
6883
  const branch = target?.branch ?? this.deps.config.baseBranch
6503
6884
  const destination = target?.target.build ?? `root:${branch}`
@@ -6515,7 +6896,13 @@ export class Dispatcher {
6515
6896
  this.deps.tickets.name,
6516
6897
  ),
6517
6898
  )
6518
- 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
+ ) {
6519
6906
  fallback.push(id)
6520
6907
  continue
6521
6908
  }
@@ -6559,6 +6946,7 @@ export class Dispatcher {
6559
6946
  target,
6560
6947
  inputs,
6561
6948
  observations,
6949
+ normalizeIdentities([...required.values()].flat()),
6562
6950
  )
6563
6951
  const missing = [
6564
6952
  ...new Set(
@@ -6586,6 +6974,7 @@ export class Dispatcher {
6586
6974
  slug ? { target: { build: slug } } : undefined,
6587
6975
  inputs,
6588
6976
  observations,
6977
+ missing,
6589
6978
  )
6590
6979
  path.push({ ...(slug ? { slug } : {}), ...parent })
6591
6980
  if (missing.every((id) => path.some((entry) => entry.identities.includes(id)))) break
@@ -6631,7 +7020,7 @@ export class Dispatcher {
6631
7020
 
6632
7021
  private async loadDependencyGraph(
6633
7022
  ticket: Ticket,
6634
- nodes: Map<string, DependencyState>,
7023
+ nodes: Map<string, DependencyNode>,
6635
7024
  opts: TickOpts = {},
6636
7025
  builtTickets?: ReadonlySet<string>,
6637
7026
  ): Promise<boolean> {
@@ -6642,7 +7031,8 @@ export class Dispatcher {
6642
7031
  const uncached = frontier.filter((id) => !nodes.has(id))
6643
7032
  if (uncached.length > 0) {
6644
7033
  const states = await this.deps.tickets.dependencyStates(uncached)
6645
- 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))
6646
7036
  }
6647
7037
  const next: string[] = []
6648
7038
  for (const id of frontier) {
@@ -6706,12 +7096,106 @@ export class Dispatcher {
6706
7096
  }
6707
7097
  }
6708
7098
 
6709
- /** Valid bounded base, deduped store-wide with -2/-3/… suffixes. */
6710
- private async uniqueSlug(base: string): Promise<string> {
6711
- let slug = base
6712
- for (let n = 2; (await this.store.getBuild(slug)) !== null; n += 1) {
6713
- 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
6714
7198
  }
6715
- return slug
7199
+ throw new Error(`no free slug for ${base} after ${MAX_SLUG_CANDIDATES} candidates`)
6716
7200
  }
6717
7201
  }