@defrex/autobuild 1.4.2 → 1.6.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 (218) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +512 -101
  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 +7 -3
  7. package/docs/architecture.md +313 -130
  8. package/docs/assets/headline-wide.png +0 -0
  9. package/docs/build-store.md +33 -3
  10. package/docs/cli.md +2 -1
  11. package/docs/configuration-overview.md +9 -0
  12. package/docs/configuration.md +217 -106
  13. package/docs/dispatcher-hosting.md +19 -3
  14. package/docs/dispatcher.md +11 -6
  15. package/docs/glossary.md +1 -1
  16. package/docs/integration-overview.md +2 -2
  17. package/docs/integration-tree.md +91 -28
  18. package/docs/merge-policy.md +28 -9
  19. package/docs/operating.md +1 -1
  20. package/docs/operator-api.md +57 -20
  21. package/docs/operator-surfaces.md +1 -1
  22. package/docs/plugin-authoring.md +89 -8
  23. package/docs/remote-store-protocol.md +39 -11
  24. package/docs/remote-ticket-protocol.md +126 -12
  25. package/docs/restacking.md +24 -6
  26. package/docs/seams.md +2 -2
  27. package/docs/setup.md +19 -13
  28. package/docs/spec-standard.md +2 -1
  29. package/docs/ticket-dependencies.md +26 -8
  30. package/docs/ticket-migration.md +70 -7
  31. package/docs/ticket-sources.md +82 -5
  32. package/docs/tickets.md +34 -2
  33. package/docs/troubleshooting.md +3 -3
  34. package/docs/verification.md +5 -5
  35. package/docs/website.md +8 -0
  36. package/docs/workspaces.md +1 -1
  37. package/package.json +4 -3
  38. package/packages/core/src/accounts/hosted-readiness.ts +21 -0
  39. package/packages/core/src/cli/attention.ts +3 -0
  40. package/packages/core/src/cli/build-control.ts +36 -12
  41. package/packages/core/src/cli/connect.ts +9 -18
  42. package/packages/core/src/cli/context.ts +44 -0
  43. package/packages/core/src/cli/dashboard/configuration.ts +11 -0
  44. package/packages/core/src/cli/dashboard/model.ts +51 -11
  45. package/packages/core/src/cli/dashboard/poll.ts +14 -0
  46. package/packages/core/src/cli/dashboard/queue.ts +21 -0
  47. package/packages/core/src/cli/dashboard/render.ts +43 -22
  48. package/packages/core/src/cli/dispatch-frontend.ts +63 -30
  49. package/packages/core/src/cli/dispatch-mode.ts +35 -16
  50. package/packages/core/src/cli/dispatch-preflight.ts +4 -1
  51. package/packages/core/src/cli/dispatch-repository-feed.ts +40 -11
  52. package/packages/core/src/cli/dispatch-tickets.ts +47 -0
  53. package/packages/core/src/cli/dispatch-upgrade-controller.ts +3 -0
  54. package/packages/core/src/cli/dispatch.ts +522 -145
  55. package/packages/core/src/cli/help.ts +63 -24
  56. package/packages/core/src/cli/init-hosted-accounts.ts +54 -0
  57. package/packages/core/src/cli/init-readiness-remote.ts +16 -3
  58. package/packages/core/src/cli/init-validation.ts +144 -42
  59. package/packages/core/src/cli/issue-links.ts +67 -0
  60. package/packages/core/src/cli/main.ts +32 -15
  61. package/packages/core/src/cli/pr-summary-publication.ts +38 -7
  62. package/packages/core/src/cli/publication-settlement.ts +36 -24
  63. package/packages/core/src/cli/repo-lease.ts +225 -0
  64. package/packages/core/src/cli/repository-status.ts +203 -49
  65. package/packages/core/src/cli/status.ts +42 -4
  66. package/packages/core/src/cli/terminals.ts +37 -2
  67. package/packages/core/src/cli/ticket-editor.ts +20 -6
  68. package/packages/core/src/cli/ticket.ts +264 -46
  69. package/packages/core/src/cli/triage-count-sampler.ts +59 -0
  70. package/packages/core/src/cli/wait.ts +4 -1
  71. package/packages/core/src/cli/watch.ts +19 -4
  72. package/packages/core/src/config/live.ts +45 -4
  73. package/packages/core/src/config/load.ts +9 -0
  74. package/packages/core/src/config/pipeline-source.ts +6 -2
  75. package/packages/core/src/config/ready-assignee.ts +86 -0
  76. package/packages/core/src/config/schema.ts +202 -38
  77. package/packages/core/src/distribution-packaging.ts +1 -1
  78. package/packages/core/src/events/catalog.ts +7 -0
  79. package/packages/core/src/events/compatibility.ts +2 -1
  80. package/packages/core/src/events/payloads.ts +85 -0
  81. package/packages/core/src/events/policy.ts +10 -0
  82. package/packages/core/src/events/repository.ts +93 -28
  83. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +237 -230
  84. package/packages/core/src/kernel/build-identity.ts +12 -0
  85. package/packages/core/src/kernel/change-presence.ts +139 -6
  86. package/packages/core/src/kernel/dispatch-capacity.ts +189 -19
  87. package/packages/core/src/kernel/dispatch-status.ts +10 -1
  88. package/packages/core/src/kernel/dispatch-upgrade.ts +104 -5
  89. package/packages/core/src/kernel/engine.ts +17 -8
  90. package/packages/core/src/kernel/finalize-pr-rejection.ts +95 -0
  91. package/packages/core/src/kernel/generators/build-log.ts +9 -0
  92. package/packages/core/src/kernel/generators/repository-journals.ts +15 -1
  93. package/packages/core/src/kernel/harvest.ts +4 -1
  94. package/packages/core/src/kernel/incremental-fixtures.ts +1 -0
  95. package/packages/core/src/kernel/integration-completeness.ts +104 -17
  96. package/packages/core/src/kernel/integration-landing.ts +17 -0
  97. package/packages/core/src/kernel/integration-state.ts +17 -0
  98. package/packages/core/src/kernel/issue-keywords.ts +202 -0
  99. package/packages/core/src/kernel/janitor-failure.ts +96 -5
  100. package/packages/core/src/kernel/kernel-git.ts +87 -0
  101. package/packages/core/src/kernel/landing-readiness.ts +25 -17
  102. package/packages/core/src/kernel/leaf-restack-state.ts +4 -2
  103. package/packages/core/src/kernel/log-index.ts +1 -1
  104. package/packages/core/src/kernel/node-issue-links.ts +142 -0
  105. package/packages/core/src/kernel/node-landing.ts +2 -1
  106. package/packages/core/src/kernel/node-parent.ts +6 -0
  107. package/packages/core/src/kernel/node-restack-transaction.ts +2 -0
  108. package/packages/core/src/kernel/pr-summary.ts +24 -0
  109. package/packages/core/src/kernel/read-deferrals.ts +75 -12
  110. package/packages/core/src/kernel/read-facts.ts +32 -1
  111. package/packages/core/src/kernel/reconcile-restack.ts +1 -1
  112. package/packages/core/src/kernel/reducer-registry.ts +37 -2
  113. package/packages/core/src/kernel/reducer.ts +147 -5
  114. package/packages/core/src/kernel/ticket-preparation.ts +16 -0
  115. package/packages/core/src/kernel/verify-budget.ts +43 -0
  116. package/packages/core/src/operator/index.ts +3 -1
  117. package/packages/core/src/operator/presentation.ts +3 -0
  118. package/packages/core/src/operator/protocol.ts +38 -2
  119. package/packages/core/src/operator/query.ts +69 -29
  120. package/packages/core/src/operator/registry.ts +47 -26
  121. package/packages/core/src/operator/tickets.ts +77 -10
  122. package/packages/core/src/plugin-sdk/index.ts +13 -0
  123. package/packages/core/src/plugins/manifest.ts +1 -1
  124. package/packages/core/src/plugins/registry.ts +1 -0
  125. package/packages/core/src/ports/forge/contract.ts +69 -0
  126. package/packages/core/src/ports/forge/create.ts +5 -0
  127. package/packages/core/src/ports/forge/fake.ts +184 -3
  128. package/packages/core/src/ports/forge/git-rewrite.ts +4 -2
  129. package/packages/core/src/ports/forge/github.ts +175 -38
  130. package/packages/core/src/ports/forge/local-git.ts +14 -0
  131. package/packages/core/src/ports/forge/readiness.ts +10 -0
  132. package/packages/core/src/ports/forge-failure.ts +43 -0
  133. package/packages/core/src/ports/runner/claude.ts +7 -1
  134. package/packages/core/src/ports/runner/codex.ts +7 -2
  135. package/packages/core/src/ports/runner/native-cli-fixture.ts +2 -1
  136. package/packages/core/src/ports/runner/pi.ts +7 -1
  137. package/packages/core/src/ports/runner/runtime.ts +3 -0
  138. package/packages/core/src/ports/runner/start-prompt.ts +37 -0
  139. package/packages/core/src/ports/tickets/contract.ts +320 -7
  140. package/packages/core/src/ports/tickets/create.ts +89 -20
  141. package/packages/core/src/ports/tickets/fake.ts +18 -0
  142. package/packages/core/src/ports/tickets/file-codec.ts +20 -0
  143. package/packages/core/src/ports/tickets/file.ts +43 -1
  144. package/packages/core/src/ports/tickets/github-fake.ts +1123 -0
  145. package/packages/core/src/ports/tickets/github-issues.ts +431 -0
  146. package/packages/core/src/ports/tickets/github-validators.ts +194 -0
  147. package/packages/core/src/ports/tickets/github.ts +2029 -0
  148. package/packages/core/src/ports/tickets/hosted-index.ts +34 -3
  149. package/packages/core/src/ports/tickets/issue-links.ts +86 -0
  150. package/packages/core/src/ports/tickets/lifecycle.ts +60 -4
  151. package/packages/core/src/ports/tickets/linear.ts +66 -6
  152. package/packages/core/src/ports/tickets/migration.ts +290 -68
  153. package/packages/core/src/ports/tickets/operations.ts +98 -12
  154. package/packages/core/src/ports/tickets/priority.ts +55 -0
  155. package/packages/core/src/ports/tickets/remote-protocol.ts +195 -29
  156. package/packages/core/src/ports/tickets/remote.ts +188 -13
  157. package/packages/core/src/ports/tickets/revision.ts +22 -1
  158. package/packages/core/src/ports/tickets/states.ts +43 -0
  159. package/packages/core/src/ports/tickets/tree.ts +58 -12
  160. package/packages/core/src/ports/tickets/update.ts +12 -2
  161. package/packages/core/src/ports/types.ts +194 -9
  162. package/packages/core/src/ports/workspace/commit-preservation.ts +163 -25
  163. package/packages/core/src/ports/workspace/git-worktree.ts +6 -2
  164. package/packages/core/src/ports/workspace/harvest-execution.ts +4 -2
  165. package/packages/core/src/ports/workspace/vercel-sandbox.ts +121 -27
  166. package/packages/core/src/processes/build-runner.ts +101 -22
  167. package/packages/core/src/processes/dispatcher.ts +1046 -372
  168. package/packages/core/src/processes/execution-no-progress.ts +7 -0
  169. package/packages/core/src/processes/harvest-child.ts +4 -2
  170. package/packages/core/src/processes/harvest-execution-state.ts +104 -0
  171. package/packages/core/src/processes/harvest-runner.ts +263 -25
  172. package/packages/core/src/processes/harvest.ts +5 -8
  173. package/packages/core/src/processes/tick-publication.ts +12 -2
  174. package/packages/core/src/processes/ticket-scan-schedule.ts +78 -0
  175. package/packages/core/src/processes/workspace-preservation.ts +36 -1
  176. package/packages/core/src/runtime-identity.ts +10 -2
  177. package/packages/core/src/scenarios/harness.ts +149 -35
  178. package/packages/core/src/store/adapter.ts +7 -1
  179. package/packages/core/src/store/contract.ts +83 -2
  180. package/packages/core/src/store/digest.ts +32 -1
  181. package/packages/core/src/store/reduced-reads.ts +10 -0
  182. package/packages/core/src/store/reducer-value-shapes.json +4471 -3427
  183. package/packages/core/src/store/remote/protocol.ts +2 -0
  184. package/packages/core/src/store/remote/released-clients.json +22 -0
  185. package/packages/core/src/store/remote/released-reducer-values/1.5.0.json +26924 -0
  186. package/packages/core/src/store/remote/released-reducer-values/1.6.0.json +27173 -0
  187. package/packages/core/src/store/remote/released-reducer-values/index.ts +4 -0
  188. package/packages/core/src/store/repo-state-events.ts +2 -0
  189. package/packages/core/src/store/types.ts +5 -0
  190. package/packages/core/src/testing/dispatch-read-budget.ts +729 -123
  191. package/packages/core/src/testing/index.ts +18 -1
  192. package/packages/core/src/testing/presence-history.ts +79 -0
  193. package/packages/core/src/testing/reduced-read-budget.ts +1424 -33
  194. package/packages/core/src/testing/upgrade-generations.ts +77 -0
  195. package/skills/code-review/SKILL.md +4 -3
  196. package/skills/finalize/SKILL.md +18 -2
  197. package/skills/guide/SKILL.md +417 -143
  198. package/skills/guide/references/accounts.md +9 -0
  199. package/skills/guide/references/integration-tree.md +91 -28
  200. package/skills/guide/references/merge-policy.md +28 -9
  201. package/skills/guide/references/operator-api.md +57 -20
  202. package/skills/guide/references/plugin-authoring.md +89 -8
  203. package/skills/guide/references/remote-store-protocol.md +39 -11
  204. package/skills/guide/references/remote-ticket-protocol.md +126 -12
  205. package/skills/guide/references/restacking.md +24 -6
  206. package/skills/guide/references/setup.md +19 -13
  207. package/skills/guide/references/spec-standard.md +2 -1
  208. package/skills/guide/references/ticket-dependencies.md +26 -8
  209. package/skills/guide/references/ticket-migration.md +70 -7
  210. package/skills/harvest-review/SKILL.md +4 -3
  211. package/skills/implement/SKILL.md +20 -1
  212. package/skills/operate/SKILL.md +149 -35
  213. package/skills/plan/SKILL.md +1 -1
  214. package/skills/reconcile/SKILL.md +5 -4
  215. package/skills/spec/SKILL.md +15 -2
  216. package/skills/tickets/SKILL.md +116 -37
  217. package/templates/autobuild.toml +5 -0
  218. package/templates/hosted-service/package.json +2 -2
@@ -1,4 +1,9 @@
1
1
  import { proveTargetLineage } from '../kernel/target-lineage'
2
+ import {
3
+ isRepositoryAuthorityLapse,
4
+ RepositoryAuthorityLapsed,
5
+ rethrowAuthorityLapse,
6
+ } from '../cli/repo-lease'
2
7
  import { assertTargetOid, observeTarget } from '../kernel/target-observation'
3
8
  import {
4
9
  MissingAccountCredentialsError,
@@ -7,10 +12,14 @@ import {
7
12
  type MissingAccountCredential,
8
13
  } from '../accounts/availability'
9
14
 
10
- import { preserveWorkspaceBeforeRelease } from './workspace-preservation'
15
+ import { preserveWorkspaceBeforeRelease, supersedeRestorationHeads } from './workspace-preservation'
11
16
  import { WorkspaceCleanupRequired } from '../ports/types'
17
+ import type { OpenHarvestExecution } from './harvest-execution-state'
12
18
  import { ArtifactMetaUnsupportedError } from '../store/artifact-meta'
13
- import type { TicketPreparation } from '../kernel/ticket-preparation'
19
+ import {
20
+ abandonedPreparationDiagnostic,
21
+ type TicketPreparation,
22
+ } from '../kernel/ticket-preparation'
14
23
  import { sampleTargetDistance } from '../kernel/target-distance'
15
24
  import { capturedBuildConfig } from './verify-cycle-config'
16
25
  import { publicationRetryGate } from '../kernel/publication-retry'
@@ -27,6 +36,7 @@ import {
27
36
  nodeTicketObservationKey,
28
37
  } from '../kernel/node-polling'
29
38
  import { reportIntegrationFailures } from '../kernel/integration-attention'
39
+ import { ticketScanDeferredByJournal, ticketScanSchedule } from './ticket-scan-schedule'
30
40
  import {
31
41
  resolveTicketRef,
32
42
  migrationIdentity,
@@ -45,14 +55,33 @@ import {
45
55
  MixedVersionDeferral,
46
56
  } from '../kernel/mixed-version'
47
57
  import { guardForge, ForgeCooldown } from '../kernel/guarded-forge'
48
- import { recordJanitorFailure } from '../kernel/janitor-failure'
58
+ import {
59
+ escalationsBeyondJanitor,
60
+ janitorBlocked,
61
+ janitorDeferral,
62
+ janitorDue,
63
+ janitorStatus,
64
+ recordJanitorFailure,
65
+ withoutJanitorEscalation,
66
+ type JanitorOperation,
67
+ } from '../kernel/janitor-failure'
68
+ import { KernelGitUnavailable, kernelGitUnavailableDetail } from '../kernel/kernel-git'
49
69
  import { isForgeFailure } from '../ports/forge-failure'
50
70
  import {
51
71
  ForgeRequestDeferred,
52
72
  withForgeRequestContext,
53
73
  forgeRequestContext,
54
74
  } from '../ports/forge-request-context'
55
- import { dispatchCapacity, nodeCapacity, type CapacityBuild } from '../kernel/dispatch-capacity'
75
+ import {
76
+ dispatchCapacity,
77
+ epilogueLeaf,
78
+ intakeCapacity,
79
+ nodeCapacity,
80
+ settlementDue,
81
+ settlementKey,
82
+ slotRequest,
83
+ type CapacityBuild,
84
+ } from '../kernel/dispatch-capacity'
56
85
  import { evaluateLandingPolicy } from '../kernel/landing-policy'
57
86
  import {
58
87
  landingAuthorized,
@@ -74,6 +103,7 @@ import {
74
103
  integrationFailed,
75
104
  integrationVerified,
76
105
  integrationHeadVerified,
106
+ integrationAdmissible,
77
107
  } from '../kernel/integration-state'
78
108
  import {
79
109
  normalizeIdentities,
@@ -82,12 +112,16 @@ import {
82
112
  presenceInputs,
83
113
  confirmedLandings,
84
114
  presenceWitness,
85
- projectPresence,
86
- presenceEvidence,
115
+ answers,
116
+ compactProbe,
117
+ projectProbe,
118
+ probeEvidence,
87
119
  destinationAliases,
88
120
  ownedContribution,
89
121
  type ChangeIdentity,
90
122
  type PresenceInputs,
123
+ type PresenceProbe,
124
+ type PresenceWitness,
91
125
  } from '../kernel/change-presence'
92
126
  import { landIntoNode, settleClosedNode, preflightNodeLanding } from '../kernel/node-landing'
93
127
  import { mkdtemp, rm } from 'node:fs/promises'
@@ -95,11 +129,13 @@ import { tmpdir } from 'node:os'
95
129
  import { join } from 'node:path'
96
130
  import { runNodeTransaction } from '../kernel/node-restack-transaction'
97
131
  import { hasBuildTrailer } from '../kernel/build-identity'
132
+ import { digestNodeTargets } from '../store/digest'
98
133
  import { readBuildDigests, readForgeHealth } from '../store/reduced-reads'
99
134
  import { readBuildSelector, readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
100
135
  import { ensureExecutionProgress } from './execution-no-progress'
101
136
  import { ticketIdentity } from '../ports/tickets/identity'
102
- import { ticketLifecycle } from '../ports/tickets/lifecycle'
137
+ import { holdsState, ticketLifecycle } from '../ports/tickets/lifecycle'
138
+ import { urgentFirst } from '../ports/tickets/priority'
103
139
  import { ensureDispatchBudget } from './dispatch-failure-budget'
104
140
  import type { TicketSourceDegradation } from '../kernel/ticket-source-health'
105
141
  /**
@@ -149,7 +185,7 @@ import type { EventPayload, PinnedAsset } from '../events/payloads'
149
185
  import type { IdSource } from '../ids'
150
186
  import { recordAutoMergeDeferralObservation } from '../kernel/auto-merge'
151
187
  import type { AutoMergeDefaultFact } from '../kernel/auto-merge-default'
152
- import { decideNextFromFacts } from '../kernel/engine'
188
+ import { decideNextFromFacts, landingRestackDue } from '../kernel/engine'
153
189
  import { composeBuildConfig } from '../config/live'
154
190
  import { BUILD_EFFECTIVE_CONFIG_ARTIFACT, parseEffectiveBuildConfig } from './build-execution-state'
155
191
  import {
@@ -163,13 +199,20 @@ import { BUILD_EXECUTION_LEASE_TTL_MS } from '../ports/workspace/build-execution
163
199
  import type {
164
200
  DependencyState,
165
201
  Forge,
202
+ IssueLink,
166
203
  Ticket,
167
204
  TicketSource,
168
205
  WorkspaceProvider,
169
206
  WorkspaceProvisionResult,
170
207
  } from '../ports/types'
171
208
  import { NoCommitsBetweenBranchesError, TicketSourceRateLimitError } from '../ports/types'
172
- import type { Exec } from '../ports/workspace/git-worktree'
209
+ import { issueLinksForForge } from '../kernel/issue-keywords'
210
+ import {
211
+ contributedIssueLinks,
212
+ nodeIssueLinksForForge,
213
+ nodeIssueLinksSyncPending,
214
+ } from '../kernel/node-issue-links'
215
+ import type { Exec, ExecResult } from '../ports/workspace/git-worktree'
173
216
  import type { ArtifactMeta, BuildDigest, BuildRecord, BuildStore, Clock } from '../store/types'
174
217
  import { preparePinnedAssets } from '../store/ticket-assets'
175
218
  import { resolveRepoOrigin } from '../cli/repo-state'
@@ -196,13 +239,15 @@ import { settlePublicationFactsBeforeRelease } from './publication-loss'
196
239
  *
197
240
  * The only per-source difference left is the *label* default. Linear has no
198
241
  * `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
242
+ * dispatchable: the historical `["autobuild"]` default. GitHub shares it, so
243
+ * an issue anyone can file still needs the opt-in label. The file tracker's gate
200
244
  * is otherwise the directory, so it defaults to no label gate. Plugin sources
201
245
  * likewise receive no host-imposed label convention. An explicit
202
246
  * `readyLabels` wins for every source.
203
247
  *
204
- * `[tickets].readyAssignee` (Linear only) adds a third conjunctive gate: the
205
- * ticket must be assigned to that user.
248
+ * `[tickets].readyAssignee` adds a third conjunctive gate for any source: the
249
+ * ticket must be assigned to that user. Only sources declaring the capability
250
+ * get this far (`config/ready-assignee.ts`).
206
251
  */
207
252
  export function readyCriteria(config: Config): {
208
253
  labels: string[]
@@ -210,14 +255,12 @@ export function readyCriteria(config: Config): {
210
255
  assignee?: string
211
256
  } {
212
257
  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
- }
258
+ const source = config.tickets.source
259
+ return {
260
+ labels: readyLabels ?? (source === 'github' || source === 'linear' ? ['autobuild'] : []),
261
+ state: readyState,
262
+ ...(readyAssignee !== undefined ? { assignee: readyAssignee } : {}),
219
263
  }
220
- return { labels: readyLabels ?? [], state: readyState }
221
264
  }
222
265
 
223
266
  /**
@@ -260,6 +303,33 @@ export function defaultProposalState(config: Config): string {
260
303
  // decision here means one tested implementation instead of one per adapter,
261
304
  // and no adapter's state taxonomy leaks upward.
262
305
 
306
+ /** A cached dependency fact with the configured rejected role applied. */
307
+ export type DependencyNode = DependencyState & { rejected?: boolean }
308
+
309
+ /**
310
+ * Apply the configured rejected role over the source's native completion
311
+ * fact: a blocker in the rejected state never resolves, even where the
312
+ * source natively counts it complete (Linear's canceled). An unset role
313
+ * changes nothing. Moving the ticket out of the state restores ordinary
314
+ * gating, because every scan reads the current state afresh.
315
+ */
316
+ export function markRejected(node: DependencyState, rejectedState?: string): DependencyNode {
317
+ return node.exists && holdsState(node.state, rejectedState)
318
+ ? { ...node, resolved: false, rejected: true }
319
+ : node
320
+ }
321
+
322
+ /** One destination's in-tick presence answers and the probe behind them. */
323
+ interface PresenceObservation {
324
+ branch: string
325
+ destination: string
326
+ head: string
327
+ identities: ChangeIdentity[]
328
+ probe: PresenceProbe
329
+ /** Questions asked this tick. A reused durable probe may cover more, but
330
+ * only these seed a re-compaction, so questions never accumulate across ticks. */
331
+ asked: ChangeIdentity[]
332
+ }
263
333
  export interface DependencyVerdict {
264
334
  /** Unresolved blocker ids — nonempty means DO NOT dispatch. */
265
335
  unresolved: string[]
@@ -278,7 +348,7 @@ export interface DependencyVerdict {
278
348
  function findCycle(
279
349
  from: string,
280
350
  path: string[],
281
- nodes: Map<string, DependencyState>,
351
+ nodes: Map<string, DependencyNode>,
282
352
  explored: Set<string>,
283
353
  ): string[] | null {
284
354
  const node = nodes.get(from)
@@ -313,7 +383,7 @@ function findCycle(
313
383
  export function analyzeDependencies(
314
384
  ticketId: string,
315
385
  blockedBy: string[],
316
- nodes: Map<string, DependencyState>,
386
+ nodes: Map<string, DependencyNode>,
317
387
  ): DependencyVerdict {
318
388
  const unresolved: string[] = []
319
389
  const diagnostics: string[] = []
@@ -333,6 +403,11 @@ export function analyzeDependencies(
333
403
  )
334
404
  continue
335
405
  }
406
+ if (node.rejected) {
407
+ unresolved.push(blockerId)
408
+ diagnostics.push(`ticket ${ticketId} blocked by ${blockerId}, which was rejected`)
409
+ continue
410
+ }
336
411
  // A resolved blocker imposes nothing, and its own history is irrelevant —
337
412
  // never walked, so a cycle *behind* completed work is not a diagnostic.
338
413
  if (node.resolved) continue
@@ -399,7 +474,8 @@ export interface TickReport {
399
474
  discarded: number
400
475
  /** Contained build janitor and ticket-preparation recovery failures this pass. */
401
476
  janitorFailed: number
402
- /** One actionable line per contained failure, attributed by build or attempt. */
477
+ /** One actionable line per contained failure or abandoned ticket preparation,
478
+ * attributed by build, ticket or attempt. */
403
479
  janitorDiagnostics: string[]
404
480
  /** Ordinary-tick recovery completed an interrupted post-creation dispatch. */
405
481
  recovered: number
@@ -506,6 +582,12 @@ export function emptyTickReport(): TickReport {
506
582
  // ── Dispatcher ───────────────────────────────────────────────────────────────
507
583
 
508
584
  const DEFAULT_SLUG_NAMING_TIMEOUT_MS = 10_000
585
+ /** Bound on -2/-3/… candidates one claim may probe for a free slug. */
586
+ const MAX_SLUG_CANDIDATES = 100
587
+ /** Body of the comment dispatch posts on every claimed ticket. The
588
+ * foreign-target diagnostic parses it to find another store's node branch. */
589
+ const dispatchCommentBody = (slug: string) => `build ${slug} dispatched`
590
+ const DISPATCH_COMMENT = /^build ([a-z0-9][a-z0-9-]*) dispatched$/
509
591
  /** Heartbeat cadence of a background provisioning continuation's execution
510
592
  * lease. A dead provisioner is therefore adopted within one lease TTL. */
511
593
  const PROVISION_HEARTBEAT_MS = 15_000
@@ -519,6 +601,14 @@ export type DispatchOutcome = 'completed' | 'deferred' | 'parked' | 'failed'
519
601
  /** One tracked background provisioning continuation (process-local). Its
520
602
  * durable residue is the `workspace.provision-started` marker plus the
521
603
  * execution lease it claims and heartbeats. */
604
+ /** Per-admission-scan inputs for target-node resolution: the ready listing's
605
+ * ids and the memoized foreign-target verdicts, one per distinct target. */
606
+ interface TargetScan {
607
+ listed: ReadonlySet<string>
608
+ foreign: Map<string, Promise<string>>
609
+ generation: number
610
+ }
611
+
522
612
  interface ProvisionContinuation {
523
613
  readonly slug: string
524
614
  readonly instance: string
@@ -607,6 +697,11 @@ export interface TickOpts {
607
697
  export type LaunchRunnerResult = 'scheduled' | 'already-active'
608
698
 
609
699
  export interface DispatcherDeps {
700
+ /** Whether this process currently holds repository authority (SPEC §12).
701
+ * Synchronous and without I/O. Absent means always true. When false, the
702
+ * tick starts no further unit of work, and its durable new-work writes are
703
+ * refused with `RepositoryAuthorityLapsed`. */
704
+ holdsRepoAuthority?: () => boolean
610
705
  /** Current selected-account presence; no store reads. */
611
706
  missingAccounts?: () => MissingAccountCredential[]
612
707
  accountCredentialSource?: MissingAccountCredential['source']
@@ -654,11 +749,14 @@ export interface DispatcherDeps {
654
749
  authorSpec?: (ticket: Ticket) => Promise<string | null>
655
750
  /** Start the repository-scoped observation workflow without awaiting it.
656
751
  * The owner must single-flight and track the promise; Dispatcher invokes
657
- * this after ready-ticket dispatch, independent of drain/build capacity. */
752
+ * this after ready-ticket dispatch, independent of drain/build capacity.
753
+ * Withheld while a foreign, provider-observable hosted-harvest execution is
754
+ * still open: its guest owns the run's open session. */
658
755
  startHarvest?: () => void
659
756
  /** Optional one-shot judgment over the final conforming spec. The dispatcher
660
757
  * supplies cancellation and treats every absence/failure/invalid result as a
661
- * local deterministic fallback, so naming can never prevent build creation. */
758
+ * local deterministic fallback, so a failed proposal never prevents build
759
+ * creation. Slug deduplication (`uniqueSlug`) can still fail the claim. */
662
760
  nameSlug?: (spec: string, signal: AbortSignal) => Promise<string | null>
663
761
  /** Settle pending publication for `slug` after durable proof that the
664
762
  * guest execution ended. Supplied by the DispatchLoop; the settlement stage
@@ -753,6 +851,21 @@ export class Dispatcher {
753
851
  }
754
852
  >()
755
853
  private readonly nodePollingTickReads = new Map<string, Promise<BuildState>>()
854
+ /** Per-process cache of the foreign-target branch-arm lookup (AUT-1106),
855
+ * keyed by target ticket id and invalidated by the target ticket's revision
856
+ * and foreign dispatch-comment slugs. `scan` is the admission scan that last
857
+ * consulted the entry; entries older than the previous scan are dropped. */
858
+ private readonly foreignBranchCache = new Map<
859
+ string,
860
+ { fingerprint: string; branch: string | null; scan: number }
861
+ >()
862
+ private foreignScanGeneration = 0
863
+ /** Last full in-memory witness per sampled destination, replaced on head
864
+ * moves, so a long-running dispatcher walks Git at most once per head. */
865
+ private readonly presenceWitnesses = new Map<
866
+ string,
867
+ { branch: string; head: string; witness: PresenceWitness }
868
+ >()
756
869
 
757
870
  private async integrationClaimKey(slug: string, state: BuildState): Promise<string> {
758
871
  return nodeTicketObservationKey(state, await this.nodePollingChildren(slug))
@@ -761,6 +874,9 @@ export class Dispatcher {
761
874
  const children: { slug: string; state: Pick<BuildState, 'pollingActivity'> }[] = []
762
875
  for (const { record, digest } of await this.repoBuildDigests()) {
763
876
  if (record.slug === slug) continue
877
+ // The digest names every node a build ever targeted, so a build it does
878
+ // not name can never be this node's child and needs no facts read.
879
+ if (!digestNodeTargets(digest).includes(slug)) continue
764
880
  const known = this.nodePollingBuilds.get(record.slug)
765
881
  // Only node relationships can move. Unrelated known work never needs
766
882
  // another full-facts read, even while it is running.
@@ -798,22 +914,29 @@ export class Dispatcher {
798
914
  }
799
915
 
800
916
  private observeIntegration(slug: string, publication = false) {
801
- return observeIntegration(this.store, this.deps.tickets, slug, () => {
802
- if (publication) {
803
- this.integrationPublicationInputs ??= integrationObservationInputs(
917
+ const rejectedState = this.rejectedState()
918
+ return observeIntegration(
919
+ this.store,
920
+ this.deps.tickets,
921
+ slug,
922
+ () => {
923
+ if (publication) {
924
+ this.integrationPublicationInputs ??= integrationObservationInputs(
925
+ this.store,
926
+ this.deps.tickets,
927
+ this.deps.repo,
928
+ )
929
+ return this.integrationPublicationInputs
930
+ }
931
+ this.integrationInputs ??= integrationObservationInputs(
804
932
  this.store,
805
933
  this.deps.tickets,
806
934
  this.deps.repo,
807
935
  )
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
- })
936
+ return this.integrationInputs
937
+ },
938
+ rejectedState === undefined ? {} : { rejectedState },
939
+ )
817
940
  }
818
941
 
819
942
  // Disposable parsed pins only. Current facts, live policy and cycle captures
@@ -924,7 +1047,7 @@ export class Dispatcher {
924
1047
  private get doneState(): string {
925
1048
  return (
926
1049
  this.deps.opts?.doneState ??
927
- (this.deps.config.tickets.source === 'hosted'
1050
+ (this.deps.config.tickets.source === 'hosted' || this.deps.config.tickets.source === 'github'
928
1051
  ? ticketLifecycle(this.deps.config.tickets).done
929
1052
  : undefined) ??
930
1053
  'Done'
@@ -936,12 +1059,25 @@ export class Dispatcher {
936
1059
  /** Process-local background provisioning, keyed by slug. A tick that sees a
937
1060
  * slug here defers to the continuation; it never blocks on it. */
938
1061
  private readonly continuations = new Map<string, ProvisionContinuation>()
1062
+ /** Per tick, rebuilt from durable state: builds launched so far, which
1063
+ * occupy a slot before their runner claims a lease. */
1064
+ private tickLaunched: ReadonlySet<string> = new Set()
1065
+ /** Per tick: finished leaves the admission gate turned away. Intake reserves their slots. */
1066
+ private readonly slotWaiters = new Set<string>()
1067
+ /** Per tick: parked leaves whose sweep decision was `wait awaiting-pr`. A
1068
+ * projected wait for one of these is one tick stale and reserves nothing. */
1069
+ private readonly parkedSettled = new Set<string>()
939
1070
 
940
1071
  // Batched confirmed landing evidence is shared across nodes for this tick.
941
- // Only durable availability facts authorize the shortcut after restart.
1072
+ // Only durable availability facts authorize the shortcut after restart. The
1073
+ // batch includes mixed-version deferred builds' durable landing facts so its
1074
+ // fingerprint matches the one the node transaction records.
942
1075
  private availabilityLandings?: ReturnType<typeof confirmedLandings>
943
1076
  private availabilityLandingKey?: string
944
1077
  private availabilityEntries?: ReturnType<Dispatcher['repoBuildDigests']>
1078
+ /** Set once kernel Git proved unable to run this tick; later node work in
1079
+ * the same tick defers on it without spawning again. */
1080
+ private kernelGitUnavailable?: KernelGitUnavailable
945
1081
 
946
1082
  /** The incremental repository view every stage reads and writes through
947
1083
  * (AUT-647): `deps.store` itself when the caller already wrapped it. */
@@ -992,11 +1128,16 @@ export class Dispatcher {
992
1128
  * loops consult this before starting each new forge/store transport call,
993
1129
  * bounding the tick's overrun to the one call already in flight. */
994
1130
  private outOfBudget(opts: TickOpts): boolean {
995
- return opts.deadlineAt !== undefined && this.deps.clock().getTime() >= opts.deadlineAt
1131
+ return (
1132
+ (opts.deadlineAt !== undefined && this.deps.clock().getTime() >= opts.deadlineAt) ||
1133
+ this.deps.holdsRepoAuthority?.() === false
1134
+ )
996
1135
  }
997
1136
 
998
1137
  lastForgeRequests?: import('../ports/forge-telemetry').ForgeRequestCounts
999
1138
  async tick(opts: TickOpts = {}): Promise<TickReport> {
1139
+ this.kernelGitUnavailable = undefined
1140
+ this.tickAbandonments = []
1000
1141
  this.availabilityEntries = undefined
1001
1142
  this.availabilityLandings = undefined
1002
1143
  this.availabilityLandingKey = undefined
@@ -1031,17 +1172,44 @@ export class Dispatcher {
1031
1172
  ? this.deps.forge.withReadScope(() => this.runTick(opts))
1032
1173
  : this.runTick(opts))
1033
1174
  if (stop || this.deps.config.forge === 'local-git') report.forgeRequests = counts()
1175
+ report.janitorDiagnostics.push(...this.tickAbandonments)
1034
1176
  return report
1177
+ } catch (error) {
1178
+ throw this.withTickAbandonments(error)
1035
1179
  } finally {
1180
+ this.tickAbandonments = []
1036
1181
  if (stop || this.deps.config.forge === 'local-git') this.lastForgeRequests = counts()
1037
1182
  stop?.()
1038
1183
  }
1039
1184
  }
1040
1185
 
1186
+ /** Ticket preparations durably abandoned during the current tick. Drained
1187
+ * once by `tick()` into its report or its rejection, so later ticks never
1188
+ * repeat them. At most 8 recoveries plus one inline abandonment per tick. */
1189
+ private tickAbandonments: string[] = []
1190
+
1191
+ /** A failed tick still reports the attempts it abandoned. The rejection
1192
+ * keeps its type: the lines are appended to a writable message in place. */
1193
+ private withTickAbandonments(error: unknown): unknown {
1194
+ if (this.tickAbandonments.length === 0) return error
1195
+ const lines = `abandoned ticket preparations this tick: ${this.tickAbandonments.join('; ')}`
1196
+ if (error instanceof Error) {
1197
+ try {
1198
+ error.message = `${error.message}; ${lines}`
1199
+ return error
1200
+ } catch {
1201
+ // A frozen or non-writable message falls through to a wrapper.
1202
+ }
1203
+ }
1204
+ return new AggregateError([error], `${String(error)}; ${lines}`, { cause: error })
1205
+ }
1206
+
1041
1207
  private async runTick(opts: TickOpts): Promise<TickReport> {
1042
1208
  this.integrationInputs = undefined
1043
1209
  this.integrationPublicationInputs = undefined
1044
1210
  this.nodePollingTickReads.clear()
1211
+ this.slotWaiters.clear()
1212
+ this.parkedSettled.clear()
1045
1213
  // One immutable config for this complete decision pass. A reload racing the
1046
1214
  // tick is observed by the next tick, never half-way through this one.
1047
1215
  this.deps.config = this.deps.getConfig?.() ?? this.deps.config
@@ -1052,6 +1220,7 @@ export class Dispatcher {
1052
1220
  /** Builds already launched this tick — a janitor/startup re-attach must
1053
1221
  * not be doubled by the sweep, nor a fresh dispatch by anything. */
1054
1222
  const launched = new Set<string>()
1223
+ this.tickLaunched = launched
1055
1224
  // One journal read for both repository-wide controls: a pause that lands
1056
1225
  // mid-tick takes effect on the next tick, matching intake (which the CLI
1057
1226
  // likewise samples before calling `tick`); the auto-merge default fact is
@@ -1092,6 +1261,10 @@ export class Dispatcher {
1092
1261
  if (this.outOfBudget(opts)) return report
1093
1262
  await this.leaseSweep(report, launched, paused, opts)
1094
1263
  if (this.outOfBudget(opts)) return report
1264
+ // Nodes with a durable verification request take freed slots before
1265
+ // intake, whether or not idle node polling visited them this tick.
1266
+ await this.admitWaitingNodes(report, launched, opts)
1267
+ if (this.outOfBudget(opts)) return report
1095
1268
  if (opts.acceptNewWork !== false) {
1096
1269
  await this.dispatch(report, launched, autoMergeUser, paused, opts, autoMergeSeedFact)
1097
1270
  }
@@ -1112,6 +1285,11 @@ export class Dispatcher {
1112
1285
  return this.deps.opts?.triageState ?? defaultTriageState(this.deps.config)
1113
1286
  }
1114
1287
 
1288
+ /** The configured rejected role's state, read from live config each time. */
1289
+ private rejectedState(): string | undefined {
1290
+ return ticketLifecycle(this.deps.config.tickets).rejected
1291
+ }
1292
+
1115
1293
  /** This repository's builds paired with their digests, from one record
1116
1294
  * listing and one digest read — the tick loops' per-build event reads start
1117
1295
  * from here so a settled terminal build costs none. Records are read before
@@ -1366,34 +1544,21 @@ export class Dispatcher {
1366
1544
  const readinessFingerprint = hash(digest)
1367
1545
  const criteriaFingerprint = hash(readyCriteria(this.deps.config))
1368
1546
  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,
1547
+ const input = {
1548
+ previous: this.latestScan(),
1549
+ previousSeq: this.store.repositoryFacts().scanSeq,
1385
1550
  mode,
1386
1551
  readinessFingerprint,
1387
1552
  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'),
1553
+ startedAt,
1554
+ intervalMs: this.deps.config.ticketScanIntervalSeconds * 1000,
1396
1555
  }
1556
+ const checkpoint = { startedAt, mode, readinessFingerprint, criteriaFingerprint }
1557
+ // The journal measurement alone proves deferral, so the cadence row is not read.
1558
+ if (ticketScanDeferredByJournal(input))
1559
+ return { ...checkpoint, allowClockRollback: false, due: false }
1560
+ const cached = await this.store.getScanCadence(this.deps.repo)
1561
+ return { ...checkpoint, ...ticketScanSchedule(input, cached) }
1397
1562
  }
1398
1563
 
1399
1564
  private async completeScan(
@@ -1496,8 +1661,11 @@ export class Dispatcher {
1496
1661
  return
1497
1662
  }
1498
1663
  // 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') {
1664
+ const facts = this.store.repositoryFacts()
1665
+ // A live guest owns its open session; launching would judge that session
1666
+ // as runner loss and start a duplicate guest beside it.
1667
+ if (this.liveForeignHarvestExecution(facts.openHarvest)) return
1668
+ if (decideHarvestControl(facts.harvest, this.maxHarvestRecoveryAttempts).kind !== 'park') {
1501
1669
  start()
1502
1670
  }
1503
1671
  }
@@ -1523,6 +1691,7 @@ export class Dispatcher {
1523
1691
  )
1524
1692
  return 'already-active'
1525
1693
  if (launched.has(slug)) return 'already-active'
1694
+ if (launchState.kind !== 'node' && !(await this.leafAdmission(slug))) return 'already-active'
1526
1695
  launched.add(slug)
1527
1696
  const facts = (await readBuildFacts(this.store, slug)).value
1528
1697
  // Callers reap and reprovision a flagged workspace; an agent never starts
@@ -1537,6 +1706,13 @@ export class Dispatcher {
1537
1706
  const branch = facts.lastCreated.payload.baseBranch
1538
1707
  await this.observeTarget(slug, branch, undefined, report)
1539
1708
  }
1709
+ return this.startRunner(slug, report)
1710
+ }
1711
+
1712
+ /** The one guarded runner start. Every dispatcher path that starts a runner
1713
+ * goes through here, so the no-progress policy cannot depend on which path
1714
+ * runs. */
1715
+ private async startRunner(slug: string, report: TickReport): Promise<LaunchRunnerResult> {
1540
1716
  if (
1541
1717
  !(await ensureExecutionProgress(
1542
1718
  this.store,
@@ -1604,11 +1780,15 @@ export class Dispatcher {
1604
1780
  * execution is not supervised by this process is observed through the
1605
1781
  * owning provider. `lost`/`ended` reaps the disposable environment and
1606
1782
  * journals the close fact with the snapshot purge outcome; `running`
1607
- * 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. */
1783
+ * leaves it — the guest is the live supervisor and its authority is its
1784
+ * durable `harvest.execution.authorized`, not any invocation's repository
1785
+ * lease, which it leaves to dispatch; the next pass reaps it after it
1786
+ * ends. Until the
1787
+ * release is journaled, an open observable execution also suppresses
1788
+ * harvest launch (`liveForeignHarvestExecution`). The run itself needs no
1789
+ * settlement here: an interrupted run stays open in the journal, and the
1790
+ * next launch after the release records its interrupted session and
1791
+ * resumes it under the repository lease. */
1612
1792
  private async settleHarvestExecutions(opts: TickOpts = {}): Promise<void> {
1613
1793
  const active = this.deps.activeHarvestExecutions?.() ?? new Set<string>()
1614
1794
  const facts = this.store.repositoryFacts()
@@ -1695,6 +1875,22 @@ export class Dispatcher {
1695
1875
  }
1696
1876
  }
1697
1877
 
1878
+ /** A foreign hosted-harvest execution still open after this tick's
1879
+ * settlement, and observable by its owning provider: the guest is the live
1880
+ * supervisor of its run, so no launch (and so no runner-loss judgment on
1881
+ * its open session) may happen until settlement journals its release. An
1882
+ * unobservable execution never blocks — settlement could never release it. */
1883
+ private liveForeignHarvestExecution(open: readonly OpenHarvestExecution[]): boolean {
1884
+ if (open.length === 0) return false
1885
+ const active = this.deps.activeHarvestExecutions?.() ?? new Set<string>()
1886
+ return open.some(
1887
+ (execution) =>
1888
+ !active.has(execution.execution) &&
1889
+ execution.commandId !== undefined &&
1890
+ this.executionOwner(execution.provider)?.harvestExecution?.observe !== undefined,
1891
+ )
1892
+ }
1893
+
1698
1894
  /** Durable idle settlement for operator sandboxes (AUT-340), staged after
1699
1895
  * harvest settlement: every journal-live environment whose latest evidence
1700
1896
  * is older than `[orchestrator].sandbox.idleMinutes` is stopped through the
@@ -1810,6 +2006,7 @@ export class Dispatcher {
1810
2006
  report.sandboxIdleStops += 1
1811
2007
  }
1812
2008
  } catch (error) {
2009
+ rethrowAuthorityLapse(error)
1813
2010
  // Contained: the next tick retries this environment.
1814
2011
  report.sandboxSettleFailures += 1
1815
2012
  report.janitorDiagnostics.push(
@@ -1855,7 +2052,7 @@ export class Dispatcher {
1855
2052
  autoMergeDefaultSeq?: number
1856
2053
  assets?: PinnedAsset[]
1857
2054
  },
1858
- ): Promise<'kicked' | 'in-flight' | 'foreign-live'> {
2055
+ ): Promise<'kicked' | 'in-flight' | 'foreign-live' | 'slot-wait'> {
1859
2056
  const slug = record.slug
1860
2057
  if (!this.accountsAvailable()) return 'in-flight'
1861
2058
  if (this.continuations.has(slug)) return 'in-flight'
@@ -1876,8 +2073,12 @@ export class Dispatcher {
1876
2073
  }
1877
2074
  // Expired lease, failed attempt, or an old lease-less marker: adopt.
1878
2075
  }
2076
+ // A finished leaf waits for a slot before its continuation reserves one.
2077
+ // Nothing is written: the wait costs no attempt and raises no attention.
2078
+ if (tail === 'launch' && !(await this.leafAdmission(slug))) return 'slot-wait'
1879
2079
  const branch = record.branch ?? `ab/${slug}`
1880
2080
  const generation = events.workspaceGenerations
2081
+ if (this.deps.holdsRepoAuthority?.() === false) return 'in-flight'
1881
2082
  await this.store.append(slug, {
1882
2083
  actor: DISPATCHER,
1883
2084
  type: 'workspace.provision-started',
@@ -1995,6 +2196,9 @@ export class Dispatcher {
1995
2196
  remote: workspaces.publication !== undefined,
1996
2197
  branch: handle.branch,
1997
2198
  base: handle.base,
2199
+ ...(handle.restorationSkipped?.length
2200
+ ? { restorationSkipped: handle.restorationSkipped }
2201
+ : {}),
1998
2202
  },
1999
2203
  } satisfies EventWrite<'workspace.provisioned'>)
2000
2204
  // Release before the launch: the launcher re-claims the lease under the
@@ -2013,8 +2217,13 @@ export class Dispatcher {
2013
2217
  const queued = (await readBuildFacts(store, slug)).value.state.status === 'queued'
2014
2218
  boundary = input.tail === 'dispatch' || queued ? 'dispatch' : 'launch'
2015
2219
  if (boundary === 'dispatch') await this.completeDispatchBoundaries(record, input.seed)
2016
- else if (this.accountsAvailable()) await this.deps.launchRunner(slug)
2220
+ // Deliberately ungated: admission was decided when this continuation
2221
+ // was kicked, and its lease and map entry have held the slot since.
2222
+ else if (this.accountsAvailable()) await this.startRunner(slug, emptyTickReport())
2017
2223
  } catch (error) {
2224
+ // A lapsed repository lease started nothing: no failure fact. The
2225
+ // finally releases the execution lease; the successor adopts the marker.
2226
+ if (isRepositoryAuthorityLapse(error)) return
2018
2227
  // Dispatch boundaries own their failure facts and exhaustion repair.
2019
2228
  // A failed tail read/write leaves durable unfinished work for the next
2020
2229
  // tick; it is not another provider workspace failure. Replacement
@@ -2135,6 +2344,7 @@ export class Dispatcher {
2135
2344
  try {
2136
2345
  await reportIntegrationFailures(this.store, record.slug)
2137
2346
  } catch (error) {
2347
+ rethrowAuthorityLapse(error)
2138
2348
  report.janitorDiagnostics.push(
2139
2349
  `build ${record.slug}: integration attention recovery failed — ${String(error)}`,
2140
2350
  )
@@ -2148,6 +2358,8 @@ export class Dispatcher {
2148
2358
  if (this.outOfBudget(opts)) break
2149
2359
  await withForgeRequestContext({ build: record.slug }, async () => {
2150
2360
  let previous: BuildState['janitor']
2361
+ // The stage in progress, named if this attempt's failure escalates.
2362
+ let operation: JanitorOperation = 'build state read'
2151
2363
  let attempted = false
2152
2364
  let failed = false
2153
2365
  try {
@@ -2163,12 +2375,8 @@ export class Dispatcher {
2163
2375
  (state.pr &&
2164
2376
  state.landing?.command &&
2165
2377
  state.landing.command.seq !== state.landing.acknowledgedSeq)
2166
- if (
2167
- !controlDue &&
2168
- previous &&
2169
- Date.parse(previous.nextAttemptAt) > this.deps.clock().getTime()
2170
- )
2171
- return
2378
+ // Read the clock only inside an episode, as before episodes could escalate.
2379
+ if (!controlDue && previous && !janitorDue(previous, this.deps.clock())) return
2172
2380
  if (mixedVersionDeferred(state)) {
2173
2381
  await deferMixedVersion(this.store, record.slug)
2174
2382
  return
@@ -2269,6 +2477,7 @@ export class Dispatcher {
2269
2477
  state.pr &&
2270
2478
  state.landing?.native?.operation
2271
2479
  ) {
2480
+ operation = 'native auto-merge cancellation'
2272
2481
  const path = this.forgeWorkspacePathOf(workspace)
2273
2482
  const observed = await this.deps.forge.getPrState(path, state.pr.number)
2274
2483
  observedPr = observed
@@ -2306,6 +2515,7 @@ export class Dispatcher {
2306
2515
  state.integration?.landing?.operation &&
2307
2516
  !state.integration.audit
2308
2517
  ) {
2518
+ operation = 'integration landing audit'
2309
2519
  await this.withKernelRepository((path) =>
2310
2520
  auditIntegrationLanding({
2311
2521
  store: this.store,
@@ -2319,6 +2529,7 @@ export class Dispatcher {
2319
2529
  }
2320
2530
  if (state.status === 'done') {
2321
2531
  if (digest.reclaimPending === true) {
2532
+ operation = 'PR attachment reclaim'
2322
2533
  await this.reclaimPrAttachments(record.slug, await history())
2323
2534
  }
2324
2535
  return
@@ -2328,6 +2539,7 @@ export class Dispatcher {
2328
2539
  state.pendingCommands.find((c) => c.command === 'abort') ??
2329
2540
  state.pendingCommands.at(0)
2330
2541
  if (command !== undefined && !executionLeaseLive) {
2542
+ operation = 'control command'
2331
2543
  await this.store.append(record.slug, {
2332
2544
  actor: DISPATCHER,
2333
2545
  type:
@@ -2338,16 +2550,19 @@ export class Dispatcher {
2338
2550
  : 'build.resumed',
2339
2551
  payload: {},
2340
2552
  })
2341
- if (command.command === 'abort')
2553
+ if (command.command === 'abort') {
2554
+ operation = 'abort cleanup'
2342
2555
  await this.cleanupAborted(record, await history(), report)
2556
+ }
2343
2557
  return
2344
2558
  }
2345
2559
  if (state.nodeOpened) {
2560
+ operation = 'target observation'
2346
2561
  let primed = false
2347
2562
  if (
2348
2563
  record.branch &&
2349
2564
  state.baseBranch &&
2350
- !((state.status === 'paused' || state.status === 'blocked') && !state.pr)
2565
+ !((state.status === 'paused' || janitorBlocked(state)) && !state.pr)
2351
2566
  ) {
2352
2567
  primed = await this.primeNodeReads(record, state, report)
2353
2568
  }
@@ -2361,6 +2576,7 @@ export class Dispatcher {
2361
2576
  )
2362
2577
  ).state !== 'open'
2363
2578
  ) {
2579
+ operation = 'PR check'
2364
2580
  await this.checkPr(
2365
2581
  record,
2366
2582
  {
@@ -2386,8 +2602,9 @@ export class Dispatcher {
2386
2602
  await this.primeNodeReads(record, state, report)
2387
2603
  }
2388
2604
  }
2389
- if ((state.status === 'paused' || state.status === 'blocked') && !state.pr) return
2605
+ if ((state.status === 'paused' || janitorBlocked(state)) && !state.pr) return
2390
2606
  if (state.nodeOpened && state.baseBranch) {
2607
+ operation = 'target observation'
2391
2608
  if (
2392
2609
  await this.observeTarget(
2393
2610
  record.slug,
@@ -2403,11 +2620,12 @@ export class Dispatcher {
2403
2620
  if (
2404
2621
  state.nodeOpened &&
2405
2622
  state.status !== 'paused' &&
2406
- (state.status !== 'blocked' || integrationFailed(state)) &&
2623
+ (!janitorBlocked(state) || integrationFailed(state)) &&
2407
2624
  state.prState !== 'merged' &&
2408
2625
  state.prState !== 'closed' &&
2409
2626
  !executionLeaseLive
2410
2627
  ) {
2628
+ operation = 'node cascade'
2411
2629
  await this.prepareIntegration(record, state, report, launched, { refreshOnly: true })
2412
2630
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
2413
2631
  await this.cascadeNode(record, state, report, launched, opts)
@@ -2415,11 +2633,13 @@ export class Dispatcher {
2415
2633
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
2416
2634
  }
2417
2635
  if (state.nodeOpened && !executionLeaseLive) {
2636
+ operation = 'node integration'
2418
2637
  await this.prepareIntegration(record, state, report, launched)
2419
2638
  loaded = undefined
2420
2639
  ;({ state, workspace, log } = await this.store.buildFacts(record.slug))
2421
2640
  }
2422
2641
  if (state.nodeOpened !== undefined && state.pr === undefined) {
2642
+ operation = 'empty node poll'
2423
2643
  await this.pollEmptyNode(record, state)
2424
2644
  await completeNodePoll()
2425
2645
  return
@@ -2429,7 +2649,7 @@ export class Dispatcher {
2429
2649
  // discard when both requests raced into the same stream.
2430
2650
  if (
2431
2651
  !executionLeaseLive &&
2432
- state.status === 'queued' &&
2652
+ janitorStatus(state) === 'queued' &&
2433
2653
  state.pendingCommands.some((command) => command.command === 'abort')
2434
2654
  ) {
2435
2655
  const acknowledged = await this.store.append(record.slug, {
@@ -2440,6 +2660,7 @@ export class Dispatcher {
2440
2660
  void acknowledged
2441
2661
  // The view folded the acknowledgement it just appended.
2442
2662
  loaded = undefined
2663
+ operation = 'abort cleanup'
2443
2664
  await this.cleanupAborted(record, await history(), report)
2444
2665
  return
2445
2666
  }
@@ -2448,19 +2669,26 @@ export class Dispatcher {
2448
2669
  // runner's workspace down or return its ticket for a duplicate build.
2449
2670
  if (
2450
2671
  !executionLeaseLive &&
2451
- state.status === 'queued' &&
2672
+ janitorStatus(state) === 'queued' &&
2452
2673
  state.discardRequest !== undefined
2453
2674
  ) {
2675
+ operation = 'discard cleanup'
2454
2676
  await this.cleanupDiscarded(record, await history(), report)
2455
2677
  return
2456
2678
  }
2457
2679
  if (!executionLeaseLive && state.status === 'aborted') {
2680
+ operation = 'abort cleanup'
2458
2681
  await this.cleanupAborted(record, await history(), report)
2459
2682
  return
2460
2683
  }
2684
+ operation = 'target observation'
2461
2685
  if (state.kind !== 'node' && state.status !== 'aborted')
2462
2686
  await this.observeTicketTarget(record, state, report)
2463
- if (state.kind !== 'node' && state.status !== 'aborted' && state.status !== 'queued') {
2687
+ if (
2688
+ state.kind !== 'node' &&
2689
+ state.status !== 'aborted' &&
2690
+ janitorStatus(state) !== 'queued'
2691
+ ) {
2464
2692
  const branch = await readBuildSelector(this.store, record.slug, 'baseBranch')
2465
2693
  if (branch !== undefined) {
2466
2694
  if (await this.observeTarget(record.slug, branch, log.restack.target?.sha, report)) {
@@ -2471,7 +2699,7 @@ export class Dispatcher {
2471
2699
  }
2472
2700
  if (
2473
2701
  state.kind !== 'node' &&
2474
- state.status !== 'queued' &&
2702
+ janitorStatus(state) !== 'queued' &&
2475
2703
  state.status !== 'aborted' &&
2476
2704
  state.prState !== 'merged' &&
2477
2705
  state.prState !== 'closed'
@@ -2496,11 +2724,8 @@ export class Dispatcher {
2496
2724
  forge: this.deps.forge,
2497
2725
  })
2498
2726
  } catch (error) {
2499
- if (
2500
- error instanceof ForgeRequestDeferred ||
2501
- (isForgeFailure(error) && error.details.kind === 'rate-limited')
2502
- )
2503
- throw error
2727
+ rethrowAuthorityLapse(error)
2728
+ if (janitorDeferral(error)) throw error
2504
2729
  if (facts.log.restack.distance?.count != null)
2505
2730
  report.janitorDiagnostics.push(
2506
2731
  `build ${record.slug}: target distance failed — ${error instanceof Error ? error.message : String(error)}`,
@@ -2531,6 +2756,7 @@ export class Dispatcher {
2531
2756
  }
2532
2757
  }
2533
2758
  if (state.pr) {
2759
+ operation = 'PR check'
2534
2760
  await this.checkPr(
2535
2761
  record,
2536
2762
  {
@@ -2549,7 +2775,15 @@ export class Dispatcher {
2549
2775
  }
2550
2776
  await completeNodePoll()
2551
2777
  } catch (error) {
2552
- if (error instanceof ForgeRequestDeferred) {
2778
+ // A lapsed repository lease is not this build's janitor failure.
2779
+ if (isRepositoryAuthorityLapse(error)) {
2780
+ attempted = false
2781
+ throw error
2782
+ }
2783
+ // The guarded forge already recorded a classified rate limit as repository
2784
+ // degradation; like the cooldown that follows it, it neither starts nor ages
2785
+ // this build's janitor episode.
2786
+ if (janitorDeferral(error)) {
2553
2787
  attempted = false
2554
2788
  return
2555
2789
  }
@@ -2567,6 +2801,7 @@ export class Dispatcher {
2567
2801
  message,
2568
2802
  this.deps.clock(),
2569
2803
  this.deps.config.policy,
2804
+ operation,
2570
2805
  )
2571
2806
  report.janitorFailed += 1
2572
2807
  report.janitorDiagnostics.push(`build ${record.slug}: janitor failed — ${message}`)
@@ -2598,11 +2833,8 @@ export class Dispatcher {
2598
2833
  })
2599
2834
  return true
2600
2835
  } catch (error) {
2601
- if (
2602
- error instanceof ForgeRequestDeferred ||
2603
- (isForgeFailure(error) && error.details.kind === 'rate-limited')
2604
- )
2605
- throw error
2836
+ rethrowAuthorityLapse(error)
2837
+ if (janitorDeferral(error)) throw error
2606
2838
  report.janitorDiagnostics.push(
2607
2839
  `build ${record.slug}: node read priming failed — ${error instanceof Error || isForgeFailure(error) ? error.message : String(error)}`,
2608
2840
  )
@@ -2629,6 +2861,7 @@ export class Dispatcher {
2629
2861
  if (state.kind === 'node') await this.observeNodeParent(record, state, report)
2630
2862
  else await this.observeWorkTarget(record, state, report)
2631
2863
  } catch (error) {
2864
+ rethrowAuthorityLapse(error)
2632
2865
  report.janitorDiagnostics.push(
2633
2866
  `build ${record.slug}: ticket target observation failed — ${error instanceof Error || isForgeFailure(error) ? error.message : String(error)}`,
2634
2867
  )
@@ -2801,6 +3034,7 @@ export class Dispatcher {
2801
3034
  )
2802
3035
  throw new Error('destination generation changed; retry target update')
2803
3036
  } catch (error) {
3037
+ rethrowAuthorityLapse(error)
2804
3038
  if (request)
2805
3039
  await this.store.append(record.slug, {
2806
3040
  actor: DISPATCHER,
@@ -2868,6 +3102,7 @@ export class Dispatcher {
2868
3102
  })) !== 'unchanged'
2869
3103
  )
2870
3104
  } catch (error) {
3105
+ rethrowAuthorityLapse(error)
2871
3106
  const message =
2872
3107
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
2873
3108
  report.janitorDiagnostics.push(`build ${slug}: target observation failed — ${message}`)
@@ -2887,8 +3122,10 @@ export class Dispatcher {
2887
3122
  return open?.localPath ?? open?.path ?? open?.ref ?? this.deps.checkout ?? this.deps.repo
2888
3123
  }
2889
3124
 
2890
- /** Deferral withholds decisions, but cannot free an existing capacity reservation. */
2891
- private async capacityBuilds(): Promise<CapacityBuild[]> {
3125
+ /** Deferral withholds decisions, but cannot free an existing capacity reservation.
3126
+ * A leaf's runner reservation is this process's continuation or a launch
3127
+ * this tick; another process's continuation holds a heartbeat lease. */
3128
+ private async capacityBuilds(launched?: ReadonlySet<string>): Promise<CapacityBuild[]> {
2892
3129
  const builds: CapacityBuild[] = []
2893
3130
  for (const { record, digest } of await this.repoBuildDigests(true)) {
2894
3131
  if (digest.terminal) continue
@@ -2898,13 +3135,82 @@ export class Dispatcher {
2898
3135
  state: facts.state,
2899
3136
  workspace: facts.workspace !== null,
2900
3137
  provisioning:
2901
- digest.kind === 'node' &&
2902
- (await readBuildFacts(this.store, record.slug)).value.provisionMarker !== undefined,
3138
+ digest.kind === 'node'
3139
+ ? (await readBuildFacts(this.store, record.slug)).value.provisionMarker !== undefined
3140
+ : this.continuations.has(record.slug) || !!launched?.has(record.slug),
3141
+ restackDue: landingRestackDue(facts.state, facts.log),
2903
3142
  })
2904
3143
  }
2905
3144
  return builds
2906
3145
  }
2907
3146
 
3147
+ /** Whether a leaf may reserve a runner now. A leaf that has not finished its
3148
+ * pipeline already holds its slot, and abort and pause acknowledgements park
3149
+ * at once, so only a finished leaf that must run again is gated: it needs
3150
+ * a free slot among every other build. A denial is recorded only in memory,
3151
+ * for this tick's intake reservation. */
3152
+ private async leafAdmission(slug: string): Promise<boolean> {
3153
+ const { state } = await this.store.buildFacts(slug)
3154
+ if (
3155
+ !epilogueLeaf(state) ||
3156
+ state.pendingCommands.some(
3157
+ (command) => command.command === 'abort' || command.command === 'pause',
3158
+ )
3159
+ )
3160
+ return true
3161
+ const others = (await this.capacityBuilds(this.tickLaunched)).filter(
3162
+ (build) => build.record.slug !== slug,
3163
+ )
3164
+ const capacity = this.deps.config.capacity
3165
+ if (dispatchCapacity(others, capacity, this.deps.clock()).occupied < capacity) {
3166
+ this.slotWaiters.delete(slug)
3167
+ return true
3168
+ }
3169
+ this.slotWaiters.add(slug)
3170
+ return false
3171
+ }
3172
+
3173
+ /** Admit every node awaiting verification that has a slot, in slug order,
3174
+ * through the janitor's own admission path. Independent of `acceptNewWork`:
3175
+ * node admission is existing work, never intake. */
3176
+ private async admitWaitingNodes(
3177
+ report: TickReport,
3178
+ launched: Set<string>,
3179
+ opts: TickOpts,
3180
+ ): Promise<void> {
3181
+ if (
3182
+ !(await this.repoBuildDigests()).some(
3183
+ ({ digest }) => digest.kind === 'node' && digest.terminal === undefined,
3184
+ )
3185
+ )
3186
+ return
3187
+ const now = this.deps.clock()
3188
+ const waiting = (await this.capacityBuilds())
3189
+ .filter((build) => slotRequest(build, now) === 'verification')
3190
+ .sort((a, b) => (a.record.slug < b.record.slug ? -1 : a.record.slug > b.record.slug ? 1 : 0))
3191
+ for (const { record, state } of waiting) {
3192
+ if (this.outOfBudget(opts)) return
3193
+ if (
3194
+ launched.has(record.slug) ||
3195
+ this.hasLiveExecutionLease(record) ||
3196
+ !state.nodeOpened ||
3197
+ !janitorDue(state.janitor, now)
3198
+ )
3199
+ continue
3200
+ await withForgeRequestContext({ build: record.slug }, async () => {
3201
+ try {
3202
+ if (!(await this.nodeHasCapacity(record.slug))) return
3203
+ await this.prepareIntegration(record, state, report, launched)
3204
+ } catch (error) {
3205
+ rethrowAuthorityLapse(error)
3206
+ report.janitorDiagnostics.push(
3207
+ `build ${record.slug}: node admission failed — ${String(error)}`,
3208
+ )
3209
+ }
3210
+ })
3211
+ }
3212
+ }
3213
+
2908
3214
  private async nodeHasCapacity(slug: string): Promise<boolean> {
2909
3215
  const builds = await this.capacityBuilds()
2910
3216
  return (
@@ -2927,6 +3233,25 @@ export class Dispatcher {
2927
3233
  /** Complete abort cleanup as an ordered checkpointed saga. External effects
2928
3234
  * are idempotent; a fact after each one prevents already-settled work from
2929
3235
  * repeating on later ticks. `build.completed` is deliberately last. */
3236
+ /** Record a landed child's effective issue links on its target node, once
3237
+ * per child (SPEC "Forge issue links"). Reduced reads only: the child's
3238
+ * refreshed state and the node's union, never any child history. */
3239
+ private async recordNodeIssueLinks(slug: string): Promise<void> {
3240
+ const state = (await this.store.buildFacts(slug)).state
3241
+ if (state.target === undefined) return
3242
+ const issueLinks = contributedIssueLinks(state)
3243
+ if (issueLinks.length === 0) return
3244
+ const node = (await this.store.buildFacts(state.target.build)).state
3245
+ // Every contributing child gets its own fact, even when the union does
3246
+ // not change; the recorded set is the durable retry evidence.
3247
+ if (node.nodeIssueLinks?.builds.includes(slug)) return
3248
+ await this.store.append(state.target.build, {
3249
+ actor: DISPATCHER,
3250
+ type: 'node.issue-links-recorded',
3251
+ payload: { build: slug, issueLinks },
3252
+ } satisfies EventWrite<'node.issue-links-recorded'>)
3253
+ }
3254
+
2930
3255
  private async cleanupAborted(
2931
3256
  record: BuildRecord,
2932
3257
  events: CurrentBuildFacts,
@@ -2995,6 +3320,7 @@ export class Dispatcher {
2995
3320
  Object.assign(events, (await readBuildFacts(store, record.slug)).value)
2996
3321
  }
2997
3322
  const fail = (operation: string, identity: string, error: unknown): never => {
3323
+ rethrowAuthorityLapse(error)
2998
3324
  if (error instanceof ForgeCooldown || isForgeFailure(error)) throw error
2999
3325
  const detail = error instanceof Error || isForgeFailure(error) ? error.message : String(error)
3000
3326
  throw new Error(
@@ -3047,6 +3373,9 @@ export class Dispatcher {
3047
3373
  }
3048
3374
  }
3049
3375
 
3376
+ // A child the forge reports merged still carries its links up to its node.
3377
+ if (events.state.prState === 'merged') await this.recordNodeIssueLinks(record.slug)
3378
+
3050
3379
  try {
3051
3380
  const released = await this.releaseWorkspace(record.slug, events, 'abort')
3052
3381
  if (released !== undefined)
@@ -3196,6 +3525,7 @@ export class Dispatcher {
3196
3525
  const message = await read.call(this.deps.forge, workspacePath, sha)
3197
3526
  return { sha, buildTrailerPresent: hasBuildTrailer(message, record.slug) }
3198
3527
  } catch (error) {
3528
+ rethrowAuthorityLapse(error)
3199
3529
  await this.store.append(record.slug, {
3200
3530
  actor: KERNEL,
3201
3531
  type: 'observation.recorded',
@@ -3265,6 +3595,21 @@ export class Dispatcher {
3265
3595
  throw new Error('node-target native auto-merge cancellation unconfirmed')
3266
3596
  nativeCancelled = true
3267
3597
  }
3598
+ // Keep a node PR's keyword lines on its set (refs-only into a parent). A
3599
+ // pure comparison with the last confirmed readback: no forge call while
3600
+ // nothing changed.
3601
+ const issueLinksPending =
3602
+ integration && prState.state === 'open' && !executionLeaseLive
3603
+ ? nodeIssueLinksSyncPending(state, forge)
3604
+ : undefined
3605
+ if (issueLinksPending) {
3606
+ await forge.updatePrIssueLinks!(workspacePath, pr.number, issueLinksPending)
3607
+ await store.append(record.slug, {
3608
+ actor: DISPATCHER,
3609
+ type: 'node.issue-links-published',
3610
+ payload: { pr: pr.number, issueLinks: issueLinksPending },
3611
+ } satisfies EventWrite<'node.issue-links-published'>)
3612
+ }
3268
3613
  // Converge native state on every poll, including paused and unready builds.
3269
3614
  // A replacement publication invalidates readiness, even if a stale enable
3270
3615
  // finished after the publisher confirmed cancellation.
@@ -3274,7 +3619,7 @@ export class Dispatcher {
3274
3619
  candidate.status === 'paused' ||
3275
3620
  candidate.status === 'done' ||
3276
3621
  candidate.status === 'aborted' ||
3277
- candidate.openEscalations.length ||
3622
+ escalationsBeyondJanitor(candidate).length ||
3278
3623
  candidate.pendingCommands.length
3279
3624
  )
3280
3625
  return false
@@ -3289,7 +3634,12 @@ export class Dispatcher {
3289
3634
  )
3290
3635
  }
3291
3636
  const facts = await store.buildFacts(record.slug)
3292
- const decision = await this.decideBuild(record.slug, facts.state, facts.log, report)
3637
+ const decision = await this.decideBuild(
3638
+ record.slug,
3639
+ withoutJanitorEscalation(facts.state),
3640
+ facts.log,
3641
+ report,
3642
+ )
3293
3643
  return decision?.kind === 'wait' && decision.reason === 'awaiting-pr'
3294
3644
  }
3295
3645
  const candidateOf = async (current: BuildState) =>
@@ -3432,6 +3782,19 @@ export class Dispatcher {
3432
3782
  report.conflicted += 1
3433
3783
  return
3434
3784
  }
3785
+ // A finished build keeps its workspace while parked, even after its
3786
+ // environment was lost; the lease sweep reaps and replaces it once the
3787
+ // build is admitted, never a runner started in the lost environment.
3788
+ const retained = openWorkspace(events)
3789
+ if (
3790
+ retained !== null &&
3791
+ this.workspaceOwner(retained)?.recovery !== undefined &&
3792
+ (events.lastExecution === 'lost' || events.lastExecution === 'stopped') &&
3793
+ epilogueLeaf(events.state)
3794
+ ) {
3795
+ report.conflicted += 1
3796
+ return
3797
+ }
3435
3798
  // The dispatcher never runs agents (§15.7): re-attach a build-runner,
3436
3799
  // which executes the reconcile epilogue phase.
3437
3800
  await this.launch(record.slug, launched, report)
@@ -3460,7 +3823,7 @@ export class Dispatcher {
3460
3823
  candidate.status === 'paused' ||
3461
3824
  candidate.status === 'done' ||
3462
3825
  candidate.status === 'aborted' ||
3463
- candidate.openEscalations.length ||
3826
+ escalationsBeyondJanitor(candidate).length ||
3464
3827
  candidate.pendingCommands.length ||
3465
3828
  !integrationVerified(
3466
3829
  candidate,
@@ -3479,14 +3842,19 @@ export class Dispatcher {
3479
3842
  current.status !== 'paused' &&
3480
3843
  current.status !== 'aborted' &&
3481
3844
  current.status !== 'done' &&
3482
- !current.openEscalations.length &&
3845
+ !escalationsBeyondJanitor(current).length &&
3483
3846
  !current.pendingCommands.length &&
3484
3847
  integrationVerified(current, config) &&
3485
3848
  cycle?.head === exact.headSha &&
3486
3849
  cycle.parent === exact.parentSha
3487
3850
  )
3488
3851
  }
3489
- const decision = await this.decideBuild(record.slug, latest.state, latest.log, report)
3852
+ const decision = await this.decideBuild(
3853
+ record.slug,
3854
+ withoutJanitorEscalation(latest.state),
3855
+ latest.log,
3856
+ report,
3857
+ )
3490
3858
  return (
3491
3859
  latest.state.pr?.number === pr.number &&
3492
3860
  latest.state.prState === 'open' &&
@@ -3613,17 +3981,24 @@ export class Dispatcher {
3613
3981
  sameLandingCandidate(native.candidate, state.landing?.decision?.candidate)
3614
3982
  ? native.retry
3615
3983
  : undefined)
3984
+ const acknowledged = nativeLandingApplied(state.landing) && !state.landing?.nativeEnablePending
3985
+ // SPEC §15.7: an armed, acknowledged request gets the forge's identity
3986
+ // readback on every eligible poll. No consent read or event while it matches.
3987
+ const maintain =
3988
+ acknowledged &&
3989
+ prState.state === 'open' &&
3990
+ prState.nativeAutoMerge === true &&
3991
+ !nativeCancelled &&
3992
+ isReady
3616
3993
  if (
3617
3994
  !integration &&
3618
3995
  !nodeTarget &&
3619
3996
  prState.state === 'open' &&
3620
3997
  landingAuthorized(state.landing) &&
3621
- (prState.nativeAutoMerge === false ||
3622
- !nativeLandingApplied(state.landing) ||
3623
- !!state.landing?.nativeEnablePending) &&
3998
+ (prState.nativeAutoMerge === false || !acknowledged || maintain) &&
3624
3999
  (!retry || Date.parse(retry.after) <= this.deps.clock().getTime()) &&
3625
4000
  commandSeq !== undefined &&
3626
- (await canApply())
4001
+ (maintain || (await canApply()))
3627
4002
  ) {
3628
4003
  const decision = state.landing!.decision!
3629
4004
  // The provider checks eligibility immediately before mutating. Inspection
@@ -3654,103 +4029,116 @@ export class Dispatcher {
3654
4029
  },
3655
4030
  })
3656
4031
  }
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
- )
4032
+ // An enabled request counts as applied only after the forge confirms
4033
+ // its method and identity message; a mismatch is repaired under consent.
4034
+ const result = await forge
4035
+ .setAutoMerge(workspacePath, pr.number, true, {
4036
+ buildSlug: record.slug,
4037
+ baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
4038
+ ...issueLinksForForge(state, forge),
4039
+ canApply: async () => {
4040
+ if (!(await canApply())) return false
4041
+ if (enableSeq === undefined)
4042
+ enableSeq = (
4043
+ await store.append(record.slug, {
4044
+ actor: DISPATCHER,
4045
+ type: 'landing.native-enable-started',
4046
+ payload: {},
4047
+ })
4048
+ ).seq
4049
+ return true
4050
+ },
4051
+ })
4052
+ .catch(async (error: unknown) => {
4053
+ if (isForgeFailure(error)) {
4054
+ const attempt = (retry?.attempt ?? 0) + 1
3718
4055
  await store.append(record.slug, {
3719
4056
  actor: DISPATCHER,
3720
- type: 'landing.native-applied',
4057
+ type: 'landing.application-failed',
3721
4058
  payload: {
3722
- enabled: true,
3723
- ...(enableSeq !== undefined ? { enableSeq } : {}),
3724
4059
  candidate: decision.candidate,
3725
4060
  decisionSeq: decision.seq,
3726
- ...(latest.landing?.command ? { commandSeq: latest.landing.command.seq } : {}),
4061
+ ...(state.landing?.command ? { commandSeq: state.landing.command.seq } : {}),
4062
+ message: error.message,
4063
+ attempt,
4064
+ after: new Date(
4065
+ Math.max(
4066
+ this.deps.clock().getTime() +
4067
+ Math.min(300_000, 30_000 * 2 ** Math.min(attempt - 1, 4)),
4068
+ error.details.kind === 'rate-limited' ? Date.parse(error.details.resetAt) : 0,
4069
+ ),
4070
+ ).toISOString(),
3727
4071
  },
3728
4072
  })
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,
4073
+ // An uncertain enable stays pending. Never spend another request during a limit.
4074
+ throw error
4075
+ }
4076
+ await settleFailedEnable()
4077
+ throw error
3753
4078
  })
4079
+ if (maintain && enableSeq === undefined) {
4080
+ // Quiet maintenance: no consent check passed, so nothing was mutated.
4081
+ // A vanished request is reconciled by the next poll's PR read.
4082
+ if (result.kind === 'deferred' && result.reason)
4083
+ await recordAutoMergeDeferralObservation(
4084
+ store,
4085
+ record.slug,
4086
+ result.reason,
4087
+ pr.number,
4088
+ commandSeq,
4089
+ this.deps.ids('obs'),
4090
+ )
4091
+ } else {
4092
+ // Only an attempt that reached the mutation guard needs cancellation.
4093
+ // Persist retry timing with its receipt so restart cannot reset backoff.
4094
+ if (result.kind !== 'applied') await settleFailedEnable()
4095
+ if (result.kind === 'applied') {
4096
+ const latest = (await store.buildFacts(record.slug)).state
4097
+ if (await canApply()) {
4098
+ if (
4099
+ latest.landing?.nativeEnablePending ||
4100
+ latest.landing?.native?.enabled !== true ||
4101
+ latest.landing.native.decisionSeq !== decision.seq ||
4102
+ latest.landing.native.commandSeq !== latest.landing.command?.seq
4103
+ )
4104
+ await store.append(record.slug, {
4105
+ actor: DISPATCHER,
4106
+ type: 'landing.native-applied',
4107
+ payload: {
4108
+ enabled: true,
4109
+ ...(enableSeq !== undefined ? { enableSeq } : {}),
4110
+ candidate: decision.candidate,
4111
+ decisionSeq: decision.seq,
4112
+ ...(latest.landing?.command ? { commandSeq: latest.landing.command.seq } : {}),
4113
+ },
4114
+ })
4115
+ } else {
4116
+ // Enable may have won after cancellation. Repair immediately, and
4117
+ // again on the next poll if this process dies at this boundary.
4118
+ const cancelled = await forge.setAutoMerge(workspacePath, pr.number, false)
4119
+ if (cancelled.kind === 'applied')
4120
+ await store.append(record.slug, {
4121
+ actor: DISPATCHER,
4122
+ type: 'landing.native-applied',
4123
+ payload: { enabled: false, ...(enableSeq !== undefined ? { enableSeq } : {}) },
4124
+ })
4125
+ }
4126
+ } else if (result.kind === 'deferred' && result.reason) {
4127
+ await recordAutoMergeDeferralObservation(
4128
+ store,
4129
+ record.slug,
4130
+ result.reason,
4131
+ pr.number,
4132
+ commandSeq,
4133
+ this.deps.ids('obs'),
4134
+ )
4135
+ } else if (result.kind === 'ungated' && prState.mergeable === true && (await canApply())) {
4136
+ await forge.squashMerge(workspacePath, pr.number, result.headSha, {
4137
+ buildSlug: record.slug,
4138
+ baseBranch: state.baseBranch ?? this.deps.config.baseBranch,
4139
+ ...issueLinksForForge(state, forge),
4140
+ })
4141
+ }
3754
4142
  }
3755
4143
  }
3756
4144
 
@@ -3865,6 +4253,9 @@ export class Dispatcher {
3865
4253
  payload: await this.mergeEvidence(record, workspacePath, prState.sha, state.kind),
3866
4254
  } satisfies EventWrite<'pr.merged'>)
3867
4255
  }
4256
+ // Before the child can become terminal, so a complete node already
4257
+ // folds every landed child's links; the node log dedupes a retry.
4258
+ await this.recordNodeIssueLinks(record.slug)
3868
4259
  await this.releaseWorkspace(record.slug, events)
3869
4260
  if (record.ticket) {
3870
4261
  await tickets.transition(await this.currentTicketId(record), this.doneState)
@@ -3944,6 +4335,7 @@ export class Dispatcher {
3944
4335
  payload: { hostedSeq: hosted.seq },
3945
4336
  })
3946
4337
  } catch (error) {
4338
+ rethrowAuthorityLapse(error)
3947
4339
  if (error instanceof ForgeCooldown) throw error
3948
4340
  try {
3949
4341
  await this.store.append(slug, {
@@ -3972,11 +4364,26 @@ export class Dispatcher {
3972
4364
  input: Parameters<WorkspaceProvider['provision']>[0],
3973
4365
  ) {
3974
4366
  const facts = (await readBuildFacts(this.store, slug)).value
4367
+ const { restoration, superseded } = supersedeRestorationHeads(
4368
+ facts.workspacePreservation?.payload.heads,
4369
+ facts.replacedHeads,
4370
+ )
3975
4371
  try {
3976
- return await this.deps.workspaces.provision({
4372
+ const handle = await this.deps.workspaces.provision({
3977
4373
  ...input,
3978
- restoration: facts.workspacePreservation?.payload.heads,
4374
+ restoration,
4375
+ ...(facts.replacedHeads.length ? { restorationReplaced: facts.replacedHeads } : {}),
4376
+ // Same predicate preservation archives under: only local-git keeps
4377
+ // archive refs in the local repository.
4378
+ ...(restoration?.length
4379
+ ? { restorationArchives: this.deps.forge.name === 'local-git' ? 'local' : 'remote' }
4380
+ : {}),
3979
4381
  })
4382
+ const skipped = [
4383
+ ...superseded.map((sha) => ({ sha, reason: 'superseded' as const })),
4384
+ ...(handle.restorationSkipped ?? []).filter((skip) => !superseded.includes(skip.sha)),
4385
+ ]
4386
+ return skipped.length ? { ...handle, restorationSkipped: skipped } : handle
3980
4387
  } catch (error) {
3981
4388
  if (error instanceof WorkspaceCleanupRequired) {
3982
4389
  await this.store.append(slug, {
@@ -4080,6 +4487,7 @@ export class Dispatcher {
4080
4487
  reason,
4081
4488
  )
4082
4489
  } catch (error) {
4490
+ rethrowAuthorityLapse(error)
4083
4491
  // Keep this generation and its pending work until forge recovery,
4084
4492
  // while allowing the sweep to supervise the remaining builds.
4085
4493
  if (error instanceof ForgeRequestDeferred) return false
@@ -4128,6 +4536,7 @@ export class Dispatcher {
4128
4536
  Object.assign(events, (await readBuildFacts(this.store, slug)).value)
4129
4537
  return true
4130
4538
  } catch (error) {
4539
+ rethrowAuthorityLapse(error)
4131
4540
  const message =
4132
4541
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
4133
4542
  const _failed = await this.store.append(slug, {
@@ -4212,6 +4621,7 @@ export class Dispatcher {
4212
4621
  })
4213
4622
  Object.assign(events, (await readBuildFacts(this.store, slug)).value)
4214
4623
  } catch (error) {
4624
+ rethrowAuthorityLapse(error)
4215
4625
  const message =
4216
4626
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
4217
4627
  const _failed = await this.store.append(slug, {
@@ -4267,8 +4677,9 @@ export class Dispatcher {
4267
4677
 
4268
4678
  // ── b. Interrupted dispatch recovery ───────────────────────────────────────
4269
4679
 
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. */
4680
+ /** The claim-time `build.created` payload. Assets and issue links are
4681
+ * omitted when the ticket had none, so such a build's log is exactly what it
4682
+ * was before. */
4272
4683
  private buildCreatedPayload(
4273
4684
  ticket: TicketRef,
4274
4685
  repo: string,
@@ -4277,6 +4688,7 @@ export class Dispatcher {
4277
4688
  autoMergeUser?: string
4278
4689
  autoMergeDefaultSeq?: number
4279
4690
  assets?: PinnedAsset[]
4691
+ issueLinks?: IssueLink[]
4280
4692
  kind?: 'work' | 'node'
4281
4693
  target?: EventPayload<'build.created'>['target']
4282
4694
  baseBranch?: string
@@ -4296,6 +4708,9 @@ export class Dispatcher {
4296
4708
  : {}),
4297
4709
  ...(config.pr !== undefined ? { pr: config.pr } : {}),
4298
4710
  ...(seed?.assets !== undefined && seed.assets.length > 0 ? { assets: seed.assets } : {}),
4711
+ ...(seed?.issueLinks !== undefined && seed.issueLinks.length > 0
4712
+ ? { issueLinks: seed.issueLinks.map(({ issue, intent }) => ({ issue, intent })) }
4713
+ : {}),
4299
4714
  }
4300
4715
  }
4301
4716
 
@@ -4359,7 +4774,13 @@ export class Dispatcher {
4359
4774
  await store.appendIfCurrent(record.slug, 0, {
4360
4775
  actor: DISPATCHER,
4361
4776
  type: 'build.created',
4362
- payload: this.buildCreatedPayload(record.ticket, record.repo, { ...seed, assets }),
4777
+ payload: this.buildCreatedPayload(record.ticket, record.repo, {
4778
+ ...seed,
4779
+ assets,
4780
+ ...(seed?.ticket.issueLinks !== undefined
4781
+ ? { issueLinks: seed.ticket.issueLinks }
4782
+ : {}),
4783
+ }),
4363
4784
  })
4364
4785
  events = (await readBuildFacts(store, record.slug)).value
4365
4786
  if (events.created === undefined) {
@@ -4426,11 +4847,15 @@ export class Dispatcher {
4426
4847
  remote: this.deps.workspaces.publication !== undefined,
4427
4848
  branch: handle.branch,
4428
4849
  base: handle.base,
4850
+ ...(handle.restorationSkipped?.length
4851
+ ? { restorationSkipped: handle.restorationSkipped }
4852
+ : {}),
4429
4853
  },
4430
4854
  } satisfies EventWrite<'workspace.provisioned'>)
4431
4855
  events = (await readBuildFacts(store, record.slug)).value
4432
4856
  }
4433
4857
  } catch (error) {
4858
+ rethrowAuthorityLapse(error)
4434
4859
  if (await this.holdForMissingAccounts(error)) return 'parked'
4435
4860
  if (error instanceof MixedVersionDeferral) return 'parked'
4436
4861
  const events = (await readBuildFacts(store, record.slug)).value
@@ -4551,7 +4976,7 @@ export class Dispatcher {
4551
4976
  if (record.ticket !== undefined && !events.commentPosted) {
4552
4977
  await this.deps.tickets.comment(
4553
4978
  await this.currentTicketId(record),
4554
- `build ${record.slug} dispatched`,
4979
+ dispatchCommentBody(record.slug),
4555
4980
  )
4556
4981
  await store.append(record.slug, {
4557
4982
  actor: DISPATCHER,
@@ -4579,11 +5004,12 @@ export class Dispatcher {
4579
5004
  return 'parked'
4580
5005
  }
4581
5006
  if (!this.accountsAvailable()) return 'parked'
4582
- if (launched === undefined) await this.deps.launchRunner(record.slug)
5007
+ if (launched === undefined) await this.startRunner(record.slug, report ?? emptyTickReport())
4583
5008
  else await this.launch(record.slug, launched, report)
4584
5009
  if (authored && report !== undefined) report.authored += 1
4585
5010
  return 'completed'
4586
5011
  } catch (error) {
5012
+ rethrowAuthorityLapse(error)
4587
5013
  if (await this.holdForMissingAccounts(error)) return 'parked'
4588
5014
  const events = (await readBuildFacts(store, record.slug)).value
4589
5015
  const attempt = events.dispatchFailureCount + 1
@@ -4743,6 +5169,7 @@ export class Dispatcher {
4743
5169
  try {
4744
5170
  await this.sweepBuild(record, report, launched, paused, now)
4745
5171
  } catch (error) {
5172
+ rethrowAuthorityLapse(error)
4746
5173
  // Per-build containment: one build's failure never stops the sweep
4747
5174
  // from advancing the others. Workspace failures are already durable
4748
5175
  // against the build; a repository-wide cooldown still ends the tick.
@@ -4809,6 +5236,18 @@ export class Dispatcher {
4809
5236
  const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
4810
5237
  if (decision === undefined) return
4811
5238
  if (state.status === 'done' || state.status === 'aborted') return
5239
+ if (decision.kind === 'wait' && decision.reason === 'awaiting-pr' && state.kind !== 'node') {
5240
+ this.parkedSettled.add(record.slug)
5241
+ // The engine reached the end of the pipeline: record it once per
5242
+ // settlement key so capacity stops counting the parked build. A lost
5243
+ // race is decided again next tick.
5244
+ if (settlementDue(state))
5245
+ await this.store.appendIfCurrent(record.slug, state.lastSeq, {
5246
+ actor: DISPATCHER,
5247
+ type: 'pipeline.settled',
5248
+ payload: { cycle: settlementKey(state) },
5249
+ })
5250
+ }
4812
5251
  const orphanEligible = (state: BuildState) =>
4813
5252
  !paused &&
4814
5253
  state.status === 'running' &&
@@ -4902,6 +5341,18 @@ export class Dispatcher {
4902
5341
  // is reaped and replaced by the next generation.
4903
5342
  if (endedInPlace && open !== null && cleanupRequiredWorkspace(await history()))
4904
5343
  endedInPlace = false
5344
+ const runs = decision.kind !== 'wait' || publicationRecoveryDue || orphanRecoveryDue
5345
+ // A finished leaf with work to run waits for a slot before anything is
5346
+ // reaped, provisioned or launched for it.
5347
+ if (runs && state.kind !== 'node' && !(await this.leafAdmission(record.slug))) return
5348
+ // A finished parked leaf keeps its workspace until merge or close; a
5349
+ // stale environment is reaped only for an admitted replacement.
5350
+ if (
5351
+ !runs &&
5352
+ state.kind !== 'node' &&
5353
+ ((decision.kind === 'wait' && decision.reason === 'awaiting-pr') || epilogueLeaf(state))
5354
+ )
5355
+ return
4905
5356
  // A provider- or log-proved END in the same generation re-attaches in
4906
5357
  // place: the guest finished its work, the workspace is still the
4907
5358
  // build's, and replacing the environment would discard a healthy
@@ -4955,6 +5406,7 @@ export class Dispatcher {
4955
5406
  const result = await this.launch(record.slug, launched, report)
4956
5407
  if (result === 'scheduled') report.swept += 1
4957
5408
  } catch (error) {
5409
+ rethrowAuthorityLapse(error)
4958
5410
  // Launchers normally record provider failures themselves. Preserve
4959
5411
  // durable attention if orphan cleanup fails before that boundary,
4960
5412
  // without counting an already-recorded failure twice.
@@ -4993,6 +5445,7 @@ export class Dispatcher {
4993
5445
  try {
4994
5446
  await this.recoverTicketPreparation(attempt)
4995
5447
  } catch (error) {
5448
+ rethrowAuthorityLapse(error)
4996
5449
  failures.push(error)
4997
5450
  }
4998
5451
  }
@@ -5015,10 +5468,19 @@ export class Dispatcher {
5015
5468
  ticket: attempt.ticket,
5016
5469
  outcome,
5017
5470
  ...(reason ? { reason: reason.slice(0, 4000) } : {}),
5471
+ ...(outcome === 'abandoned' ? { claimed: attempt.claimed } : {}),
5018
5472
  },
5019
5473
  })
5020
5474
  }
5021
5475
 
5476
+ /** Durably abandon an attempt, then queue its one operator diagnostic for
5477
+ * this tick. No line exists unless the resolution was appended. */
5478
+ private async abandonPreparation(attempt: TicketPreparation, reason: string): Promise<void> {
5479
+ const recorded = reason.slice(0, 4000)
5480
+ await this.preparationResolved(attempt, 'abandoned', recorded)
5481
+ this.tickAbandonments.push(abandonedPreparationDiagnostic(attempt, recorded))
5482
+ }
5483
+
5022
5484
  private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
5023
5485
  try {
5024
5486
  // A rejected create can have committed. Unavailable or conflicting readback
@@ -5035,9 +5497,8 @@ export class Dispatcher {
5035
5497
  created.payload.ticket?.source !== attempt.ticket.source ||
5036
5498
  created.payload.ticket?.id !== attempt.ticket.id
5037
5499
  )
5038
- return await this.preparationResolved(
5500
+ return await this.abandonPreparation(
5039
5501
  attempt,
5040
- 'abandoned',
5041
5502
  `Conflicting build ownership at ${attempt.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
5042
5503
  )
5043
5504
  await this.preparationResolved(attempt, 'owned')
@@ -5052,15 +5513,10 @@ export class Dispatcher {
5052
5513
  )
5053
5514
  const ticket = await this.deps.tickets.get(ref.id)
5054
5515
  if (!ticket)
5055
- return await this.preparationResolved(
5056
- attempt,
5057
- 'abandoned',
5058
- 'Ticket no longer exists; ticket unchanged.',
5059
- )
5516
+ return await this.abandonPreparation(attempt, 'Ticket no longer exists; ticket unchanged.')
5060
5517
  if (ticket.state === undefined)
5061
- return await this.preparationResolved(
5518
+ return await this.abandonPreparation(
5062
5519
  attempt,
5063
- 'abandoned',
5064
5520
  'Ticket state is unavailable; ticket unchanged. Inspect the provider record before manually retrying.',
5065
5521
  )
5066
5522
  const state = (value: string) => value.toLowerCase()
@@ -5072,11 +5528,15 @@ export class Dispatcher {
5072
5528
  )
5073
5529
  return
5074
5530
  }
5075
- if (!attempt.claimed || state(ticket.state) !== state(attempt.claimedState))
5076
- return await this.preparationResolved(
5531
+ if (!attempt.claimed)
5532
+ return await this.abandonPreparation(
5077
5533
  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'}`,
5534
+ `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'}`,
5535
+ )
5536
+ if (state(ticket.state) !== state(attempt.claimedState))
5537
+ return await this.abandonPreparation(
5538
+ attempt,
5539
+ `Confirmed claim but ticket externally changed to state ${ticket.state}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
5080
5540
  )
5081
5541
  await this.deps.tickets.transition(ref.id, handback)
5082
5542
  await this.preparationResolved(
@@ -5084,6 +5544,7 @@ export class Dispatcher {
5084
5544
  handback === attempt.readyState ? 'handed-back' : 'bounced',
5085
5545
  )
5086
5546
  } catch (error) {
5547
+ rethrowAuthorityLapse(error)
5087
5548
  const message = error instanceof Error ? error.message : String(error)
5088
5549
  try {
5089
5550
  await this.store.appendRepo(this.deps.repo, {
@@ -5134,15 +5595,22 @@ export class Dispatcher {
5134
5595
  report.ticketDiagnostics = []
5135
5596
  report.dependencyDiagnostics = []
5136
5597
  report.creationDiagnostics = []
5137
- // Blocked and paused builds still occupy a slot: their workspaces and
5138
- // pending work are live, only waiting on a human. Capacity is per repo
5139
- // (§16.1) — another repo's builds never consume this repo's slots.
5140
- const capacityBuilds = await this.capacityBuilds()
5141
- const active = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock()).occupied
5598
+ // Capacity counts builds running work. An unfinished build holds its slot
5599
+ // even while blocked or paused; a finished build parked for its merge
5600
+ // decision holds none. Capacity is per repo (§16.1) — another repo's
5601
+ // builds never consume this repo's slots.
5602
+ const capacityBuilds = await this.capacityBuilds(launched)
5603
+ // A node awaiting verification, or a parked build that must run again,
5604
+ // reserves its slot ahead of new claims until it is admitted; this only
5605
+ // ever lowers the claim budget.
5606
+ const projection = dispatchCapacity(capacityBuilds, config.capacity, this.deps.clock())
5142
5607
  const activeRefs: TicketRef[] = capacityBuilds
5143
5608
  .filter(({ state }) => state.status !== 'done' && state.status !== 'aborted')
5144
5609
  .flatMap(({ record }) => (record.ticket ? [record.ticket] : []))
5145
- let capacity = config.capacity - active
5610
+ let capacity = intakeCapacity(projection, {
5611
+ settled: this.parkedSettled,
5612
+ denied: this.slotWaiters,
5613
+ })
5146
5614
 
5147
5615
  // The ready scan runs even at full capacity: `queued` is the operator's
5148
5616
  // standing queue-depth report and must stay honest exactly when the
@@ -5164,19 +5632,14 @@ export class Dispatcher {
5164
5632
  creation,
5165
5633
  ]),
5166
5634
  )
5167
- const ready = listing.tickets.filter(
5635
+ const eligible = listing.tickets.filter(
5168
5636
  (ticket) =>
5169
5637
  !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
- }),
5638
+ !this.preparing(ticket.ref.source, ticket.ref.id),
5179
5639
  )
5640
+ // Urgent first, each class in source order (stable). Every gate below is
5641
+ // unchanged; a source without the priority capability is all normal.
5642
+ const ready = this.deps.tickets.priority ? urgentFirst(eligible) : eligible
5180
5643
  report.invalidTickets += listing.diagnostics.length
5181
5644
  report.ticketDiagnostics.push(...listing.diagnostics)
5182
5645
  report.queued = ready.length
@@ -5216,15 +5679,20 @@ export class Dispatcher {
5216
5679
  }
5217
5680
  // One dependency-node cache per scan: blockers are commonly shared across
5218
5681
  // the ready set. Never reuse ticket or dependency objects between scans.
5219
- const nodes = new Map<string, DependencyState>(
5682
+ const rejectedState = this.rejectedState()
5683
+ const nodes = new Map<string, DependencyNode>(
5220
5684
  listing.tickets.map((ticket) => [
5221
5685
  ticket.ref.id,
5222
- {
5223
- id: ticket.ref.id,
5224
- exists: true,
5225
- resolved: ticket.resolved,
5226
- blockedBy: [...(ticket.blockedBy ?? [])],
5227
- },
5686
+ markRejected(
5687
+ {
5688
+ id: ticket.ref.id,
5689
+ exists: true,
5690
+ resolved: ticket.resolved,
5691
+ ...(ticket.state !== undefined ? { state: ticket.state } : {}),
5692
+ blockedBy: [...(ticket.blockedBy ?? [])],
5693
+ },
5694
+ rejectedState,
5695
+ ),
5228
5696
  ]),
5229
5697
  )
5230
5698
 
@@ -5257,19 +5725,32 @@ export class Dispatcher {
5257
5725
  (build.digest.kind !== 'node' || build.digest.mergedSha !== undefined)
5258
5726
  )
5259
5727
  })
5260
- const destinationHeads = new Map<
5261
- string,
5262
- { branch: string; destination: string; head: string; identities: string[] }
5263
- >()
5728
+ const destinationHeads = new Map<string, PresenceObservation>()
5264
5729
  const demands: { slug: string; request: EventPayload<'node.restack-requested'> }[] = []
5265
5730
  const verdicts = new Map<string, DependencyVerdict>()
5266
5731
  const failed = new Set<string>()
5267
5732
  const targetBlocked = new Set<string>()
5268
5733
  const preflightTargets = new Map<string, string>()
5734
+ const generation = ++this.foreignScanGeneration
5735
+ for (const [id, entry] of this.foreignBranchCache)
5736
+ if (entry.scan < generation - 1) this.foreignBranchCache.delete(id)
5737
+ const targetScan: TargetScan = {
5738
+ listed: new Set(listing.tickets.map((ticket) => ticket.ref.id)),
5739
+ foreign: new Map(),
5740
+ generation,
5741
+ }
5269
5742
  for (const ticket of ready) {
5270
5743
  if (this.outOfBudget(opts)) return
5271
5744
  if (withheld.has(ticket.ref.id)) continue
5272
- const target = await this.resolveNodeTarget(ticket)
5745
+ let target: Awaited<ReturnType<Dispatcher['resolveNodeTarget']>>
5746
+ try {
5747
+ target = await this.resolveNodeTarget(ticket, targetScan)
5748
+ } catch (error) {
5749
+ if (error instanceof TicketSourceRateLimitError) {
5750
+ await this.sourceFailure(error, 'dependency-check')
5751
+ }
5752
+ throw error
5753
+ }
5273
5754
  if (typeof target === 'string') {
5274
5755
  targetBlocked.add(ticket.ref.id)
5275
5756
  report.dependencyBlocked += 1
@@ -5278,7 +5759,12 @@ export class Dispatcher {
5278
5759
  }
5279
5760
  preflightTargets.set(ticket.ref.id, JSON.stringify(target))
5280
5761
  if (this.outOfBudget(opts)) return
5281
- if ((!hasNodes && ticket.blockersResolved === true) || (ticket.blockedBy ?? []).length === 0)
5762
+ // The listing fact cannot see role names, so a configured rejected role
5763
+ // takes the batched dependency read instead of trusting it.
5764
+ if (
5765
+ (!hasNodes && rejectedState === undefined && ticket.blockersResolved === true) ||
5766
+ (ticket.blockedBy ?? []).length === 0
5767
+ )
5282
5768
  continue
5283
5769
  let verdict: DependencyVerdict
5284
5770
  try {
@@ -5337,6 +5823,7 @@ export class Dispatcher {
5337
5823
  }
5338
5824
  verdicts.set(ticket.ref.id, verdict)
5339
5825
  }
5826
+ await this.recordDestinationPresence(destinationHeads)
5340
5827
  if (this.outOfBudget(opts)) return
5341
5828
  if (failed.size === 0) {
5342
5829
  await this.sourceCondition(undefined, 'dependency-check')
@@ -5376,7 +5863,7 @@ export class Dispatcher {
5376
5863
  if (failed.has(ticket.ref.id) || targetBlocked.has(ticket.ref.id)) continue
5377
5864
  if ((verdicts.get(ticket.ref.id)?.unresolved.length ?? 0) > 0) continue
5378
5865
 
5379
- const target = await this.resolveNodeTarget(ticket)
5866
+ const target = await this.resolveNodeTarget(ticket, targetScan)
5380
5867
  if (typeof target === 'string') {
5381
5868
  report.dependencyBlocked += 1
5382
5869
  report.dependencyDiagnostics.push(`ticket ${ticket.ref.id}: ${target}`)
@@ -5413,6 +5900,8 @@ export class Dispatcher {
5413
5900
  claimed: false,
5414
5901
  }
5415
5902
  await store.ensureRepo(this.deps.repo)
5903
+ // A lapsed run leaves the ticket Ready for whoever holds the repository.
5904
+ if (this.deps.holdsRepoAuthority?.() === false) break
5416
5905
  await store.appendRepo(this.deps.repo, {
5417
5906
  actor: DISPATCHER,
5418
5907
  type: 'ticket-preparation.intended',
@@ -5479,8 +5968,9 @@ export class Dispatcher {
5479
5968
 
5480
5969
  stage = 'naming'
5481
5970
  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}`
5971
+ const prefix = ticket.kind === 'node' ? 'ab-node' : 'ab'
5972
+ const slug = await this.uniqueSlug(baseSlug, prefix)
5973
+ const branch = `${prefix}/${slug}`
5484
5974
  const repoOrigin = await this.resolveRepoOriginOnce()
5485
5975
  createdSeed = {
5486
5976
  ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
@@ -5495,6 +5985,9 @@ export class Dispatcher {
5495
5985
  ? { autoMergeDefaultSeq: autoMergeSeedFact.seq }
5496
5986
  : {}),
5497
5987
  assets,
5988
+ // Frozen from the same claimed ticket sample as the body (SPEC
5989
+ // "Forge issue links"); later ticket edits never reach this build.
5990
+ ...(ticket.issueLinks !== undefined ? { issueLinks: ticket.issueLinks } : {}),
5498
5991
  }
5499
5992
  // `build.created` rides with the record so the pinned assets and the
5500
5993
  // record exist together or not at all.
@@ -5521,6 +6014,9 @@ export class Dispatcher {
5521
6014
  established = true
5522
6015
  await this.preparationResolved(attempt, 'owned')
5523
6016
  } catch (error) {
6017
+ // A lapse is not a preparation failure: the successor recovers the
6018
+ // intended attempt through `recoverTicketPreparations`.
6019
+ rethrowAuthorityLapse(error)
5524
6020
  // Settlement and completion errors after successful creation cannot
5525
6021
  // release the claim. A later tick settles the retained creation identity.
5526
6022
  if (established) throw error
@@ -5576,6 +6072,7 @@ export class Dispatcher {
5576
6072
  */
5577
6073
  private async resolveNodeTarget(
5578
6074
  ticket: Ticket,
6075
+ scan: TargetScan,
5579
6076
  ): Promise<
5580
6077
  | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
5581
6078
  | string
@@ -5589,7 +6086,8 @@ export class Dispatcher {
5589
6086
  return `integration requires forge ${forge.name} capabilities createNodeBranch, compareBranches and remoteBranchSha; upgrade the plugin`
5590
6087
  if (ticket.target === undefined) return undefined
5591
6088
  const migrations = this.store.repositoryFacts().ticketMigrations
5592
- const entries = (await this.repoBuildDigests())
6089
+ const all = await this.repoBuildDigests()
6090
+ const entries = all
5593
6091
  .filter(
5594
6092
  ({ record }) =>
5595
6093
  record.ticket &&
@@ -5615,7 +6113,7 @@ export class Dispatcher {
5615
6113
  const latest = entries[0]
5616
6114
  if (latest && entries[1]?.record.createdAt === latest.record.createdAt)
5617
6115
  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`
6116
+ if (!latest) return this.foreignTargetDiagnostic(ticket.target, ticket.ref.source, all, scan)
5619
6117
  const { record, digest } = latest
5620
6118
  if (digest.kind !== 'node') return `target ${ticket.target} is not a node`
5621
6119
  if (digest.terminal || digest.prClosed || digest.merged)
@@ -5688,23 +6186,66 @@ export class Dispatcher {
5688
6186
  private async kernelRepository(root: string): Promise<string> {
5689
6187
  const checkout = this.deps.checkout ?? this.deps.repo
5690
6188
  if (!this.deps.repoOrigin) return checkout
6189
+ if (this.kernelGitUnavailable) throw this.kernelGitUnavailable
5691
6190
  // Origin-mode CLI wiring supplies a scratch checkout path too. Only an
5692
6191
  // actual Git repository can provide the kernel's local object database.
5693
6192
  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
6193
+ const probe = await this.kernelGit(() =>
6194
+ this.deps.exec(['git', 'rev-parse', '--git-dir'], { cwd: checkout }),
6195
+ )
6196
+ if (probe.exitCode === 0) {
6197
+ await this.kernelGitRecovered()
6198
+ return checkout
6199
+ }
5696
6200
  }
5697
6201
  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
- },
6202
+ const clone = await this.kernelGit(() =>
6203
+ (this.deps.forge.kernelExec ?? this.deps.exec)(
6204
+ ['git', 'clone', '--bare', this.deps.repoOrigin!, path],
6205
+ { cwd: root },
6206
+ ),
5703
6207
  )
5704
6208
  if (clone.exitCode !== 0) throw new Error(clone.stderr)
6209
+ await this.kernelGitRecovered()
5705
6210
  return path
5706
6211
  }
5707
6212
 
6213
+ /** Run one kernel Git command, turning "Git cannot execute" into the
6214
+ * repository-level condition: one durable `dispatcher.kernel-git-unavailable`
6215
+ * per outage (read from the already-advanced repository projection, so a
6216
+ * fresh process does not repeat it) and a deferral for the node work. */
6217
+ private async kernelGit(run: () => Promise<ExecResult>): Promise<ExecResult> {
6218
+ let detail: string | undefined
6219
+ let result: ExecResult | undefined
6220
+ try {
6221
+ result = await run()
6222
+ detail = kernelGitUnavailableDetail({ result })
6223
+ } catch (error) {
6224
+ detail = kernelGitUnavailableDetail({ error })
6225
+ if (detail === undefined) throw error
6226
+ }
6227
+ if (detail === undefined) return result!
6228
+ this.kernelGitUnavailable = new KernelGitUnavailable('git', detail)
6229
+ if (this.store.repositoryFacts().kernelGit === undefined) {
6230
+ await this.store.ensureRepo(this.deps.repo)
6231
+ await this.store.appendRepo(this.deps.repo, {
6232
+ actor: DISPATCHER,
6233
+ type: 'dispatcher.kernel-git-unavailable',
6234
+ payload: { executable: 'git', detail },
6235
+ })
6236
+ }
6237
+ throw this.kernelGitUnavailable
6238
+ }
6239
+
6240
+ private async kernelGitRecovered(): Promise<void> {
6241
+ if (this.store.repositoryFacts().kernelGit === undefined) return
6242
+ await this.store.appendRepo(this.deps.repo, {
6243
+ actor: DISPATCHER,
6244
+ type: 'dispatcher.kernel-git-recovered',
6245
+ payload: { executable: 'git' },
6246
+ })
6247
+ }
6248
+
5708
6249
  private async withKernelRepository<T>(run: (path: string) => Promise<T>): Promise<T> {
5709
6250
  const root = await mkdtemp(join(tmpdir(), 'autobuild-node-transport-'))
5710
6251
  try {
@@ -5766,7 +6307,9 @@ export class Dispatcher {
5766
6307
  forge.remoteBranchSha(state.baseBranch),
5767
6308
  forge.remoteBranchSha(record.branch),
5768
6309
  ])
5769
- this.availabilityEntries ??= this.repoBuildDigests()
6310
+ // Landing evidence must match runNodeTransaction, which reads every
6311
+ // repository build; reading a deferred digest decides nothing for it.
6312
+ this.availabilityEntries ??= this.repoBuildDigests(true)
5770
6313
  const entries = await this.availabilityEntries
5771
6314
  this.availabilityLandings ??= confirmedLandings(entries)
5772
6315
  this.availabilityLandingKey ??= restackLandingKey(this.availabilityLandings)
@@ -5895,6 +6438,8 @@ export class Dispatcher {
5895
6438
  beforeReplay,
5896
6439
  canWrite: async () => {
5897
6440
  if (await deferMixedVersion(this.store, record.slug)) return false
6441
+ // A lapse is not lost writer authority: it must escape unrecorded.
6442
+ if (this.deps.holdsRepoAuthority?.() === false) throw new RepositoryAuthorityLapsed()
5898
6443
  if (this.outOfBudget(opts)) return false
5899
6444
  if (state.pr && (await forge.getPrState(checkout, state.pr.number)).state !== 'open')
5900
6445
  return false
@@ -5904,7 +6449,7 @@ export class Dispatcher {
5904
6449
  current.status !== 'done' &&
5905
6450
  current.status !== 'aborted' &&
5906
6451
  current.status !== 'paused' &&
5907
- (current.status !== 'blocked' || integrationFailed(current)) &&
6452
+ (!janitorBlocked(current) || integrationFailed(current)) &&
5908
6453
  current.prState !== 'merged' &&
5909
6454
  current.prState !== 'closed' &&
5910
6455
  current.pendingCommands.length === 0 &&
@@ -5978,6 +6523,9 @@ export class Dispatcher {
5978
6523
  remote: false,
5979
6524
  branch: handle.branch,
5980
6525
  base: handle.base,
6526
+ ...(handle.restorationSkipped?.length
6527
+ ? { restorationSkipped: handle.restorationSkipped }
6528
+ : {}),
5981
6529
  },
5982
6530
  })
5983
6531
  }
@@ -5985,6 +6533,7 @@ export class Dispatcher {
5985
6533
  }
5986
6534
  }
5987
6535
  } catch (error) {
6536
+ rethrowAuthorityLapse(error)
5988
6537
  if (await this.holdForMissingAccounts(error)) return
5989
6538
  const message =
5990
6539
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
@@ -5997,7 +6546,7 @@ export class Dispatcher {
5997
6546
  ) {
5998
6547
  await this.store.refreshBuild(record.slug)
5999
6548
  const current = (await this.store.buildFacts(record.slug)).state
6000
- if (!current.openEscalations.length)
6549
+ if (!escalationsBeyondJanitor(current).length)
6001
6550
  await this.store.append(record.slug, {
6002
6551
  actor: KERNEL,
6003
6552
  type: 'escalation.raised',
@@ -6026,20 +6575,8 @@ export class Dispatcher {
6026
6575
  launched: Set<string>,
6027
6576
  sampling: { refreshOnly?: boolean } = {},
6028
6577
  ): 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
6578
+ // The janitor's own escalation never skips the preparation that would recover it.
6579
+ if (!integrationAdmissible(withoutJanitorEscalation(state))) return
6043
6580
  const forge = this.kernelForge()
6044
6581
  if (!record.branch || !state.baseBranch || !forge.compareBranches) return
6045
6582
  const comparison = await forge.compareBranches(state.baseBranch!, record.branch!)
@@ -6079,7 +6616,7 @@ export class Dispatcher {
6079
6616
  state.nodeRestack?.active ||
6080
6617
  state.integration?.intent ||
6081
6618
  state.nodeRestack?.contributionBase !== comparison.parentSha ||
6082
- state.openEscalations.length ||
6619
+ escalationsBeyondJanitor(state).length ||
6083
6620
  state.status === 'paused' ||
6084
6621
  state.status === 'done' ||
6085
6622
  state.status === 'aborted' ||
@@ -6224,6 +6761,9 @@ export class Dispatcher {
6224
6761
  remote: false,
6225
6762
  branch: handle.branch,
6226
6763
  base: handle.base,
6764
+ ...(handle.restorationSkipped?.length
6765
+ ? { restorationSkipped: handle.restorationSkipped }
6766
+ : {}),
6227
6767
  },
6228
6768
  })
6229
6769
  }
@@ -6261,6 +6801,10 @@ export class Dispatcher {
6261
6801
  )
6262
6802
  return
6263
6803
  let pr: Awaited<ReturnType<typeof forge.openPr>>
6804
+ // A node's PR carries its set (its own links and its landed children's
6805
+ // union) from the start, refs-only into a parent; checkPr keeps it
6806
+ // current as later children land.
6807
+ const issueLinks = nodeIssueLinksForForge(state, forge)
6264
6808
  try {
6265
6809
  pr = await forge.openPr({
6266
6810
  workspacePath: this.deps.checkout ?? this.deps.repo,
@@ -6268,6 +6812,7 @@ export class Dispatcher {
6268
6812
  base: state.baseBranch,
6269
6813
  title: `Integration: ${record.ticket?.id ?? record.slug}`,
6270
6814
  body: `Integration build ${record.slug}. Target: ${state.target?.ticket.id ?? state.baseBranch}. Human merge required.`,
6815
+ ...(issueLinks ? { issueLinks } : {}),
6271
6816
  })
6272
6817
  } catch (error) {
6273
6818
  if (
@@ -6395,95 +6940,124 @@ export class Dispatcher {
6395
6940
  }
6396
6941
  }
6397
6942
 
6943
+ /** Answer `query` for one destination with bounded, query-scoped evidence.
6944
+ * A durable probe at the sampled head that covers the questions is reused
6945
+ * without Git; otherwise one fresh walk (or this process's in-memory witness
6946
+ * at the same head) is compacted. Full witnesses are never persisted. */
6398
6947
  private async sampleDestinationPresence(
6399
6948
  branch: string,
6400
6949
  destination: string,
6401
6950
  target: { target: { build: string } } | undefined,
6402
6951
  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()
6952
+ observations: Map<string, PresenceObservation>,
6953
+ query: readonly ChangeIdentity[],
6954
+ ): Promise<PresenceObservation> {
6955
+ const aliases = destinationAliases(inputs, target?.target.build)
6956
+ const entry = observations.get(destination)
6957
+ const asked = normalizeIdentities([...(entry?.asked ?? []), ...query])
6958
+ if (entry && answers(entry.probe, query, inputs.landings, aliases)) {
6959
+ entry.asked = asked
6960
+ return entry
6961
+ }
6962
+ const forge = this.kernelForge()
6963
+ let head = entry?.head
6964
+ if (head === undefined) {
6411
6965
  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)
6966
+ head = await forge.remoteBranchSha(branch)
6967
+ }
6968
+ const cached = this.store.repositoryFacts().presence[destination]
6969
+ let probe: PresenceProbe
6970
+ if (
6971
+ cached?.head === head &&
6972
+ cached.branch === branch &&
6973
+ cached.probe &&
6974
+ answers(cached.probe as PresenceProbe, asked, inputs.landings, aliases)
6975
+ )
6976
+ probe = cached.probe as PresenceProbe
6977
+ else {
6978
+ const memo = this.presenceWitnesses.get(destination)
6979
+ const witness =
6980
+ memo?.branch === branch && memo.head === head
6981
+ ? memo.witness
6982
+ : await this.sampleDestinationWitness(branch, head, target)
6983
+ this.presenceWitnesses.set(destination, { branch, head, witness })
6984
+ probe = compactProbe(witness, asked, inputs.landings, aliases)
6985
+ }
6986
+ const identities = projectProbe(probe, inputs.landings, aliases)
6987
+ const observed = { branch, destination, head, identities, probe, asked }
6988
+ observations.set(destination, observed)
6989
+ return observed
6990
+ }
6991
+
6992
+ /** Persist each destination's final in-tick probe once, after every ticket
6993
+ * has added its questions, and only when it differs from the durable one. */
6994
+ private async recordDestinationPresence(observations: Map<string, PresenceObservation>) {
6995
+ for (const { branch, destination, head, identities, probe } of observations.values()) {
6996
+ const evidence = probeEvidence(probe, identities)
6414
6997
  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
6998
+ if (cached?.head === head && cached.branch === branch && cached.evidence === evidence)
6999
+ continue
7000
+ await this.store.ensureRepo(this.deps.repo)
7001
+ await this.store.appendRepo(this.deps.repo, {
7002
+ actor: DISPATCHER,
7003
+ type: 'change-presence.observed',
7004
+ payload: { branch, destination, head, evidence, identities, probe },
7005
+ })
7006
+ }
7007
+ }
7008
+
7009
+ /** One snapshot of the destination at `head` and its full in-memory witness. */
7010
+ private async sampleDestinationWitness(
7011
+ branch: string,
7012
+ head: string,
7013
+ target: { target: { build: string } } | undefined,
7014
+ ): Promise<PresenceWitness> {
7015
+ const forge = this.kernelForge()
7016
+ if (!forge.snapshotBase && !forge.kernelExec && !forge.rewrite)
7017
+ throw new Error('forge cannot snapshot destination presence')
7018
+ return this.withKernelRepository(async (path) => {
7019
+ const destinationRef = `refs/autobuild/reconcile/${target?.target.build ?? 'presence'}/presence`
7020
+ let sampled: string
7021
+ if (forge.snapshotBase)
7022
+ sampled = await forge.snapshotBase({
7023
+ workspacePath: path,
7024
+ base: branch,
7025
+ destinationRef,
6482
7026
  })
7027
+ else if (target && forge.rewrite)
7028
+ sampled = await forge.rewrite.snapshot({
7029
+ workspacePath: path,
7030
+ branch,
7031
+ destinationRef,
7032
+ })
7033
+ else {
7034
+ const exec = forge.kernelExec ?? this.deps.exec
7035
+ const fetch = await exec(
7036
+ [
7037
+ 'git',
7038
+ 'fetch',
7039
+ '--no-tags',
7040
+ '--no-write-fetch-head',
7041
+ '--refmap=',
7042
+ 'origin',
7043
+ `+refs/heads/${branch}:${destinationRef}`,
7044
+ ],
7045
+ { cwd: path },
7046
+ )
7047
+ if (fetch.exitCode !== 0) throw new Error(fetch.stderr)
7048
+ const resolved = await exec(
7049
+ ['git', 'rev-parse', '--verify', `${destinationRef}^{commit}`],
7050
+ { cwd: path },
7051
+ )
7052
+ if (resolved.exitCode !== 0) throw new Error(resolved.stderr)
7053
+ sampled = resolved.stdout.trim()
6483
7054
  }
6484
- observations.set(destination, observed)
6485
- }
6486
- return observed!
7055
+ if (sampled !== head) throw new Error('destination moved while sampling presence')
7056
+ return presenceWitness(
7057
+ { exec: forge.kernelExec ?? this.deps.exec, workspacePath: path },
7058
+ head,
7059
+ )
7060
+ })
6487
7061
  }
6488
7062
 
6489
7063
  private async presenceVerdict(
@@ -6491,13 +7065,10 @@ export class Dispatcher {
6491
7065
  target:
6492
7066
  | { target: NonNullable<EventPayload<'build.created'>['target']>; branch: string }
6493
7067
  | undefined,
6494
- nodes: Map<string, DependencyState>,
7068
+ nodes: Map<string, DependencyNode>,
6495
7069
  inputs: PresenceInputs,
6496
7070
  demands: { slug: string; request: EventPayload<'node.restack-requested'> }[],
6497
- observations: Map<
6498
- string,
6499
- { branch: string; destination: string; head: string; identities: string[] }
6500
- >,
7071
+ observations: Map<string, PresenceObservation>,
6501
7072
  ): Promise<DependencyVerdict> {
6502
7073
  const branch = target?.branch ?? this.deps.config.baseBranch
6503
7074
  const destination = target?.target.build ?? `root:${branch}`
@@ -6515,7 +7086,13 @@ export class Dispatcher {
6515
7086
  this.deps.tickets.name,
6516
7087
  ),
6517
7088
  )
6518
- if (id === ticket.ref.id || !nodes.get(id)?.exists || build === undefined) {
7089
+ // A rejected blocker's diagnostic wins over any build it once had.
7090
+ if (
7091
+ id === ticket.ref.id ||
7092
+ !nodes.get(id)?.exists ||
7093
+ nodes.get(id)?.rejected ||
7094
+ build === undefined
7095
+ ) {
6519
7096
  fallback.push(id)
6520
7097
  continue
6521
7098
  }
@@ -6559,6 +7136,7 @@ export class Dispatcher {
6559
7136
  target,
6560
7137
  inputs,
6561
7138
  observations,
7139
+ normalizeIdentities([...required.values()].flat()),
6562
7140
  )
6563
7141
  const missing = [
6564
7142
  ...new Set(
@@ -6586,6 +7164,7 @@ export class Dispatcher {
6586
7164
  slug ? { target: { build: slug } } : undefined,
6587
7165
  inputs,
6588
7166
  observations,
7167
+ missing,
6589
7168
  )
6590
7169
  path.push({ ...(slug ? { slug } : {}), ...parent })
6591
7170
  if (missing.every((id) => path.some((entry) => entry.identities.includes(id)))) break
@@ -6631,7 +7210,7 @@ export class Dispatcher {
6631
7210
 
6632
7211
  private async loadDependencyGraph(
6633
7212
  ticket: Ticket,
6634
- nodes: Map<string, DependencyState>,
7213
+ nodes: Map<string, DependencyNode>,
6635
7214
  opts: TickOpts = {},
6636
7215
  builtTickets?: ReadonlySet<string>,
6637
7216
  ): Promise<boolean> {
@@ -6642,7 +7221,8 @@ export class Dispatcher {
6642
7221
  const uncached = frontier.filter((id) => !nodes.has(id))
6643
7222
  if (uncached.length > 0) {
6644
7223
  const states = await this.deps.tickets.dependencyStates(uncached)
6645
- for (const state of states) nodes.set(state.id, state)
7224
+ const rejectedState = this.rejectedState()
7225
+ for (const state of states) nodes.set(state.id, markRejected(state, rejectedState))
6646
7226
  }
6647
7227
  const next: string[] = []
6648
7228
  for (const id of frontier) {
@@ -6706,12 +7286,106 @@ export class Dispatcher {
6706
7286
  }
6707
7287
  }
6708
7288
 
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}`
7289
+ /** Whether this store has an unresolved preparation attempt for the ticket. */
7290
+ private preparing(source: string, id: string): boolean {
7291
+ const facts = this.store.repositoryFacts()
7292
+ return Object.values(facts.preparation).some((attempt) => {
7293
+ const ref = resolveTicketRef(
7294
+ facts.ticketMigrations,
7295
+ attempt.ticket,
7296
+ this.deps.tickets.name,
7297
+ attempt.slug ?? attempt.attempt,
7298
+ )
7299
+ return ref.source === source && ref.id === id
7300
+ })
7301
+ }
7302
+
7303
+ /**
7304
+ * A target node with no build in this store is either not yet claimed or
7305
+ * being built by another store (AUT-1106). One ticket read per distinct
7306
+ * target per admission scan; the forge branch lookup runs only when the
7307
+ * target's revision or foreign dispatch-comment slugs change. Never fails
7308
+ * admission: read failures fall back to the not-yet-claimed text.
7309
+ */
7310
+ private foreignTargetDiagnostic(
7311
+ target: string,
7312
+ source: string,
7313
+ all: readonly { record: BuildRecord }[],
7314
+ scan: TargetScan,
7315
+ ): Promise<string> {
7316
+ const pending = `target node ${target} is not yet claimed`
7317
+ if (scan.listed.has(target) || this.preparing(source, target)) return Promise.resolve(pending)
7318
+ const memo = scan.foreign.get(target)
7319
+ if (memo !== undefined) return memo
7320
+ const share = 'dispatchers on one repository must share one store (ab connect)'
7321
+ const verdict = (async () => {
7322
+ let ticket: Ticket | null
7323
+ try {
7324
+ ticket = await this.deps.tickets.get(target)
7325
+ } catch (error) {
7326
+ if (error instanceof TicketSourceRateLimitError) throw error
7327
+ return pending
7328
+ }
7329
+ if (ticket === null) return pending
7330
+ const doing = ticketLifecycle(this.deps.config.tickets).doing
7331
+ if (!ticket.resolved && ticket.state?.toLowerCase() === doing.toLowerCase())
7332
+ 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}`
7333
+ const forge = this.deps.forge
7334
+ const exists = forge.remoteBranchExists
7335
+ if (ticket.comments === undefined || exists === undefined) return pending
7336
+ // Only a node branch this store owns is not evidence of another store:
7337
+ // separate stores may reuse a slug for unrelated tickets or prefixes.
7338
+ const owned = new Set(all.flatMap(({ record }) => record.branch ?? []))
7339
+ const slugs = [
7340
+ ...new Set(
7341
+ [...ticket.comments]
7342
+ .reverse()
7343
+ .flatMap((comment) => DISPATCH_COMMENT.exec(comment.body)?.[1] ?? [])
7344
+ .filter((slug) => !owned.has(`ab-node/${slug}`)),
7345
+ ),
7346
+ ]
7347
+ if (slugs.length === 0) return pending
7348
+ const fingerprint = `${ticket.revision}\n${[...slugs].sort().join(',')}`
7349
+ const cached = this.foreignBranchCache.get(target)
7350
+ let branch: string | null
7351
+ if (cached?.fingerprint === fingerprint) {
7352
+ cached.scan = scan.generation
7353
+ branch = cached.branch
7354
+ } else {
7355
+ branch = null
7356
+ try {
7357
+ for (const slug of slugs) {
7358
+ if (await exists.call(forge, `ab-node/${slug}`)) {
7359
+ branch = `ab-node/${slug}`
7360
+ break
7361
+ }
7362
+ }
7363
+ } catch {
7364
+ return pending
7365
+ }
7366
+ this.foreignBranchCache.set(target, { fingerprint, branch, scan: scan.generation })
7367
+ }
7368
+ return branch === null
7369
+ ? pending
7370
+ : `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}`
7371
+ })()
7372
+ scan.foreign.set(target, verdict)
7373
+ return verdict
7374
+ }
7375
+
7376
+ /** Valid bounded base, deduped with -2/-3/… against this store's builds and,
7377
+ * when the forge can answer, against build branches already on the remote
7378
+ * (another store's builds, AUT-1106). Claim-time only; a forge failure fails
7379
+ * the naming stage and the claim is handed back. */
7380
+ private async uniqueSlug(base: string, prefix: 'ab' | 'ab-node'): Promise<string> {
7381
+ const forge = this.deps.forge
7382
+ const exists = forge.remoteBranchExists
7383
+ for (let n = 1; n <= MAX_SLUG_CANDIDATES; n += 1) {
7384
+ const slug = n === 1 ? base : `${base}-${n}`
7385
+ if ((await this.store.getBuild(slug)) !== null) continue
7386
+ if (exists !== undefined && (await exists.call(forge, `${prefix}/${slug}`))) continue
7387
+ return slug
6714
7388
  }
6715
- return slug
7389
+ throw new Error(`no free slug for ${base} after ${MAX_SLUG_CANDIDATES} candidates`)
6716
7390
  }
6717
7391
  }