@defrex/autobuild 0.13.0 → 1.0.0-beta.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 (210) hide show
  1. package/README.md +5 -3
  2. package/SPEC.md +673 -99
  3. package/bin/ab-dispatch-kernel.ts +4 -6
  4. package/docs/architecture.md +322 -75
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/configuration.md +112 -12
  7. package/docs/hosted-service.md +20 -2
  8. package/docs/integration-tree.md +117 -0
  9. package/docs/landing-policy.md +150 -0
  10. package/docs/mcp.md +24 -0
  11. package/docs/migration-1.0.md +68 -0
  12. package/docs/operator-api.md +20 -9
  13. package/docs/remote-store-protocol.md +114 -9
  14. package/docs/remote-ticket-protocol.md +26 -5
  15. package/docs/restacking.md +79 -0
  16. package/docs/setup.md +49 -6
  17. package/docs/ticket-dependencies.md +69 -0
  18. package/docs/ticket-migration.md +8 -0
  19. package/package.json +4 -3
  20. package/packages/core/src/cli/attention.ts +40 -163
  21. package/packages/core/src/cli/build-control.ts +75 -55
  22. package/packages/core/src/cli/bulk-control.ts +3 -2
  23. package/packages/core/src/cli/context.ts +68 -78
  24. package/packages/core/src/cli/dashboard/actions.ts +6 -3
  25. package/packages/core/src/cli/dashboard/landing-display.ts +6 -0
  26. package/packages/core/src/cli/dashboard/live.ts +5 -0
  27. package/packages/core/src/cli/dashboard/model.ts +178 -40
  28. package/packages/core/src/cli/dashboard/poll.ts +15 -9
  29. package/packages/core/src/cli/dashboard/refresh.ts +176 -0
  30. package/packages/core/src/cli/dashboard/render.ts +78 -28
  31. package/packages/core/src/cli/dashboard/repository-poll.ts +57 -0
  32. package/packages/core/src/cli/dashboard/selection.ts +7 -1
  33. package/packages/core/src/cli/dashboard/tree.ts +107 -0
  34. package/packages/core/src/cli/dispatch-frontend.ts +173 -169
  35. package/packages/core/src/cli/dispatch-process.ts +14 -7
  36. package/packages/core/src/cli/dispatch-repository-feed.ts +196 -0
  37. package/packages/core/src/cli/dispatch.ts +397 -214
  38. package/packages/core/src/cli/dispatcher-liveness.ts +41 -21
  39. package/packages/core/src/cli/harvest.ts +71 -39
  40. package/packages/core/src/cli/help.ts +49 -32
  41. package/packages/core/src/cli/historical-build-state.ts +27 -0
  42. package/packages/core/src/cli/init-validation.ts +43 -2
  43. package/packages/core/src/cli/keyboard.ts +6 -0
  44. package/packages/core/src/cli/landings.ts +18 -0
  45. package/packages/core/src/cli/main.ts +52 -18
  46. package/packages/core/src/cli/mcp.ts +9 -0
  47. package/packages/core/src/cli/pr-attachments.ts +10 -13
  48. package/packages/core/src/cli/pr-summary-publication.ts +27 -60
  49. package/packages/core/src/cli/pr-summary.ts +43 -13
  50. package/packages/core/src/cli/publication-settlement.ts +177 -21
  51. package/packages/core/src/cli/repository-status.ts +49 -2
  52. package/packages/core/src/cli/status.ts +133 -36
  53. package/packages/core/src/cli/terminal-restore.ts +54 -0
  54. package/packages/core/src/cli/terminal.ts +16 -2
  55. package/packages/core/src/cli/terminals.ts +121 -219
  56. package/packages/core/src/cli/ticket-editor.ts +10 -3
  57. package/packages/core/src/cli/ticket.ts +115 -20
  58. package/packages/core/src/cli/upgrade-commit.ts +4 -0
  59. package/packages/core/src/cli/upgrade-compatibility.ts +2 -2
  60. package/packages/core/src/cli/upgrade-landing.ts +69 -0
  61. package/packages/core/src/cli/upgrade.ts +16 -0
  62. package/packages/core/src/cli/wait.ts +194 -91
  63. package/packages/core/src/cli/watch.ts +111 -109
  64. package/packages/core/src/config/landing.ts +22 -0
  65. package/packages/core/src/config/live.ts +1 -0
  66. package/packages/core/src/config/pipeline-source.ts +4 -3
  67. package/packages/core/src/config/schema.ts +3 -0
  68. package/packages/core/src/events/catalog.ts +48 -3
  69. package/packages/core/src/events/payloads.ts +295 -6
  70. package/packages/core/src/events/repository.ts +38 -3
  71. package/packages/core/src/integration/harness.ts +11 -2
  72. package/packages/core/src/kernel/__snapshots__/reducer-registry.test.ts.snap +3330 -119
  73. package/packages/core/src/kernel/auto-merge-default.ts +1 -0
  74. package/packages/core/src/kernel/auto-merge.ts +29 -4
  75. package/packages/core/src/kernel/build-identity.ts +94 -0
  76. package/packages/core/src/kernel/change-presence.ts +179 -0
  77. package/packages/core/src/kernel/dispatch-status.ts +17 -1
  78. package/packages/core/src/kernel/dispatcher-liveness.ts +10 -4
  79. package/packages/core/src/kernel/engine.ts +89 -2
  80. package/packages/core/src/kernel/generators/build-log.ts +23 -0
  81. package/packages/core/src/kernel/generators/leaf-restack-log.ts +110 -0
  82. package/packages/core/src/kernel/generators/node-restack-log.ts +94 -0
  83. package/packages/core/src/kernel/generators/repository-journals.ts +25 -3
  84. package/packages/core/src/kernel/harvest.ts +25 -23
  85. package/packages/core/src/kernel/integration-completeness.ts +81 -0
  86. package/packages/core/src/kernel/integration-landing.ts +263 -0
  87. package/packages/core/src/kernel/integration-stack.ts +36 -0
  88. package/packages/core/src/kernel/integration-state.ts +135 -0
  89. package/packages/core/src/kernel/landing-policy.ts +47 -0
  90. package/packages/core/src/kernel/landing-publication.ts +41 -0
  91. package/packages/core/src/kernel/landing-readiness.ts +67 -0
  92. package/packages/core/src/kernel/landing-state.ts +96 -0
  93. package/packages/core/src/kernel/leaf-restack-completion.ts +24 -0
  94. package/packages/core/src/kernel/leaf-restack-state.ts +73 -0
  95. package/packages/core/src/kernel/log-index-value.ts +38 -0
  96. package/packages/core/src/kernel/log-index.ts +35 -5
  97. package/packages/core/src/kernel/node-landing.ts +439 -0
  98. package/packages/core/src/kernel/node-parent.ts +184 -0
  99. package/packages/core/src/kernel/node-restack-state.ts +191 -0
  100. package/packages/core/src/kernel/node-restack-transaction.ts +210 -0
  101. package/packages/core/src/kernel/node-restack.ts +274 -0
  102. package/packages/core/src/kernel/read-facts.ts +704 -0
  103. package/packages/core/src/kernel/reconcile-head.ts +51 -0
  104. package/packages/core/src/kernel/reconcile-restack.ts +560 -0
  105. package/packages/core/src/kernel/reducer-registry.ts +153 -3
  106. package/packages/core/src/kernel/reducer.ts +121 -6
  107. package/packages/core/src/kernel/repository-attention.ts +179 -0
  108. package/packages/core/src/kernel/service-facts.ts +135 -0
  109. package/packages/core/src/kernel/snapshot-parent.ts +33 -0
  110. package/packages/core/src/kernel/terminal-guard.ts +133 -0
  111. package/packages/core/src/ontology.ts +9 -1
  112. package/packages/core/src/operator/annotations.ts +12 -0
  113. package/packages/core/src/operator/control.ts +11 -6
  114. package/packages/core/src/operator/index.ts +6 -0
  115. package/packages/core/src/operator/landings.ts +35 -0
  116. package/packages/core/src/operator/presentation.ts +1 -0
  117. package/packages/core/src/operator/protocol.ts +12 -3
  118. package/packages/core/src/operator/query.ts +40 -21
  119. package/packages/core/src/operator/read-view.ts +4 -13
  120. package/packages/core/src/operator/registry.ts +48 -19
  121. package/packages/core/src/operator/requests.ts +3 -22
  122. package/packages/core/src/operator/sandbox.ts +10 -9
  123. package/packages/core/src/operator/tickets.ts +57 -11
  124. package/packages/core/src/plugin-sdk/index.ts +13 -0
  125. package/packages/core/src/ports/forge/contract.ts +91 -3
  126. package/packages/core/src/ports/forge/fake.ts +142 -4
  127. package/packages/core/src/ports/forge/git-rewrite.ts +232 -0
  128. package/packages/core/src/ports/forge/github-readiness.ts +421 -0
  129. package/packages/core/src/ports/forge/github.ts +631 -35
  130. package/packages/core/src/ports/forge/local-git.ts +119 -5
  131. package/packages/core/src/ports/forge/readiness.ts +99 -0
  132. package/packages/core/src/ports/tickets/contract.ts +41 -0
  133. package/packages/core/src/ports/tickets/create.ts +8 -1
  134. package/packages/core/src/ports/tickets/fake.ts +32 -1
  135. package/packages/core/src/ports/tickets/file-codec.ts +7 -0
  136. package/packages/core/src/ports/tickets/file.ts +18 -1
  137. package/packages/core/src/ports/tickets/hosted-index.ts +2 -0
  138. package/packages/core/src/ports/tickets/linear.ts +124 -4
  139. package/packages/core/src/ports/tickets/migration.ts +25 -1
  140. package/packages/core/src/ports/tickets/operations.ts +7 -2
  141. package/packages/core/src/ports/tickets/remote-protocol.ts +19 -0
  142. package/packages/core/src/ports/tickets/remote.ts +10 -1
  143. package/packages/core/src/ports/tickets/revision.ts +3 -1
  144. package/packages/core/src/ports/tickets/tree.ts +148 -0
  145. package/packages/core/src/ports/tickets/update.ts +15 -2
  146. package/packages/core/src/ports/types.ts +135 -5
  147. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  148. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -1
  149. package/packages/core/src/ports/workspace/vercel-sandbox.ts +60 -3
  150. package/packages/core/src/processes/build-child.ts +6 -6
  151. package/packages/core/src/processes/build-runner.ts +586 -87
  152. package/packages/core/src/processes/dispatch-failure-budget.ts +5 -4
  153. package/packages/core/src/processes/dispatcher-selectors.ts +15 -9
  154. package/packages/core/src/processes/dispatcher.ts +2239 -357
  155. package/packages/core/src/processes/execution-no-progress.ts +46 -1
  156. package/packages/core/src/processes/harvest-execution-state.ts +15 -9
  157. package/packages/core/src/processes/harvest-runner.ts +34 -70
  158. package/packages/core/src/processes/harvest.ts +38 -15
  159. package/packages/core/src/processes/infrastructure-failure-budget.ts +13 -15
  160. package/packages/core/src/processes/orchestrator-tick.ts +2 -2
  161. package/packages/core/src/processes/publication-loss.ts +35 -21
  162. package/packages/core/src/processes/publication-state.ts +30 -5
  163. package/packages/core/src/processes/repo-view.ts +244 -1130
  164. package/packages/core/src/processes/tick-publication.ts +110 -0
  165. package/packages/core/src/store/adapter.ts +23 -0
  166. package/packages/core/src/store/build-scope.ts +35 -0
  167. package/packages/core/src/store/contract.ts +909 -0
  168. package/packages/core/src/store/digest.ts +52 -4
  169. package/packages/core/src/store/local/schema.ts +26 -13
  170. package/packages/core/src/store/local/store.ts +296 -55
  171. package/packages/core/src/store/memory.ts +181 -30
  172. package/packages/core/src/store/phase-session.ts +34 -0
  173. package/packages/core/src/store/reduced-reads.ts +240 -0
  174. package/packages/core/src/store/reducer-value-shapes.json +18323 -0
  175. package/packages/core/src/store/reducer-value-validation.ts +96 -0
  176. package/packages/core/src/store/reducer-values.ts +145 -0
  177. package/packages/core/src/store/remote/client.ts +85 -0
  178. package/packages/core/src/store/remote/compatibility.ts +21 -9
  179. package/packages/core/src/store/remote/index.ts +19 -0
  180. package/packages/core/src/store/remote/protocol.ts +27 -0
  181. package/packages/core/src/store/remote/version.ts +3 -1
  182. package/packages/core/src/store/repo-state-events.ts +3 -1
  183. package/packages/core/src/store/repo-tick.ts +72 -0
  184. package/packages/core/src/store/session-handle.ts +34 -0
  185. package/packages/core/src/store/snapshots.ts +10 -0
  186. package/packages/core/src/store/subscribe.ts +1 -1
  187. package/packages/core/src/store/ticket-assets.ts +4 -4
  188. package/packages/core/src/store/types.ts +71 -6
  189. package/packages/core/src/testing/dispatch-read-budget.ts +215 -0
  190. package/packages/core/src/testing/index.ts +10 -0
  191. package/packages/core/src/testing/reduced-read-budget.ts +502 -0
  192. package/packages/core/src/testing/refresh-scheduler.ts +32 -0
  193. package/skills/guide/SKILL.md +116 -62
  194. package/skills/guide/references/integration-tree.md +117 -0
  195. package/skills/guide/references/landing-policy.md +150 -0
  196. package/skills/guide/references/migration-1.0.md +68 -0
  197. package/skills/guide/references/operator-api.md +13 -6
  198. package/skills/guide/references/plugin-authoring.md +34 -0
  199. package/skills/guide/references/remote-store-protocol.md +114 -9
  200. package/skills/guide/references/remote-ticket-protocol.md +26 -5
  201. package/skills/guide/references/restacking.md +79 -0
  202. package/skills/guide/references/setup.md +49 -6
  203. package/skills/guide/references/ticket-dependencies.md +69 -0
  204. package/skills/guide/references/ticket-migration.md +8 -0
  205. package/skills/operate/SKILL.md +55 -5
  206. package/skills/reconcile/SKILL.md +55 -48
  207. package/skills/spec/SKILL.md +67 -1
  208. package/skills/tickets/SKILL.md +55 -2
  209. package/templates/autobuild.toml +3 -0
  210. package/templates/hosted-service/package.json +2 -2
@@ -110,6 +110,7 @@ export function pickAutoMergeDefault(
110
110
  * this predicate must be revisited.
111
111
  */
112
112
  export function autoMergeDefaultEligible(state: BuildState): boolean {
113
+ if (state.kind === 'node') return false
113
114
  if (state.status === 'done' || state.status === 'aborted') return false
114
115
  // An empty log is a record whose `build.created` has not landed yet (the
115
116
  // crash or one-await window between `createBuild` and the first append):
@@ -1,3 +1,4 @@
1
+ import { readDeferralLedger } from '../store/reduced-reads'
1
2
  import type { AbEvent, EventEnvelope, EventWrite } from '../events/catalog'
2
3
  import { KERNEL } from '../events/envelope'
3
4
  import { autoMergeDeferralClasses, type AutoMergeDeferralReason } from '../ports/types'
@@ -111,7 +112,7 @@ export function autoMergeDeferralRef(prNumber: number, commandSeq: number): stri
111
112
  * `pr.closed` fact in the log ends it — and until later evidence proves the
112
113
  * PR head changed, superseding the recorded condition until the gate
113
114
  * re-examines consent and records a fresh observation. Head-changing evidence
114
- * is a `reconcile.completed` (the resolution is a merge commit on the branch)
115
+ * is a `reconcile.completed` (a replayed change, or a historical merge resolution)
115
116
  * or a `finalize.completed` whose head differs from the head the observation
116
117
  * was recorded under. The dedupe and the projection share this predicate, so
117
118
  * a stale observation stops suppressing and re-recording after reconcile
@@ -273,6 +274,8 @@ const DEFERRAL_SUMMARIES = {
273
274
  'github-plan-limitation':
274
275
  'GitHub rulesets are unavailable because of the repository account plan',
275
276
  'repository-auto-merge-disabled': 'repository-level auto-merge is disabled',
277
+ 'gated-node-destination':
278
+ 'node destination has merge-blocking gates; serialized landing requires human action',
276
279
  'unproven-gate-state': 'merge-gate state or native auto-merge application could not be proven',
277
280
  'merge-conflicts': 'the PR has merge conflicts with its base branch',
278
281
  'mergeability-uncomputed':
@@ -322,10 +325,10 @@ export async function recordAutoMergeDeferralObservation(
322
325
  ): Promise<EventEnvelope<'observation.recorded'> | null> {
323
326
  if (autoMergeDeferralClasses[reason.code] === 'pipeline-resolved') return null
324
327
  while (true) {
325
- const events = await store.getEvents(slug)
326
- if (hasAutoMergeDeferralObservation(events, prNumber, commandSeq)) return null
328
+ const current = await readDeferralLedger(store, slug)
329
+ if (deferralObservationFrom(current.value, prNumber, commandSeq)) return null
327
330
 
328
- const expectedSeq = events.at(-1)?.seq ?? 0
331
+ const expectedSeq = current.cursor
329
332
  const appended = await store.appendIfCurrent(
330
333
  slug,
331
334
  expectedSeq,
@@ -334,3 +337,25 @@ export async function recordAutoMergeDeferralObservation(
334
337
  if (appended !== null) return appended
335
338
  }
336
339
  }
340
+
341
+ /** Clock-independent merge attention shared by persisted seeds and CLI output. */
342
+ export function mergeAttentionFromFacts(state: BuildState, ledger: DeferralLedger) {
343
+ if (state.pr && state.landing?.forgeMerge?.classification === 'possible-stale-enable')
344
+ return {
345
+ pr: state.pr,
346
+ reason: 'Landing contrary to policy: possible stale native enable; inspect the target',
347
+ }
348
+ if (
349
+ !state.finalizeCompletedSeq ||
350
+ !state.pr ||
351
+ state.prState !== 'open' ||
352
+ state.status === 'done' ||
353
+ state.status === 'aborted'
354
+ )
355
+ return null
356
+ // Consent and hold attention belongs to the current readiness queue. Only
357
+ // gate deferrals remain here, so stale or unfinished landings cannot wake
358
+ // through a second, weaker consent predicate.
359
+ const deferral = currentAutoMergeDeferralFrom(ledger, state)
360
+ return deferral === undefined ? null : { pr: state.pr, reason: deferral }
361
+ }
@@ -0,0 +1,94 @@
1
+ /** Stable change identity, independent of commit object ids. */
2
+ const KEY = 'Autobuild-Build'
3
+
4
+ export function validateBuildSlug(slug: string): void {
5
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) {
6
+ throw new Error(`invalid build slug: ${JSON.stringify(slug)}`)
7
+ }
8
+ }
9
+
10
+ interface Trailer {
11
+ key: string
12
+ value: string
13
+ raw: string
14
+ }
15
+
16
+ /** Only the terminal paragraph can be a trailer block. Continuations belong
17
+ * to the preceding trailer; prose elsewhere is never identity evidence. */
18
+ function splitTrailers(
19
+ message: string,
20
+ allowStandalone = true,
21
+ ): { prefix: string; trailers: Trailer[] } {
22
+ const content = message.replace(/(?:\r?\n)+$/, '')
23
+ const boundaries = [...content.matchAll(/\r?\n(?:[ \t]*\r?\n)+/g)]
24
+ const boundary = boundaries.at(-1)
25
+ const start = boundary === undefined ? 0 : boundary.index + boundary[0].length
26
+ if (boundary === undefined && !allowStandalone) return { prefix: content, trailers: [] }
27
+ const lines = content.slice(start).split('\n')
28
+ const trailers: Trailer[] = []
29
+ for (const line of lines) {
30
+ const match = /^([A-Za-z0-9-]+)[ \t]*:[ \t]*(.*)\r?$/.exec(line)
31
+ if (match) {
32
+ trailers.push({ key: match[1]!, value: match[2]!.trim(), raw: line })
33
+ } else if (/^[ \t]+\S/.test(line) && trailers.length > 0) {
34
+ const last = trailers[trailers.length - 1]!
35
+ last.value += `\n${line.trim()}`
36
+ last.raw += `\n${line}`
37
+ } else {
38
+ trailers.push({ key: '', value: '', raw: line })
39
+ }
40
+ }
41
+ const entries = trailers.filter((entry) => entry.key !== '')
42
+ // Git accepts mixed prose/trailer paragraphs only when a generated signoff
43
+ // is present and trailers make up at least a quarter of the paragraph.
44
+ if (
45
+ entries.length !== trailers.length &&
46
+ !(
47
+ entries.some((entry) => entry.key.toLowerCase() === 'signed-off-by') &&
48
+ entries.length * 4 >= trailers.length
49
+ )
50
+ ) {
51
+ return { prefix: content, trailers: [] }
52
+ }
53
+ return { prefix: content.slice(0, start), trailers }
54
+ }
55
+
56
+ export function buildTrailers(message: string): string[] {
57
+ return splitTrailers(message, false)
58
+ .trailers.filter((entry) => entry.key.toLowerCase() === KEY.toLowerCase())
59
+ .map((entry) => entry.value)
60
+ }
61
+
62
+ export function hasBuildTrailer(message: string, slug: string): boolean {
63
+ validateBuildSlug(slug)
64
+ return buildTrailers(message).includes(slug)
65
+ }
66
+
67
+ /** Preserve non-identity bytes, use LF for new separators, and emit exactly
68
+ * one final newline. Empty bodies become a trailer-only message. */
69
+ export function withBuildTrailer(
70
+ message: string,
71
+ slug: string,
72
+ options: { includesSubject?: boolean } = {},
73
+ ): string {
74
+ validateBuildSlug(slug)
75
+ const { prefix, trailers } = splitTrailers(message, options.includesSubject !== true)
76
+ const kept = trailers.filter((entry) => entry.key.toLowerCase() !== KEY.toLowerCase())
77
+ let body = prefix + kept.map((entry) => entry.raw).join('\n')
78
+ if (kept.length > 0) body += '\n'
79
+ else if (
80
+ (body !== '' || options.includesSubject === true) &&
81
+ !/(?:\r?\n)[ \t]*(?:\r?\n)$/.test(body)
82
+ )
83
+ body += '\n\n'
84
+ return `${body}${KEY}: ${slug}\n`
85
+ }
86
+
87
+ export async function historyContainsBuild(
88
+ messages: AsyncIterable<string>,
89
+ slug: string,
90
+ ): Promise<boolean> {
91
+ validateBuildSlug(slug)
92
+ for await (const message of messages) if (hasBuildTrailer(message, slug)) return true
93
+ return false
94
+ }
@@ -0,0 +1,179 @@
1
+ import type { BuildRecord, BuildDigest } from '../store/types'
2
+ import type { CurrentBuildFacts } from '../store/reduced-reads'
3
+ import type { BuildState } from './reducer'
4
+ import type { NodeGit } from './node-restack'
5
+ import { history } from './node-restack'
6
+ import { buildTrailers } from './build-identity'
7
+
8
+ export type ChangeIdentity = `build:${string}` | `foreign:${string}`
9
+ export const normalizeIdentities = (ids: Iterable<ChangeIdentity>): ChangeIdentity[] =>
10
+ [...new Set(ids)].sort()
11
+ export interface PresenceBuild {
12
+ record: BuildRecord
13
+ digest: BuildDigest
14
+ }
15
+ /** A tied newest generation is an error, never an invitation to fall back. */
16
+ export function blockerBuild(
17
+ entries: PresenceBuild[],
18
+ source: string,
19
+ id: string,
20
+ ): PresenceBuild | string | undefined {
21
+ const generations = entries
22
+ .filter(({ record }) => record.ticket?.source === source && record.ticket.id === id)
23
+ .sort(
24
+ (a, b) =>
25
+ b.record.createdAt.localeCompare(a.record.createdAt) ||
26
+ b.record.slug.localeCompare(a.record.slug),
27
+ )
28
+ if (generations[0] && generations[1]?.record.createdAt === generations[0].record.createdAt)
29
+ return `blocker ${id} has ambiguous build generations at ${generations[0].record.createdAt}`
30
+ return generations[0]
31
+ }
32
+ export function missingChanges(
33
+ required: readonly ChangeIdentity[],
34
+ present: readonly string[],
35
+ ): ChangeIdentity[] {
36
+ const available = new Set(present)
37
+ return required.filter((id) => !available.has(id))
38
+ }
39
+
40
+ function originalForeign(sha: string, aliases: Map<string, string>): string {
41
+ const seen = new Set<string>()
42
+ while (aliases.has(sha) && aliases.get(sha) !== sha) {
43
+ if (seen.has(sha)) throw new Error('cyclic foreign identity evidence')
44
+ seen.add(sha)
45
+ sha = aliases.get(sha)!
46
+ }
47
+ return sha
48
+ }
49
+
50
+ export interface LandingEvidence {
51
+ slug: string
52
+ sha: string
53
+ /** A node landing transports its completed owned contribution. */
54
+ contribution?: ChangeIdentity[]
55
+ }
56
+ /** Stable identities and confirmed foreign replay aliases survive node rewrites.
57
+ * Expand transported contributions transitively, including older manifests
58
+ * that retained a nested node identity rather than its leaf identities. */
59
+ function expandLandings(
60
+ identities: ChangeIdentity[],
61
+ proofs: ChangeIdentity[],
62
+ landings: LandingEvidence[],
63
+ ): ChangeIdentity[] {
64
+ const byIdentity = new Map<ChangeIdentity, LandingEvidence[]>()
65
+ for (const landing of landings) {
66
+ for (const key of [`build:${landing.slug}`, `foreign:${landing.sha}`] as ChangeIdentity[]) {
67
+ const proofs = byIdentity.get(key) ?? []
68
+ proofs.push(landing)
69
+ byIdentity.set(key, proofs)
70
+ }
71
+ }
72
+ const result = new Set(identities)
73
+ const visited = new Set<ChangeIdentity>()
74
+ const pending = [...identities, ...proofs]
75
+ while (pending.length) {
76
+ const identity = pending.pop()!
77
+ if (visited.has(identity)) continue
78
+ visited.add(identity)
79
+ for (const landing of byIdentity.get(identity) ?? []) {
80
+ const transported = landing.contribution ?? [`build:${landing.slug}` as const]
81
+ for (const item of transported) {
82
+ result.add(item)
83
+ pending.push(item)
84
+ }
85
+ }
86
+ }
87
+ return normalizeIdentities(result)
88
+ }
89
+
90
+ /** Exact Git ancestry plus confirmed landing facts handles trailerless squash
91
+ * commits. No optimistic writer intent or source lifecycle is consulted. */
92
+ export async function observePresence(
93
+ git: NodeGit,
94
+ head: string,
95
+ landings: LandingEvidence[],
96
+ aliases = new Map<string, string>(),
97
+ ): Promise<ChangeIdentity[]> {
98
+ const commits = await history(git, [head])
99
+ const proofs: ChangeIdentity[] = []
100
+ const result: ChangeIdentity[] = []
101
+ const relevantForeign = new Set(
102
+ landings
103
+ .flatMap((landing) => landing.contribution ?? [])
104
+ .filter((id) => id.startsWith('foreign:')),
105
+ )
106
+ for (const commit of commits) {
107
+ for (const build of buildTrailers(commit.message)) result.push(`build:${build}`)
108
+ const foreign: ChangeIdentity = `foreign:${originalForeign(commit.sha, aliases)}`
109
+ proofs.push(foreign, `foreign:${commit.sha}`)
110
+ if (aliases.has(commit.sha) || relevantForeign.has(foreign)) result.push(foreign)
111
+ }
112
+ return expandLandings(result, proofs, landings)
113
+ }
114
+
115
+ /** Reconstruct a historical node contribution only from its retained source
116
+ * range. The caller must establish the source head and confirmed landing. */
117
+ export async function ownedContribution(
118
+ git: NodeGit,
119
+ base: string,
120
+ head: string,
121
+ landings: LandingEvidence[],
122
+ aliases: Map<string, string>,
123
+ ): Promise<ChangeIdentity[]> {
124
+ const check = await git.exec(['git', 'merge-base', '--is-ancestor', base, head], {
125
+ cwd: git.workspacePath,
126
+ })
127
+ if (check.exitCode !== 0) throw new Error('cannot establish node contribution boundary')
128
+ const commits = await history(git, [`${base}..${head}`], ['--first-parent'])
129
+ const proofs: ChangeIdentity[] = []
130
+ const result: ChangeIdentity[] = []
131
+ for (const commit of commits) {
132
+ const trailers = buildTrailers(commit.message)
133
+ if (trailers.length > 1) throw new Error('ambiguous node contribution identity')
134
+ if (trailers.length === 1) result.push(`build:${trailers[0]!}`)
135
+ else result.push(`foreign:${originalForeign(commit.sha, aliases)}`)
136
+ proofs.push(`foreign:${commit.sha}`, `foreign:${originalForeign(commit.sha, aliases)}`)
137
+ }
138
+ return expandLandings(result, proofs, landings)
139
+ }
140
+
141
+ export interface PresenceInputs {
142
+ entries: PresenceBuild[]
143
+ states: Map<string, BuildState>
144
+ aliases: Map<string, string>
145
+ landings: LandingEvidence[]
146
+ }
147
+ /** Read full state only for the destinations whose histories are inspected.
148
+ * Confirmed landing/contribution evidence comes from the batched digest read. */
149
+ export async function presenceInputs(
150
+ store: { buildFacts(slug: string): Promise<CurrentBuildFacts> },
151
+ entries: PresenceBuild[],
152
+ destinations: Iterable<string> = [],
153
+ ): Promise<PresenceInputs> {
154
+ const states = new Map<string, BuildState>()
155
+ const aliases = new Map<string, string>()
156
+ const pending = [...destinations]
157
+ while (pending.length) {
158
+ const slug = pending.pop()!
159
+ if (states.has(slug)) continue
160
+ const state = (await store.buildFacts(slug)).state
161
+ states.set(slug, state)
162
+ for (const [sha, original] of Object.entries(state.nodeRestack?.foreignAliases ?? {}))
163
+ aliases.set(sha, original)
164
+ if (state.target) pending.push(state.target.build)
165
+ }
166
+ const landings: LandingEvidence[] = []
167
+ for (const { record, digest } of entries) {
168
+ if (!digest.mergedSha || digest.terminal === 'aborted' || digest.prClosed) continue
169
+ if (digest.kind === 'node') {
170
+ if (digest.nodeContribution?.landing === digest.mergedSha)
171
+ landings.push({
172
+ slug: record.slug,
173
+ sha: digest.mergedSha,
174
+ contribution: digest.nodeContribution.identities as ChangeIdentity[],
175
+ })
176
+ } else landings.push({ slug: record.slug, sha: digest.mergedSha })
177
+ }
178
+ return { entries, states, aliases, landings }
179
+ }
@@ -1,3 +1,5 @@
1
+ import { formatReadinessFailure } from '../ports/forge/readiness'
2
+ import type { RepositoryEventPayload } from '../events/repository'
1
3
  import type { RepositoryEvent } from '../events/repository'
2
4
  import type { ArtifactRef } from '../ontology'
3
5
  import type { IncrementalReducer } from './incremental'
@@ -14,6 +16,7 @@ export interface DispatchStatus {
14
16
  creationWithheld?: number
15
17
  yieldedHolder?: string
16
18
  availableUpgrade?: string
19
+ forgeReadinessFailures?: RepositoryEventPayload<'dispatcher.forge-readiness-failed'>[]
17
20
  roleWarnings: string[]
18
21
  diagnostics: string[]
19
22
  /** Latest notice of warning/failure severity, retained independently from routine notices. */
@@ -49,6 +52,9 @@ export function reduceDispatchStatus(
49
52
  }
50
53
  : {
51
54
  ...previous,
55
+ ...(previous.forgeReadinessFailures
56
+ ? { forgeReadinessFailures: [...previous.forgeReadinessFailures] }
57
+ : {}),
52
58
  roleWarnings: [...previous.roleWarnings],
53
59
  diagnostics: [...previous.diagnostics],
54
60
  }
@@ -63,6 +69,7 @@ export function reduceDispatchStatus(
63
69
  state.health = 'running'
64
70
  state.effectiveConfig = event.payload.effectiveConfig
65
71
  state.roleWarnings = [...event.payload.roleWarnings]
72
+ state.forgeReadinessFailures = undefined
66
73
  state.notice = undefined
67
74
  state.warningNotice = undefined
68
75
  break
@@ -79,6 +86,11 @@ export function reduceDispatchStatus(
79
86
  : 'autobuild.toml reloaded'
80
87
  if (event.payload.restartRequired.length > 0) state.warningNotice = state.notice
81
88
  break
89
+ case 'dispatcher.forge-readiness-failed':
90
+ state.forgeReadinessFailures ??= []
91
+ if (!state.forgeReadinessFailures.some((failure) => failure.check === event.payload.check))
92
+ state.forgeReadinessFailures.push({ ...event.payload })
93
+ break
82
94
  case 'dispatcher.config-rejected':
83
95
  state.notice = errorNotice('config reload rejected', event.payload.error)
84
96
  state.warningNotice = state.notice
@@ -151,7 +163,7 @@ export function reduceDispatchStatus(
151
163
 
152
164
  /** Bump when `DispatchStatus`'s shape or fold semantics change (it is its own
153
165
  * accumulator: `lastSeq` makes the fold skip already-seen events). */
154
- export const DISPATCH_STATUS_REDUCER_VERSION = 2
166
+ export const DISPATCH_STATUS_REDUCER_VERSION = 3
155
167
 
156
168
  /** The incremental form of `reduceDispatchStatus` for one run. The run is a
157
169
  * parameter, so this is a factory. */
@@ -170,3 +182,7 @@ export function dispatchStatusReducer(
170
182
  reduce: (events) => reduceDispatchStatus(events, run),
171
183
  }
172
184
  }
185
+
186
+ export function forgeReadinessWarnings(status: Readonly<DispatchStatus>): string[] {
187
+ return (status.forgeReadinessFailures ?? []).map(formatReadinessFailure)
188
+ }
@@ -18,6 +18,9 @@ export function projectDispatcherLiveness(
18
18
  (e.type === 'dispatcher.tick-completed' || e.type === 'dispatcher.tick-failed') &&
19
19
  e.payload.run === id,
20
20
  )
21
+ const finished = record?.tick?.finished?.run === id ? record.tick.finished : undefined
22
+ const useSample = finished !== undefined && (!tick || finished.completedAt >= tick.ts)
23
+ const lastTickAt = useSample ? finished.completedAt : (tick?.ts ?? null)
21
24
  const heartbeatAt =
22
25
  record?.lease?.holder === id && start && record.heartbeatAt && record.heartbeatAt >= start.ts
23
26
  ? record.heartbeatAt
@@ -30,10 +33,13 @@ export function projectDispatcherLiveness(
30
33
  heartbeatAt,
31
34
  heartbeatAgeMs: heartbeatAt === null ? null : age(heartbeatAt),
32
35
  leaseExpiresAt: record?.lease?.holder === id ? record.lease.expiresAt : null,
33
- lastTickAt: tick?.ts ?? null,
34
- lastTickAgeMs: tick ? age(tick.ts) : null,
35
- lastTick:
36
- tick?.type === 'dispatcher.tick-completed'
36
+ lastTickAt,
37
+ lastTickAgeMs: lastTickAt ? age(lastTickAt) : null,
38
+ lastTick: useSample
39
+ ? finished.outcome === 'completed'
40
+ ? { outcome: 'completed' as const, counters: finished.counters }
41
+ : { outcome: 'failed' as const, error: finished.error }
42
+ : tick?.type === 'dispatcher.tick-completed'
37
43
  ? { outcome: 'completed' as const, counters: tick.payload.counters }
38
44
  : tick?.type === 'dispatcher.tick-failed'
39
45
  ? { outcome: 'failed' as const, error: tick.payload.error }
@@ -1,3 +1,4 @@
1
+ import { integrationCurrent, integrationConfig, integrationFailed } from './integration-state'
1
2
  /**
2
3
  * The kernel pipeline engine (SPEC §8): "read the event log, decide the next
3
4
  * phase per the transition table, invoke the AgentRunner with `/{skill}
@@ -55,6 +56,7 @@ export type VerifyAction =
55
56
  export type FinalizeAction = { kind: 'check'; command: string } | { kind: 'agent'; skill: string }
56
57
 
57
58
  export type Decision =
59
+ | { kind: 'restack'; trigger: 'verify-entry' | 'awaiting-landing'; cycle: number }
58
60
  | { kind: 'capture-reconcile-policy'; reconcileSeq: number }
59
61
  | { kind: 'wait'; reason: WaitReason }
60
62
  | { kind: 'acknowledge'; command: 'pause' | 'resume' | 'abort' }
@@ -143,6 +145,59 @@ export function decideNextFromFacts(state: BuildState, log: LogIndex, config: Co
143
145
  // ── 3. Escalations (§11, §15.6-B) ──────────────────────────────────────────
144
146
  // blocked ≡ any open (unanswered) escalation (§15.5).
145
147
  if (state.openEscalations.length > 0) return { kind: 'wait', reason: 'blocked' }
148
+ if (state.kind === 'node') {
149
+ if (state.nodeRestack?.conflict) {
150
+ const attempt =
151
+ state.currentPhase?.phase === 'reconcile'
152
+ ? (state.currentPhase.attempt ?? state.reconcileAttempts)
153
+ : state.reconcileAttempts + 1
154
+ return {
155
+ kind: 'run-phase',
156
+ phase: 'reconcile',
157
+ round: attempt,
158
+ reconcile: { attempt },
159
+ }
160
+ }
161
+ const cycle = state.integration?.cycle
162
+ if (!integrationCurrent(state) || cycle?.config !== integrationConfig(config))
163
+ return { kind: 'wait', reason: 'awaiting-pr' }
164
+ if (integrationFailed(state)) return { kind: 'wait', reason: 'blocked' }
165
+ const results = log.verifyCompleted.filter(
166
+ (result) =>
167
+ result.seq > cycle.seq &&
168
+ result.restackId === cycle.id &&
169
+ result.headSha === cycle.head &&
170
+ result.baseSha === cycle.parent,
171
+ )
172
+ const starts = log.verifyStarted.filter(
173
+ (result) => result.seq > cycle.seq && result.restackId === cycle.id,
174
+ )
175
+ const attempts = [...results, ...starts].map((result) => result.attempt)
176
+ const attempt = attempts.length ? Math.max(...attempts) : log.maxVerifyAttemptEver + 1
177
+ for (const step of config.verify.steps) {
178
+ if (
179
+ results.some(
180
+ (result) =>
181
+ result.step === step && (result.outcome === 'pass' || result.outcome === 'skipped'),
182
+ )
183
+ )
184
+ continue
185
+ const selected = config.verify.stepConfigs[step]!
186
+ const action: VerifyAction =
187
+ selected.kind === 'check'
188
+ ? {
189
+ kind: 'run-check',
190
+ step,
191
+ command: config.commands[selected.command] ?? selected.command,
192
+ attempt,
193
+ }
194
+ : { kind: 'run-agent-verify', step, skill: selected.skill, attempt }
195
+ return selected.paths === undefined || selected.always === true
196
+ ? action
197
+ : { kind: 'evaluate-verify', step, attempt, paths: selected.paths, action }
198
+ }
199
+ return { kind: 'wait', reason: 'awaiting-pr' }
200
+ }
146
201
  // revise-spec: park until the human lands spec rev N+1 (§6.3); the
147
202
  // spec.revised event's seq becomes the restart boundary used everywhere
148
203
  // below. guidance and dismiss-finding resolutions do not decide anything
@@ -306,6 +361,23 @@ export function decideNextFromFacts(state: BuildState, log: LogIndex, config: Co
306
361
  ? { kind: 'run-phase', phase: 'implement', round }
307
362
  : { kind: 'run-phase', phase: 'implement', round, feedback }
308
363
  }
364
+ // A frozen transaction always wins over a new observation. The runner owns
365
+ // workspace mutation; the dispatcher only records target movement.
366
+ if (log.restack.active !== undefined) {
367
+ if (log.restack.replay?.conflicted) {
368
+ const round = log.restack.reconcileAttempt ?? state.reconcileAttempts + 1
369
+ return { kind: 'run-phase', phase: 'reconcile', round, reconcile: { attempt: round } }
370
+ }
371
+ return { kind: 'restack', trigger: log.restack.active.trigger, cycle: log.restack.active.cycle }
372
+ }
373
+ if (
374
+ log.restack.gates[String(cycleBoundary)] === undefined &&
375
+ (log.restack.finalizedAt ?? 0) < cycleBoundary &&
376
+ !log.verifyStarted.some((v) => v.seq > cycleBoundary) &&
377
+ cycleResults.length === 0
378
+ ) {
379
+ return { kind: 'restack', trigger: 'verify-entry', cycle: cycleBoundary }
380
+ }
309
381
  // Attempt numbering (§15.6-A): every step in one cycle shares one attempt.
310
382
  // A cycle already underway (started or completed events after the boundary)
311
383
  // keeps its number — a crashed step re-runs at the SAME attempt (§15.6-C);
@@ -321,10 +393,17 @@ export function decideNextFromFacts(state: BuildState, log: LogIndex, config: Co
321
393
  const reconcileCycle =
322
394
  log.lastReconcileCompletedSeq > Math.max(log.code.latestApproveSeq, log.restartSeq)
323
395
  const policy =
324
- reconcileCycle && log.reconcilePolicy?.reconcileSeq === cycleBoundary
396
+ reconcileCycle &&
397
+ !log.restack.initialVerification &&
398
+ log.reconcilePolicy?.reconcileSeq === cycleBoundary
325
399
  ? log.reconcilePolicy
326
400
  : undefined
327
- if (reconcileCycle && policy === undefined && cycleAttempts.length === 0) {
401
+ if (
402
+ reconcileCycle &&
403
+ !log.restack.initialVerification &&
404
+ policy === undefined &&
405
+ cycleAttempts.length === 0
406
+ ) {
328
407
  return { kind: 'capture-reconcile-policy', reconcileSeq: cycleBoundary }
329
408
  }
330
409
  const approvedPlan = log.plan.approvedPlan
@@ -431,6 +510,14 @@ export function decideNextFromFacts(state: BuildState, log: LogIndex, config: Co
431
510
  // ── 9. Post-PR epilogue (§15.7): finalize → (conflicted → reconcile →
432
511
  // verify:*)* → merged | closed. The dispatcher's janitor emits pr.* and
433
512
  // completes the build; the engine only ever runs reconcile here.
513
+ if (
514
+ log.restack.target !== undefined &&
515
+ (log.restack.target.sha !== (log.restack.completed?.targetBase ?? log.restack.initialBase) ||
516
+ (state.target !== undefined &&
517
+ (log.restack.postStepAt ?? 0) > (log.restack.completedAt ?? 0)))
518
+ ) {
519
+ return { kind: 'restack', trigger: 'awaiting-landing', cycle: cycleBoundary }
520
+ }
434
521
  if (state.prState === 'conflicted' && log.lastConflict !== undefined) {
435
522
  if (log.conflictReconcileStarted !== undefined) {
436
523
  // Crashed reconcile: re-run the SAME attempt from its start (§15.6-C) —
@@ -40,6 +40,29 @@ function randomWrite(rand: () => number): EventWrite {
40
40
  const session = pick(rand, ['s_a', 's_b'])
41
41
  const step = pick(rand, ['types', 'unit'])
42
42
  const templates: Array<() => EventWrite> = [
43
+ () =>
44
+ w('landing.decided', {
45
+ candidate: { head: SHA, parent: 'b'.repeat(40), cycle: 'cycle' },
46
+ from: pick(rand, ['leaf', 'node']),
47
+ into: rand() < 0.5 ? { kind: 'root' } : { kind: 'node', ticket: 'N-1' },
48
+ labels: ['release'],
49
+ mode: pick(rand, ['auto', 'consent']),
50
+ rule:
51
+ rand() < 0.5
52
+ ? { default: true }
53
+ : { index: 0, snapshot: { label: 'release', mode: 'auto' } },
54
+ }),
55
+ () => w('build.hold-requested', {}),
56
+ () => w('build.land-requested', { decisionSeq: 1 }),
57
+ () => w('landing.command-acknowledged', { commandSeq: 1 }),
58
+ () =>
59
+ w('landing.native-applied', {
60
+ enabled: rand() < 0.5,
61
+ candidate: { head: SHA, parent: 'b'.repeat(40), cycle: 'cycle' },
62
+ decisionSeq: 1,
63
+ commandSeq: 2,
64
+ operation: 'rewrite-1',
65
+ }),
43
66
  () => w('runner.attached', { instance: 'runner-1', host: 'local' }),
44
67
  () => w('spec.imported', { artifact: ART('spec', 0), ticket: { source: 'linear', id: 'E-1' } }),
45
68
  () => w('spec.revised', { artifact: ART('spec', round), escalation: 1 }),