@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
@@ -0,0 +1,95 @@
1
+ import { KERNEL } from '../events/envelope'
2
+ import type { ForgeRejection } from '../ports/forge-failure'
3
+ import { ForgeRequestDeferred } from '../ports/forge-request-context'
4
+ import { readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
5
+ import type { BuildStore } from '../store/types'
6
+
7
+ /**
8
+ * A forge that refuses a dispatcher-side finalize PR create for a reason a
9
+ * retry cannot fix (a 4xx validation answer such as GitHub's "No commits
10
+ * between") is a question for the operator, not a provider failure. One
11
+ * escalation is raised per rejection; while it is open the request is parked
12
+ * without calling the forge, and each answer authorizes exactly one more
13
+ * attempt. Escalation ids are keyed by the publication request and the seq
14
+ * of the answer that authorized the attempt (0 for the first), so a crash
15
+ * between the rejection and its fact, or repeated ticks, never raise twice.
16
+ */
17
+ type FinalizeRequest = {
18
+ seq: number
19
+ payload: { branch: string; sha: string }
20
+ }
21
+
22
+ export function finalizePrEscalationPrefix(requestSeq: number) {
23
+ return `publication:finalize:${requestSeq}:`
24
+ }
25
+
26
+ export function finalizePrEscalationId(requestSeq: number, anchor: number) {
27
+ return `${finalizePrEscalationPrefix(requestSeq)}${anchor}`
28
+ }
29
+
30
+ /** Returns the anchor for the next PR-create attempt, or throws: deferred
31
+ * while a rejection awaits its answer, plainly once the build is ending. */
32
+ export function finalizePrRejectionGate(facts: CurrentBuildFacts, request: FinalizeRequest) {
33
+ const prefix = finalizePrEscalationPrefix(request.seq)
34
+ const open = facts.state.openEscalations.find((e) => e.id.startsWith(prefix))
35
+ const answered = facts.state.answeredEscalations.filter((e) => e.id.startsWith(prefix))
36
+ const latest = answered.at(-1)
37
+ const ending =
38
+ facts.state.status === 'aborted' ||
39
+ facts.state.status === 'done' ||
40
+ facts.state.discardRequest !== undefined ||
41
+ facts.state.pendingCommands.some((command) => command.command === 'abort') ||
42
+ latest?.resolution === 'abort'
43
+ if ((open !== undefined || latest !== undefined) && ending)
44
+ throw new Error(
45
+ `finalize PR create was rejected by the forge and the build is ending; not retrying (${(open ?? latest)!.id})`,
46
+ )
47
+ if (open !== undefined)
48
+ throw new ForgeRequestDeferred(
49
+ `finalize PR create rejected by the forge; awaiting an answer to ${open.id}`,
50
+ )
51
+ return latest?.answeredSeq ?? 0
52
+ }
53
+
54
+ export interface FinalizePrRejectionDeps {
55
+ store: BuildStore
56
+ }
57
+
58
+ /** Record the rejection once, then park the request. Always throws. */
59
+ export async function raiseFinalizePrRejection(
60
+ deps: FinalizePrRejectionDeps,
61
+ slug: string,
62
+ request: FinalizeRequest,
63
+ baseBranch: string,
64
+ anchor: number,
65
+ rejection: ForgeRejection,
66
+ ): Promise<never> {
67
+ const id = finalizePrEscalationId(request.seq, anchor)
68
+ for (;;) {
69
+ const facts = (await readBuildFacts(deps.store, slug)).value
70
+ if (
71
+ facts.state.openEscalations.some((e) => e.id === id) ||
72
+ facts.state.answeredEscalations.some((e) => e.id === id)
73
+ )
74
+ break
75
+ const raised = await deps.store.appendIfCurrent(slug, facts.state.lastSeq, {
76
+ actor: KERNEL,
77
+ type: 'escalation.raised',
78
+ payload: {
79
+ id,
80
+ phase: 'finalize',
81
+ round: 1,
82
+ source: 'policy',
83
+ policyCause: 'non-retryable-phase-failure',
84
+ question:
85
+ `finalize could not open the pull request: ${rejection.forge} rejected the PR create ` +
86
+ `with HTTP ${rejection.status}: ${rejection.forgeMessage}. Branch ${request.payload.branch} ` +
87
+ `at ${request.payload.sha} → ${baseBranch}. No sandbox or provider recovery is needed. ` +
88
+ `Answer retry to re-attempt the PR create once (for example after pushing commits or ` +
89
+ `fixing the base), give guidance, or abort.`,
90
+ },
91
+ })
92
+ if (raised) break
93
+ }
94
+ throw new ForgeRequestDeferred(`finalize PR create rejected; escalated ${id}`)
95
+ }
@@ -48,6 +48,15 @@ function randomWrite(rand: () => number): EventWrite {
48
48
  nextAttemptAt: '2026-01-01T00:01:00.000Z',
49
49
  }),
50
50
  () => w('build.janitor-failing', { message: 'forge unavailable' }),
51
+ () =>
52
+ w('build.janitor-escalated', {
53
+ id: 'janitor:2026-01-01T00:00:00.000Z',
54
+ operation: 'PR check',
55
+ message: 'forge unavailable',
56
+ attempt,
57
+ firstFailureAt: '2026-01-01T00:00:00.000Z',
58
+ question: 'Janitor PR check has failed.',
59
+ }),
51
60
  () => w('build.janitor-recovered', {}),
52
61
  () =>
53
62
  w('landing.application-failed', {
@@ -240,6 +240,11 @@ export function randomStatusJournal(seed: number, length: number): RepositoryEve
240
240
  },
241
241
  }),
242
242
  () => ({ type: 'dispatcher.forge-recovered', payload: { forge: 'github' } }),
243
+ () => ({
244
+ type: 'dispatcher.kernel-git-unavailable',
245
+ payload: { executable: 'git', detail: 'Executable not found in $PATH: "git"' },
246
+ }),
247
+ () => ({ type: 'dispatcher.kernel-git-recovered', payload: { executable: 'git' } }),
243
248
  () => ({
244
249
  type: 'dispatcher.run-started',
245
250
  payload: {
@@ -254,6 +259,8 @@ export function randomStatusJournal(seed: number, length: number): RepositoryEve
254
259
  payload: {
255
260
  run,
256
261
  queued: i,
262
+ // Deterministic (no rand draw) so the other templates' sequence holds.
263
+ ...(i % 2 === 0 ? { triage: i } : {}),
257
264
  counters: { ...counters, creationWithheld: 1 },
258
265
  janitorDiagnostics: ['j'],
259
266
  ticketDiagnostics: [],
@@ -278,7 +285,14 @@ export function randomStatusJournal(seed: number, length: number): RepositoryEve
278
285
  type: 'dispatcher.operator-reported',
279
286
  payload: { run, level: pick(rand, ['info', 'warning']), message: 'm' },
280
287
  }),
281
- () => ({ type: 'dispatcher.upgrade-available', payload: { run, version: '1.0.0' } }),
288
+ // Shares a slot deterministically (no rand draw) so the sequence holds.
289
+ () =>
290
+ i % 5 !== 0
291
+ ? { type: 'dispatcher.upgrade-available', payload: { run, version: '1.0.0' } }
292
+ : {
293
+ type: 'dispatcher.summary-handoff',
294
+ payload: { run, slug: 'b', status: 'verifying' },
295
+ },
282
296
  () => ({
283
297
  type: 'dispatcher.run-stopped',
284
298
  payload: { run, outcome: pick(rand, ['normal', 'abnormal']) },
@@ -44,6 +44,8 @@ export interface HarvestProposalReservation {
44
44
  proposalKey: string
45
45
  id: string
46
46
  seq: number
47
+ /** The reservation fact's time: the earliest the id could first be used. */
48
+ reservedAt: string
47
49
  }
48
50
 
49
51
  export interface HarvestRecoveryRequest {
@@ -220,7 +222,7 @@ export interface HarvestAcc {
220
222
  }
221
223
 
222
224
  /** Bump when `HarvestAcc`'s shape or fold semantics change. */
223
- export const HARVEST_REDUCER_VERSION = 3
225
+ export const HARVEST_REDUCER_VERSION = 4
224
226
 
225
227
  function foldHarvest(acc: HarvestAcc, events: readonly RepositoryEvent[]): void {
226
228
  const order = acc.runs
@@ -590,6 +592,7 @@ function foldHarvest(acc: HarvestAcc, events: readonly RepositoryEvent[]): void
590
592
  proposalKey: event.payload.proposalKey,
591
593
  id: event.payload.id,
592
594
  seq: event.seq,
595
+ reservedAt: event.ts,
593
596
  })
594
597
  break
595
598
  }
@@ -167,6 +167,7 @@ export function randomBuildItem(rand: Rand): readonly [string, Record<string, un
167
167
  () => ['observation.recorded', { id: 'o', kind: 'followup', summary: 's', refs: [marker] }],
168
168
  () => ['observation.recorded', { id: 'o2', kind: 'refactor', summary: 's' }],
169
169
  () => ['session.started', { session: 's', role: 'r', runner: 'c', phase: 'plan' }],
170
+ () => ['pipeline.settled', { cycle: 1 + Math.floor(rand() * 40) }],
170
171
  ]
171
172
  return pick(rand, templates)()
172
173
  }
@@ -2,29 +2,80 @@ import { readTicketMigrations, resolveTicketRef, type TicketMigrations } from '.
2
2
  import type { BuildState } from './reducer'
3
3
  import type { TicketSource, TicketListing } from '../ports/types'
4
4
  import type { BuildStore, BuildRecord } from '../store/types'
5
- import { readBuildFacts } from '../store/reduced-reads'
5
+ import { readBuildDigests, readBuildFacts } from '../store/reduced-reads'
6
+ import { digestNodeTargets } from '../store/digest'
6
7
  import { DISPATCHER } from '../events/envelope'
7
8
  import type { EventPayload } from '../events/payloads'
9
+ import { contributedIssueLinks } from './node-issue-links'
10
+ import { holdsState } from '../ports/tickets/lifecycle'
8
11
 
9
- /** One exhaustive source sample shared by every node in a dispatcher pass.
10
- * Scheduling may be cached; publication always requests a sample from this pass. */
12
+ /** The pass's source sample: either one exhaustive listing shared by every
13
+ * node, or, when the source lists one node's targeting tickets, a per-node
14
+ * targeted listing memoized for the pass. Scheduling may be cached;
15
+ * publication always requests a sample from this pass. */
11
16
  export interface IntegrationObservationInputs {
12
17
  migrations?: TicketMigrations
13
- listing: TicketListing
14
- builds: { record: BuildRecord; state: BuildState }[]
18
+ listing?: TicketListing
19
+ targeting?: (nodeId: string) => Promise<TicketListing>
20
+ /** Every repository build with the node slugs its digest names, a superset
21
+ * of every node it targets or moves between. */
22
+ builds: { record: BuildRecord; nodeTargets: readonly string[] }[]
23
+ /** Current facts for one build; memoized for this sample. */
24
+ state: (slug: string) => Promise<BuildState>
25
+ }
26
+
27
+ function canEnumerate(tickets: TicketSource): boolean {
28
+ return !!tickets.integrationTree && (!!tickets.listAll || !!tickets.listTargeting)
29
+ }
30
+
31
+ /** One targeted listing per node for the life of an inputs object; a failed
32
+ * read is forgotten so a later pass retries it. */
33
+ function memoizedTargeting(
34
+ tickets: TicketSource & { listTargeting: NonNullable<TicketSource['listTargeting']> },
35
+ ): (nodeId: string) => Promise<TicketListing> {
36
+ // Captured once: the targeting decision is fixed for the pass, so a source
37
+ // that withdraws it later fails closed rather than falling back to listAll.
38
+ const list = tickets.listTargeting.bind(tickets)
39
+ const listings = new Map<string, Promise<TicketListing>>()
40
+ return (nodeId) => {
41
+ let listing = listings.get(nodeId)
42
+ if (listing === undefined) {
43
+ listing = list(nodeId)
44
+ listings.set(nodeId, listing)
45
+ listing.catch(() => listings.delete(nodeId))
46
+ }
47
+ return listing
48
+ }
15
49
  }
16
50
  export async function integrationObservationInputs(
17
51
  store: BuildStore,
18
52
  tickets: TicketSource,
19
53
  repo: string,
20
54
  ): Promise<IntegrationObservationInputs> {
21
- if (!tickets.integrationTree || !tickets.listAll)
55
+ if (!canEnumerate(tickets))
22
56
  throw new Error('ticket source cannot establish exhaustive integration completeness')
23
- const listing = await tickets.listAll()
24
- const builds = []
25
- for (const record of await store.listBuildsForRepo(repo))
26
- builds.push({ record, state: (await readBuildFacts(store, record.slug)).value.state })
27
- return { listing, builds, migrations: await readTicketMigrations(store, repo) }
57
+ const sample: Pick<IntegrationObservationInputs, 'listing' | 'targeting'> = tickets.listTargeting
58
+ ? { targeting: memoizedTargeting(tickets as Parameters<typeof memoizedTargeting>[0]) }
59
+ : { listing: await tickets.listAll!() }
60
+ // Records before digests, so a concurrent create cannot break completeness.
61
+ const records = await store.listBuildsForRepo(repo)
62
+ const digests = await readBuildDigests(store, repo)
63
+ const builds = records.map((record) => {
64
+ const digest = digests.get(record.slug)
65
+ if (digest === undefined)
66
+ throw new Error(`build digest missing for ${record.slug}: the digest read broke completeness`)
67
+ return { record, nodeTargets: digestNodeTargets(digest) }
68
+ })
69
+ const states = new Map<string, Promise<BuildState>>()
70
+ const state = (slug: string) => {
71
+ let read = states.get(slug)
72
+ if (!read) {
73
+ read = readBuildFacts(store, slug).then((facts) => facts.value.state)
74
+ states.set(slug, read)
75
+ }
76
+ return read
77
+ }
78
+ return { ...sample, builds, state, migrations: await readTicketMigrations(store, repo) }
28
79
  }
29
80
 
30
81
  /** A failed or partial enumeration cannot authorize verification or publication. */
@@ -33,6 +84,11 @@ export async function observeIntegration(
33
84
  tickets: TicketSource,
34
85
  slug: string,
35
86
  inputs?: () => Promise<IntegrationObservationInputs>,
87
+ /** The configured rejected role: a child ticket in it no longer keeps the
88
+ * node incomplete. Unset means no such role. `onFailure` reports an
89
+ * enumeration or observation failure that is recorded as a diagnostic, so a
90
+ * caller can tell it apart from incompleteness; it is never persisted. */
91
+ options: { rejectedState?: string; onFailure?: (error: unknown) => void } = {},
36
92
  ): Promise<EventPayload<'integration.observed'>> {
37
93
  const record = await store.getBuild(slug)
38
94
  const state = (await readBuildFacts(store, slug)).value.state
@@ -46,15 +102,27 @@ export async function observeIntegration(
46
102
  observation.children = state.integration?.observation?.children
47
103
 
48
104
  try {
49
- if (!record?.ticket || !tickets.integrationTree || !tickets.listAll)
105
+ if (!record?.ticket || !canEnumerate(tickets))
50
106
  throw new Error('ticket source cannot establish exhaustive integration completeness')
51
107
  const {
52
- listing,
108
+ listing: shared,
109
+ targeting,
53
110
  builds,
111
+ state: facts,
54
112
  migrations: supplied,
55
113
  } = await (inputs ? inputs() : integrationObservationInputs(store, tickets, record.repo))
114
+ // Only builds whose digest names this node can relate to it; the rest
115
+ // never need a facts read.
116
+ const related = await Promise.all(
117
+ builds
118
+ .filter((build) => build.nodeTargets.includes(slug))
119
+ .map(async (build) => ({ record: build.record, state: await facts(build.record.slug) })),
120
+ )
56
121
  const migrations = supplied ?? (await readTicketMigrations(store, record.repo))
57
122
  const nodeRef = resolveTicketRef(migrations, record.ticket, tickets.name, slug)
123
+ const listing = shared ?? (await targeting?.(nodeRef.id))
124
+ if (listing === undefined)
125
+ throw new Error('ticket source cannot establish exhaustive integration completeness')
58
126
  observation.membershipSource = tickets.name
59
127
  const current = (build: BuildRecord) =>
60
128
  build.ticket
@@ -62,11 +130,26 @@ export async function observeIntegration(
62
130
  : undefined
63
131
  observation.diagnostics.push(...listing.diagnostics)
64
132
  for (const ticket of listing.tickets)
65
- if (ticket.target === nodeRef.id && !ticket.resolved) children.add(ticket.ref.id)
133
+ if (
134
+ ticket.target === nodeRef.id &&
135
+ !ticket.resolved &&
136
+ !holdsState(ticket.state, options.rejectedState)
137
+ )
138
+ children.add(ticket.ref.id)
66
139
  // Frozen claims survive edits to the source ticket's target.
67
- for (const { record: build, state: child } of builds) {
140
+ for (const { record: build, state: child } of related) {
68
141
  if (child.target?.build === slug && child.status !== 'done' && child.status !== 'aborted')
69
142
  children.add(current(build)?.id ?? build.slug)
143
+ // A merged contribution whose links the node has not recorded stays open
144
+ // until its merge or abort cleanup appends them, however its ticket moved.
145
+ if (
146
+ child.target?.build === slug &&
147
+ child.prState === 'merged' &&
148
+ child.outcome === undefined &&
149
+ !state.nodeIssueLinks?.builds.includes(build.slug) &&
150
+ contributedIssueLinks(child).length > 0
151
+ )
152
+ children.add(current(build)?.id ?? build.slug)
70
153
  if (
71
154
  [child.nodeRestack?.parentRequest, child.nodeRestack?.parentChange].some(
72
155
  (move) => move && (move.old.target?.build === slug || move.next.target?.build === slug),
@@ -118,7 +201,7 @@ export async function observeIntegration(
118
201
  for (const { record: build } of builds)
119
202
  if (
120
203
  (build.ticket?.source === tickets.name ||
121
- builds.some(
204
+ related.some(
122
205
  (entry) =>
123
206
  entry.record.slug === build.slug &&
124
207
  (entry.state.target?.build === slug ||
@@ -131,7 +214,7 @@ export async function observeIntegration(
131
214
  current(build)?.id ?? build.slug,
132
215
  build.ticket?.title,
133
216
  )
134
- for (const { record: build, state: child } of builds) {
217
+ for (const { record: build, state: child } of related) {
135
218
  if (
136
219
  !build.ticket ||
137
220
  child.target?.build !== slug ||
@@ -150,6 +233,9 @@ export async function observeIntegration(
150
233
  const entry = display.get(JSON.stringify([ref.source, ref.id]))
151
234
  if (entry) entry.claims = [...new Set([...(entry.claims ?? []), build.slug])].sort()
152
235
  }
236
+ // A targeted listing holds only current children, so a contribution whose
237
+ // ticket has since moved keeps its previous or build title. Display only:
238
+ // membership above does not depend on it.
153
239
  for (const ticket of listing.tickets)
154
240
  if (
155
241
  (ticket.ref.source === tickets.name && children.has(ticket.ref.id)) ||
@@ -166,6 +252,7 @@ export async function observeIntegration(
166
252
  )
167
253
  } catch (error) {
168
254
  observation.diagnostics.push(error instanceof Error ? error.message : String(error))
255
+ options.onFailure?.(error)
169
256
  }
170
257
  observation.openChildren = [...children].sort()
171
258
  observation.diagnostics.sort()
@@ -8,6 +8,7 @@ import type { BuildStore } from '../store/types'
8
8
  import { readBuildFacts } from '../store/reduced-reads'
9
9
  import { inspectIntegrationStack } from './integration-stack'
10
10
  import { acknowledgeNodeLanding } from './node-landing'
11
+ import { nodeIssueLinksForForge, nodeIssueLinksPublished } from './node-issue-links'
11
12
 
12
13
  export interface IntegrationLandingDeps {
13
14
  store: BuildStore
@@ -100,6 +101,22 @@ export async function landIntegrationRoot(deps: IntegrationLandingDeps): Promise
100
101
  return
101
102
  }
102
103
  await inspectIntegrationStack(exec, workspacePath, parent, head)
104
+ // Refresh the PR body to the final set (own links and children's
105
+ // union) and confirm the readback before any merge request, even when
106
+ // the published fact matches, so landing closes every fully resolved
107
+ // issue. A failure throws first.
108
+ state = (await readBuildFacts(store, slug)).value.state
109
+ const issueLinks = nodeIssueLinksForForge(state, forge)
110
+ if (issueLinks) {
111
+ await authority()
112
+ await forge.updatePrIssueLinks!(workspacePath, deps.pr, issueLinks)
113
+ if (!nodeIssueLinksPublished(state, deps.pr, issueLinks))
114
+ await store.append(slug, {
115
+ actor: KERNEL,
116
+ type: 'node.issue-links-published',
117
+ payload: { pr: deps.pr, issueLinks },
118
+ })
119
+ }
103
120
  const local = forge.name === 'local-git'
104
121
  if (!local && !forge.mergeLinearStack) return // Never substitute squash.
105
122
  const gate = local ? await forge.inspectLandingGate?.(deps.destination) : undefined
@@ -170,6 +170,23 @@ export function integrationCycleVerified(state: BuildState): boolean {
170
170
  )
171
171
  }
172
172
 
173
+ /** Durable facts that rule out preparing or admitting integration verification. */
174
+ export function integrationAdmissible(state: BuildState): boolean {
175
+ return !(
176
+ state.targetRewrite ||
177
+ state.status === 'paused' ||
178
+ state.status === 'done' ||
179
+ state.status === 'aborted' ||
180
+ state.pendingCommands.length ||
181
+ state.openEscalations.length ||
182
+ state.prState === 'merged' ||
183
+ state.prState === 'closed' ||
184
+ state.integration?.intent ||
185
+ state.nodeRestack?.parentRequest ||
186
+ state.nodeRestack?.parentChange
187
+ )
188
+ }
189
+
173
190
  export function integrationNeedsRunner(state: BuildState): boolean {
174
191
  return integrationCurrent(state) && !integrationFailed(state) && !integrationCycleVerified(state)
175
192
  }
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Forge issue keywords for a build's frozen issue links (SPEC "Forge issue
3
+ * links"). One pure module owns the text rules so the PR title and body, the
4
+ * landed commit message and every identity comparison compose identically:
5
+ *
6
+ * - each linked issue gets one canonical `Closes #N` or `Refs #N` line;
7
+ * - a closing keyword aimed at a `refs` issue is rewritten to `refs`, wherever
8
+ * it appears, so prose cannot close what the build only partly resolves;
9
+ * - the keyword paragraph sits before a terminal git trailer block, never
10
+ * inside it, so `Autobuild-Build` and co-author parsing stay intact.
11
+ *
12
+ * With no links every function returns its input unchanged.
13
+ */
14
+ import type { Forge, IssueLink } from '../ports/types'
15
+ import { splitTrailerBlock, withBuildTrailer } from './build-identity'
16
+
17
+ export interface IssueKeywordOptions {
18
+ /** `owner/name` of the forge repository. Qualified references
19
+ * (`owner/name#N`, issue URLs) count only for this repository. */
20
+ repository?: string
21
+ }
22
+
23
+ /** GitHub's closing keywords ("Linking a pull request to an issue"). */
24
+ const CLOSING = 'close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved'
25
+ const MENTION = 'refs?|references'
26
+ const SEPARATOR = String.raw`(?:[ \t]*:[ \t]*|[ \t]+)`
27
+
28
+ function escapeRegExp(text: string): string {
29
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
30
+ }
31
+
32
+ /** One issue reference in any form GitHub resolves to this repository. */
33
+ function referenceSource(repository: string | undefined): string {
34
+ const local = String.raw`#\d+|GH-\d+`
35
+ if (repository === undefined) return local
36
+ const repo = repository.split('/').map(escapeRegExp).join('/')
37
+ return [
38
+ String.raw`(?:https?://)?(?:www\.)?github\.com/${repo}/issues/\d+`,
39
+ String.raw`${repo}#\d+`,
40
+ local,
41
+ ].join('|')
42
+ }
43
+
44
+ function referencedIssue(reference: string): number {
45
+ return Number(/(\d+)$/.exec(reference)![1])
46
+ }
47
+
48
+ /** `Closes #820`, `Refs #824`, one per link, ascending by issue number. */
49
+ export function issueKeywordLines(links: readonly IssueLink[]): string[] {
50
+ return [...links]
51
+ .sort((a, b) => a.issue - b.issue)
52
+ .map((link) => `${link.intent === 'closes' ? 'Closes' : 'Refs'} #${link.issue}`)
53
+ }
54
+
55
+ /**
56
+ * Rewrite every closing keyword whose reference names a linked `refs` issue to
57
+ * `refs`, keeping the separator and the reference as written. Each
58
+ * keyword–reference pair stands alone: `Fixes #1, fixes #824` rewrites only
59
+ * the second. Other repositories, unlinked numbers and `closes` issues are
60
+ * untouched.
61
+ */
62
+ export function neutralizeClosingReferences(
63
+ text: string,
64
+ links: readonly IssueLink[],
65
+ options: IssueKeywordOptions = {},
66
+ ): string {
67
+ const refs = new Set(links.filter((link) => link.intent === 'refs').map((link) => link.issue))
68
+ if (refs.size === 0) return text
69
+ const pattern = new RegExp(
70
+ String.raw`\b(${CLOSING})(${SEPARATOR})(${referenceSource(options.repository)})(?!\w)`,
71
+ 'gi',
72
+ )
73
+ return text.replace(pattern, (whole, keyword: string, separator: string, reference: string) => {
74
+ if (!refs.has(referencedIssue(reference))) return whole
75
+ const replacement = keyword[0] === keyword[0]!.toUpperCase() ? 'Refs' : 'refs'
76
+ return `${replacement}${separator}${reference}`
77
+ })
78
+ }
79
+
80
+ /** A line that is only a keyword and a reference to a linked issue. */
81
+ function isLinkedKeywordLine(line: string, linked: ReadonlySet<number>, source: RegExp): boolean {
82
+ const match = source.exec(line)
83
+ return match !== null && linked.has(referencedIssue(match[2]!))
84
+ }
85
+
86
+ /**
87
+ * Neutralize, drop whole lines that only restate a linked issue, and append
88
+ * the canonical keyword paragraph. With `trailers` (the default) a terminal
89
+ * git trailer block stays last and the paragraph goes before it; a PR body
90
+ * passes `trailers: false` so it ends with the lines. Idempotent.
91
+ */
92
+ export function withIssueKeywords(
93
+ text: string,
94
+ links: readonly IssueLink[],
95
+ options: IssueKeywordOptions & { trailers?: boolean; includesSubject?: boolean } = {},
96
+ ): string {
97
+ if (links.length === 0) return text
98
+ const neutral = neutralizeClosingReferences(text, links, options)
99
+ const { body, trailers } =
100
+ options.trailers === false
101
+ ? { body: neutral, trailers: '' }
102
+ : splitTrailerBlock(neutral, { includesSubject: options.includesSubject === true })
103
+ const linked = new Set(links.map((link) => link.issue))
104
+ const line = new RegExp(
105
+ String.raw`^[ \t]*(${CLOSING}|${MENTION})${SEPARATOR}(${referenceSource(options.repository)})[ \t]*\.?\r?$`,
106
+ 'i',
107
+ )
108
+ const keep = (part: string): string =>
109
+ part
110
+ .split('\n')
111
+ .filter((entry) => !isLinkedKeywordLine(entry, linked, line))
112
+ .join('\n')
113
+ .replace(/\s+$/, '')
114
+ const prose = keep(body)
115
+ const tail = keep(trailers)
116
+ const block = issueKeywordLines(links).join('\n')
117
+ const composed = `${prose === '' ? '' : `${prose}\n\n`}${block}${tail === '' ? '' : `\n\n${tail}`}`
118
+ return /\n$/.test(text) ? `${composed}\n` : composed
119
+ }
120
+
121
+ /** The landed commit message: keyword paragraph, then the build trailer
122
+ * block. With no links this is exactly `withBuildTrailer`. */
123
+ export function landingMessage(
124
+ message: string,
125
+ slug: string,
126
+ links: readonly IssueLink[],
127
+ options: IssueKeywordOptions & { includesSubject?: boolean } = {},
128
+ ): string {
129
+ return withBuildTrailer(
130
+ withIssueKeywords(message, links, options),
131
+ slug,
132
+ options.includesSubject === true ? { includesSubject: true } : {},
133
+ )
134
+ }
135
+
136
+ /** A leaf's own keywords reach the default branch only when it is aimed at
137
+ * the configured base, through a forge whose merges close issues. This gates
138
+ * the landing call and a base-aimed leaf's PR. Nodes and node-target leaves
139
+ * carry links upward instead (`kernel/node-issue-links`), a root node's PR
140
+ * body emits the node's set, and a node-target leaf's PR gets refs-only lines
141
+ * from `prIssueLinksForForge`. */
142
+ export function emitsIssueKeywords(
143
+ state: {
144
+ kind?: 'work' | 'node'
145
+ target?: unknown
146
+ issueLinks: readonly IssueLink[]
147
+ },
148
+ forge: Pick<Forge, 'closesIssues'>,
149
+ ): boolean {
150
+ return (
151
+ forge.closesIssues === true &&
152
+ state.kind !== 'node' &&
153
+ state.target === undefined &&
154
+ state.issueLinks.length > 0
155
+ )
156
+ }
157
+
158
+ /** The `{issue, intent}` projection a forge's landing call receives, when it
159
+ * should. Always `{}` for a node-target leaf: a commit landed into a node
160
+ * carries no keyword lines. */
161
+ export function issueLinksForForge(
162
+ state: Parameters<typeof emitsIssueKeywords>[0],
163
+ forge: Pick<Forge, 'closesIssues'>,
164
+ ): { issueLinks: IssueLink[] } | Record<string, never> {
165
+ return emitsIssueKeywords(state, forge)
166
+ ? { issueLinks: state.issueLinks.map(({ issue, intent }) => ({ issue, intent })) }
167
+ : {}
168
+ }
169
+
170
+ /** The `{issue, intent}` projection a leaf's PR receives when it opens. A
171
+ * leaf aimed at the configured base gets its sealed links unchanged. A leaf
172
+ * aimed at a node gets every link as `refs`, so each issue shows the PR
173
+ * without the PR closing it; the closing lines land in the root node's PR. */
174
+ export function prIssueLinksForForge(
175
+ state: Parameters<typeof emitsIssueKeywords>[0],
176
+ forge: Pick<Forge, 'closesIssues'>,
177
+ ): { issueLinks: IssueLink[] } | Record<string, never> {
178
+ if (forge.closesIssues !== true || state.kind === 'node' || state.issueLinks.length === 0)
179
+ return {}
180
+ const nested = state.target !== undefined
181
+ return {
182
+ issueLinks: state.issueLinks.map(({ issue, intent }) => ({
183
+ issue,
184
+ intent: nested ? ('refs' as const) : intent,
185
+ })),
186
+ }
187
+ }
188
+
189
+ /** Human form with downgrade provenance, e.g.
190
+ * `closes #820, refs #824 (downgraded from closes: only the API half)`. */
191
+ export function describeIssueLinks(
192
+ links: ReadonlyArray<IssueLink & { downgrade?: { reason: string } }>,
193
+ ): string {
194
+ return links
195
+ .map(
196
+ (link) =>
197
+ `${link.intent} #${link.issue}${
198
+ link.downgrade !== undefined ? ` (downgraded from closes: ${link.downgrade.reason})` : ''
199
+ }`,
200
+ )
201
+ .join(', ')
202
+ }