@defrex/autobuild 1.6.0 → 1.8.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 (165) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +423 -57
  3. package/docs/agent-runtimes.md +1 -1
  4. package/docs/answering-blocked-builds.md +44 -3
  5. package/docs/architecture.md +124 -29
  6. package/docs/cli.md +1 -0
  7. package/docs/configuration-overview.md +11 -1
  8. package/docs/configuration.md +334 -14
  9. package/docs/dispatcher.md +1 -1
  10. package/docs/forges.md +1 -0
  11. package/docs/integration-overview.md +2 -2
  12. package/docs/integration-tree.md +7 -4
  13. package/docs/merge-policy.md +78 -6
  14. package/docs/migration-1.0.md +4 -2
  15. package/docs/operating.md +3 -2
  16. package/docs/operator-api.md +45 -13
  17. package/docs/operator-surfaces.md +16 -3
  18. package/docs/plugin-authoring.md +45 -7
  19. package/docs/remote-store-protocol.md +28 -7
  20. package/docs/restacking.md +35 -11
  21. package/docs/ticket-dependencies.md +9 -4
  22. package/docs/ticket-sources.md +34 -6
  23. package/docs/tickets.md +7 -1
  24. package/docs/troubleshooting.md +1 -1
  25. package/docs/workspaces.md +1 -1
  26. package/package.json +3 -3
  27. package/packages/core/src/cli/attention.ts +2 -0
  28. package/packages/core/src/cli/binary-direct.ts +1 -0
  29. package/packages/core/src/cli/build-control.ts +65 -7
  30. package/packages/core/src/cli/context.ts +55 -14
  31. package/packages/core/src/cli/dashboard/actions.ts +13 -4
  32. package/packages/core/src/cli/dashboard/landing-display.ts +32 -8
  33. package/packages/core/src/cli/dashboard/model.ts +61 -8
  34. package/packages/core/src/cli/dashboard/render.ts +28 -3
  35. package/packages/core/src/cli/dashboard/tree.ts +9 -1
  36. package/packages/core/src/cli/dispatch-frontend.ts +10 -14
  37. package/packages/core/src/cli/dispatch-preflight.ts +1 -0
  38. package/packages/core/src/cli/dispatch-repository-feed.ts +145 -109
  39. package/packages/core/src/cli/dispatch.ts +9 -3
  40. package/packages/core/src/cli/help.ts +80 -11
  41. package/packages/core/src/cli/init-validation.ts +14 -1
  42. package/packages/core/src/cli/landings.ts +1 -1
  43. package/packages/core/src/cli/main.ts +60 -9
  44. package/packages/core/src/cli/publication-settlement.ts +10 -0
  45. package/packages/core/src/cli/repository-status.ts +37 -2
  46. package/packages/core/src/cli/status.ts +186 -12
  47. package/packages/core/src/cli/terminals.ts +197 -4
  48. package/packages/core/src/cli/ticket.ts +22 -4
  49. package/packages/core/src/cli/wait.ts +1 -0
  50. package/packages/core/src/cli/watch.ts +73 -0
  51. package/packages/core/src/config/landing.ts +12 -0
  52. package/packages/core/src/config/live.ts +4 -0
  53. package/packages/core/src/config/path-selectors.ts +68 -0
  54. package/packages/core/src/config/profiles.ts +96 -0
  55. package/packages/core/src/config/ready-assignee.ts +43 -11
  56. package/packages/core/src/config/roles.ts +33 -10
  57. package/packages/core/src/config/schema.ts +205 -81
  58. package/packages/core/src/events/catalog.ts +17 -3
  59. package/packages/core/src/events/compatibility.ts +4 -1
  60. package/packages/core/src/events/forge-degradation-policy.ts +16 -2
  61. package/packages/core/src/events/head-paths-limits.ts +25 -0
  62. package/packages/core/src/events/payloads.ts +323 -20
  63. package/packages/core/src/events/policy.ts +22 -0
  64. package/packages/core/src/events/repository.ts +47 -1
  65. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +320 -130
  66. package/packages/core/src/kernel/build-creation.ts +29 -0
  67. package/packages/core/src/kernel/consent-revocation.ts +72 -0
  68. package/packages/core/src/kernel/dispatch-capacity.ts +19 -8
  69. package/packages/core/src/kernel/engine.ts +48 -8
  70. package/packages/core/src/kernel/forge-health.ts +47 -0
  71. package/packages/core/src/kernel/guarded-forge.ts +76 -18
  72. package/packages/core/src/kernel/head-paths-state.ts +63 -0
  73. package/packages/core/src/kernel/head-paths.ts +401 -0
  74. package/packages/core/src/kernel/landing-policy-identity.ts +20 -0
  75. package/packages/core/src/kernel/landing-policy.ts +55 -2
  76. package/packages/core/src/kernel/landing-readiness.ts +104 -9
  77. package/packages/core/src/kernel/landing-state.ts +44 -4
  78. package/packages/core/src/kernel/leaf-restack-state.ts +50 -2
  79. package/packages/core/src/kernel/log-index.ts +27 -1
  80. package/packages/core/src/kernel/node-parent.ts +2 -0
  81. package/packages/core/src/kernel/node-polling.ts +13 -3
  82. package/packages/core/src/kernel/node-restack-state.ts +8 -1
  83. package/packages/core/src/kernel/node-restack-transaction.ts +45 -0
  84. package/packages/core/src/kernel/read-deferrals.ts +3 -1
  85. package/packages/core/src/kernel/read-facts.ts +37 -2
  86. package/packages/core/src/kernel/reducer-registry.ts +22 -1
  87. package/packages/core/src/kernel/reducer.ts +332 -16
  88. package/packages/core/src/kernel/target-observation.ts +2 -5
  89. package/packages/core/src/kernel/terminal-guard.ts +52 -3
  90. package/packages/core/src/kernel/ticket-handbacks.ts +40 -0
  91. package/packages/core/src/kernel/ticket-preparation.ts +15 -1
  92. package/packages/core/src/kernel/ticket-wait.ts +345 -0
  93. package/packages/core/src/kernel/verify-applicability.ts +9 -19
  94. package/packages/core/src/ontology.ts +1 -0
  95. package/packages/core/src/operator/annotations.ts +6 -0
  96. package/packages/core/src/operator/index.ts +3 -0
  97. package/packages/core/src/operator/protocol.ts +25 -2
  98. package/packages/core/src/operator/query.ts +1 -1
  99. package/packages/core/src/operator/registry.ts +122 -10
  100. package/packages/core/src/operator/repository-events.ts +67 -0
  101. package/packages/core/src/operator/sandbox-host.ts +3 -0
  102. package/packages/core/src/operator/tickets.ts +15 -3
  103. package/packages/core/src/plugin-sdk/index.ts +4 -0
  104. package/packages/core/src/ports/forge/create.ts +6 -0
  105. package/packages/core/src/ports/forge/github-transport.ts +40 -3
  106. package/packages/core/src/ports/forge/github.ts +12 -1
  107. package/packages/core/src/ports/forge/workspace-ancestry.ts +60 -0
  108. package/packages/core/src/ports/forge-failure.ts +31 -2
  109. package/packages/core/src/ports/runner/routing.ts +66 -5
  110. package/packages/core/src/ports/tickets/assignees.ts +54 -0
  111. package/packages/core/src/ports/tickets/contract.ts +164 -4
  112. package/packages/core/src/ports/tickets/create.ts +17 -3
  113. package/packages/core/src/ports/tickets/fake.ts +5 -0
  114. package/packages/core/src/ports/tickets/github-fake.ts +18 -2
  115. package/packages/core/src/ports/tickets/github.ts +247 -29
  116. package/packages/core/src/ports/tickets/hosted-index.ts +1 -0
  117. package/packages/core/src/ports/tickets/operations.ts +6 -1
  118. package/packages/core/src/ports/tickets/tree.ts +12 -2
  119. package/packages/core/src/ports/tickets/update.ts +6 -2
  120. package/packages/core/src/ports/types.ts +36 -5
  121. package/packages/core/src/ports/workspace/vercel-sandbox.ts +9 -0
  122. package/packages/core/src/processes/build-child.ts +28 -7
  123. package/packages/core/src/processes/build-execution-state.ts +34 -2
  124. package/packages/core/src/processes/build-runner.ts +165 -19
  125. package/packages/core/src/processes/dispatcher.ts +837 -115
  126. package/packages/core/src/processes/execution-no-progress.ts +22 -2
  127. package/packages/core/src/processes/harvest-child.ts +4 -0
  128. package/packages/core/src/processes/harvest-runner.ts +5 -0
  129. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  130. package/packages/core/src/processes/publication-state.ts +6 -1
  131. package/packages/core/src/processes/repo-view.ts +2 -0
  132. package/packages/core/src/scenarios/harness.ts +15 -1
  133. package/packages/core/src/store/digest.ts +41 -2
  134. package/packages/core/src/store/reduced-reads.ts +4 -1
  135. package/packages/core/src/store/reducer-value-shapes.json +10310 -8441
  136. package/packages/core/src/store/remote/client.ts +49 -10
  137. package/packages/core/src/store/remote/index.ts +4 -0
  138. package/packages/core/src/store/remote/protocol.ts +18 -1
  139. package/packages/core/src/store/remote/released-clients.json +22 -0
  140. package/packages/core/src/store/remote/released-reducer-values/1.7.0.json +27366 -0
  141. package/packages/core/src/store/remote/released-reducer-values/1.8.0.json +29043 -0
  142. package/packages/core/src/store/remote/released-reducer-values/index.ts +4 -0
  143. package/packages/core/src/store/repo-state-events.ts +3 -0
  144. package/packages/core/src/store/types.ts +27 -0
  145. package/packages/core/src/testing/dispatch-read-budget.ts +84 -58
  146. package/packages/core/src/testing/index.ts +2 -0
  147. package/packages/core/src/testing/reduced-read-budget.ts +419 -9
  148. package/skills/code-review/SKILL.md +8 -0
  149. package/skills/finalize/SKILL.md +4 -0
  150. package/skills/guide/SKILL.md +241 -47
  151. package/skills/guide/references/integration-tree.md +7 -4
  152. package/skills/guide/references/merge-policy.md +78 -6
  153. package/skills/guide/references/migration-1.0.md +4 -2
  154. package/skills/guide/references/operator-api.md +45 -13
  155. package/skills/guide/references/plugin-authoring.md +45 -7
  156. package/skills/guide/references/remote-store-protocol.md +28 -7
  157. package/skills/guide/references/restacking.md +35 -11
  158. package/skills/guide/references/ticket-dependencies.md +9 -4
  159. package/skills/implement/SKILL.md +15 -1
  160. package/skills/operate/SKILL.md +133 -16
  161. package/skills/plan/SKILL.md +17 -2
  162. package/skills/plan-review/SKILL.md +8 -0
  163. package/skills/reconcile/SKILL.md +21 -5
  164. package/skills/tickets/SKILL.md +23 -6
  165. package/templates/hosted-service/package.json +2 -2
@@ -0,0 +1,401 @@
1
+ /**
2
+ * The paths each candidate head changes (SPEC §15 "Head path facts").
3
+ *
4
+ * The build that produces a candidate head records it once, before the write
5
+ * that establishes the head: a `head.paths-recorded` event carrying a bounded
6
+ * summary, deposited atomically with a `head-paths` artifact holding the
7
+ * complete sets. Build state folds the summaries; the selectors here answer
8
+ * "what does the current candidate head change" without git or store reads,
9
+ * so the dispatcher's per-poll path never pays for the fact. `readHeadPaths`
10
+ * is the explicit, once-per-candidate read of the complete sets.
11
+ */
12
+ import { randomUUID } from 'node:crypto'
13
+ import { tmpdir } from 'node:os'
14
+ import { join } from 'node:path'
15
+ import { z } from 'zod'
16
+ import type { Actor } from '../events/envelope'
17
+ import type { EventEnvelope, EventWrite } from '../events/catalog'
18
+ import {
19
+ HEAD_PATHS_ARTIFACT,
20
+ HEAD_PATHS_PREVIEW,
21
+ HEAD_PATHS_RECORDS,
22
+ } from '../events/head-paths-limits'
23
+ import { headPathsFor, type HeadPathsSource, type HeadPathsSummary } from './head-paths-state'
24
+ import type { Exec } from '../ports/workspace/git-worktree'
25
+ import { readBuildFacts, readBuildSelector } from '../store/reduced-reads'
26
+ import type { LeafRestackState } from './leaf-restack-state'
27
+ import type { ArtifactInput, ArtifactMeta, BuildStore } from '../store/types'
28
+ import type { BuildState } from './reducer'
29
+
30
+ export { HEAD_PATHS_ARTIFACT, HEAD_PATHS_PREVIEW, HEAD_PATHS_RECORDS }
31
+
32
+ export {
33
+ candidateHead,
34
+ candidateHeadPaths,
35
+ foldHeadPaths,
36
+ headPathsFor,
37
+ type HeadPathsAnswer,
38
+ type HeadPathsPayload,
39
+ type HeadPathsSource,
40
+ type HeadPathsSummary,
41
+ } from './head-paths-state'
42
+
43
+ // ── Complete sets (artifact) ─────────────────────────────────────────────────
44
+
45
+ const pathList = z.array(z.string().min(1))
46
+ export const headPathsArtifactSchema = z.strictObject({
47
+ version: z.literal(1),
48
+ head: z.string().min(1),
49
+ destination: z.string().min(1),
50
+ mergeBase: z.string().min(1),
51
+ paths: pathList,
52
+ resolution: z.strictObject({ paths: pathList }).optional(),
53
+ })
54
+ export type HeadPathsArtifact = z.infer<typeof headPathsArtifactSchema>
55
+
56
+ export class HeadPathsReadError extends Error {
57
+ override readonly name = 'HeadPathsReadError'
58
+ }
59
+
60
+ function matchesSummary(
61
+ paths: readonly string[],
62
+ summary: { total: number; preview: readonly string[] },
63
+ ): boolean {
64
+ return (
65
+ paths.length === summary.total && summary.preview.every((path, index) => paths[index] === path)
66
+ )
67
+ }
68
+
69
+ /** The complete path sets behind one recorded summary: one artifact read. A
70
+ * missing or mismatched artifact is a typed error, never a recomputation. */
71
+ export async function readHeadPaths(
72
+ store: Pick<BuildStore, 'getArtifact'>,
73
+ slug: string,
74
+ record: HeadPathsSummary,
75
+ ): Promise<{ paths: string[]; resolution?: { paths: string[] } }> {
76
+ const where = `${HEAD_PATHS_ARTIFACT}@${record.artifact.rev} for head ${record.head}`
77
+ const artifact = await store.getArtifact(slug, HEAD_PATHS_ARTIFACT, record.artifact.rev)
78
+ if (artifact === null) throw new HeadPathsReadError(`${where} is missing`)
79
+ let content: HeadPathsArtifact
80
+ try {
81
+ content = headPathsArtifactSchema.parse(JSON.parse(new TextDecoder().decode(artifact.content)))
82
+ } catch (error) {
83
+ throw new HeadPathsReadError(
84
+ `${where} is malformed: ${error instanceof Error ? error.message : String(error)}`,
85
+ )
86
+ }
87
+ if (
88
+ content.head !== record.head ||
89
+ content.destination !== record.destination ||
90
+ content.mergeBase !== record.mergeBase ||
91
+ !matchesSummary(content.paths, record) ||
92
+ (content.resolution === undefined) !== (record.resolution === undefined) ||
93
+ (content.resolution !== undefined &&
94
+ !matchesSummary(content.resolution.paths, record.resolution!))
95
+ )
96
+ throw new HeadPathsReadError(`${where} does not match its recorded summary`)
97
+ return {
98
+ paths: content.paths,
99
+ ...(content.resolution === undefined
100
+ ? {}
101
+ : { resolution: { paths: content.resolution.paths } }),
102
+ }
103
+ }
104
+
105
+ // ── Git computation ──────────────────────────────────────────────────────────
106
+
107
+ /** Parse `git diff --name-only -z`; malformed output fails closed. */
108
+ export function parseNulChangedPaths(output: string): string[] {
109
+ if (output.length === 0) return []
110
+ if (!output.endsWith('\0')) {
111
+ throw new Error('git diff --name-only -z returned non-NUL-terminated output')
112
+ }
113
+ const paths = output.slice(0, -1).split('\0')
114
+ if (paths.some((path) => path.length === 0)) {
115
+ throw new Error('git diff --name-only -z returned an empty path entry')
116
+ }
117
+ return paths
118
+ }
119
+
120
+ function sortedUnique(paths: Iterable<string>): string[] {
121
+ return [...new Set(paths)].sort()
122
+ }
123
+
124
+ async function run(exec: Exec, cwd: string, args: string[]) {
125
+ return exec(['git', ...args], { cwd })
126
+ }
127
+
128
+ async function gitOut(exec: Exec, cwd: string, args: string[]): Promise<string> {
129
+ const result = await run(exec, cwd, args)
130
+ if (result.exitCode !== 0)
131
+ throw new Error(
132
+ `git ${args.join(' ')} exited ${result.exitCode}: ` +
133
+ `${result.stderr.trim() || result.stdout.trim() || '(no output)'}`,
134
+ )
135
+ return result.stdout
136
+ }
137
+
138
+ /** Every path that differs between two tree-ish values. `--no-renames` lists
139
+ * a rename as its deletion and its addition, so both paths count. */
140
+ async function diffPaths(exec: Exec, cwd: string, from: string, to: string): Promise<string[]> {
141
+ return sortedUnique(
142
+ parseNulChangedPaths(
143
+ await gitOut(exec, cwd, ['diff', '--no-renames', '--name-only', '-z', from, to, '--']),
144
+ ),
145
+ )
146
+ }
147
+
148
+ /** The paths `head` changes against its merge base with `destination`. */
149
+ export async function computeChangedPaths(
150
+ exec: Exec,
151
+ cwd: string,
152
+ input: { head: string; destination: string },
153
+ ): Promise<{ mergeBase: string; paths: string[] }> {
154
+ for (const commit of [input.head, input.destination])
155
+ await gitOut(exec, cwd, ['cat-file', '-e', `${commit}^{commit}`])
156
+ const base = await run(exec, cwd, ['merge-base', input.destination, input.head])
157
+ if (base.exitCode !== 0 || base.stdout.trim() === '')
158
+ throw new Error(
159
+ `head ${input.head} has no merge base with destination ${input.destination}` +
160
+ (base.stderr.trim() ? `: ${base.stderr.trim()}` : ''),
161
+ )
162
+ const mergeBase = base.stdout.trim().split('\n')[0]!
163
+ return { mergeBase, paths: await diffPaths(exec, cwd, mergeBase, input.head) }
164
+ }
165
+
166
+ /** One replayed change: `change` replayed onto `onto` as a three-way merge
167
+ * with base `parent` (the change's mainline parent), resolved into `head`. */
168
+ export interface ResolutionInput {
169
+ change: string
170
+ parent: string
171
+ mainline?: number
172
+ onto: string
173
+ head: string
174
+ }
175
+
176
+ function unsupportedMergeTree(result: { exitCode: number; stderr: string }): boolean {
177
+ return (
178
+ result.exitCode === 129 ||
179
+ /usage: git merge-tree|unknown option|unrecognized argument/i.test(result.stderr)
180
+ )
181
+ }
182
+
183
+ /**
184
+ * The tree of the purely mechanical replay of `change` onto `onto`, conflict
185
+ * markers included. `git merge-tree --write-tree --merge-base` computes it
186
+ * without touching any worktree; older Git rebuilds the identical three-way
187
+ * merge in a temporary detached worktree, leaving the caller's untouched.
188
+ */
189
+ export async function mechanicalTree(
190
+ exec: Exec,
191
+ cwd: string,
192
+ input: Omit<ResolutionInput, 'head'>,
193
+ opts: { mergeBaseOption?: boolean } = {},
194
+ ): Promise<string> {
195
+ const parent = (
196
+ await gitOut(exec, cwd, ['rev-parse', '--verify', `${input.parent}^{commit}`])
197
+ ).trim()
198
+ if (opts.mergeBaseOption !== false) {
199
+ const result = await run(exec, cwd, [
200
+ 'merge-tree',
201
+ '--write-tree',
202
+ '--no-messages',
203
+ `--merge-base=${parent}`,
204
+ input.onto,
205
+ input.change,
206
+ ])
207
+ if (result.exitCode === 0 || result.exitCode === 1) {
208
+ const tree = result.stdout.split('\n')[0]?.trim() ?? ''
209
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(tree))
210
+ throw new Error(`git merge-tree returned no tree: ${JSON.stringify(result.stdout)}`)
211
+ return tree
212
+ }
213
+ if (!unsupportedMergeTree(result))
214
+ throw new Error(`git merge-tree exited ${result.exitCode}: ${result.stderr.trim()}`)
215
+ }
216
+ return worktreeReplayTree(exec, cwd, input)
217
+ }
218
+
219
+ async function worktreeReplayTree(
220
+ exec: Exec,
221
+ cwd: string,
222
+ input: Omit<ResolutionInput, 'head' | 'parent'>,
223
+ ): Promise<string> {
224
+ const path = join(tmpdir(), `autobuild-head-paths-${randomUUID()}`)
225
+ await gitOut(exec, cwd, ['worktree', 'add', '--detach', path, input.onto])
226
+ try {
227
+ const picked = await run(exec, path, [
228
+ '-c',
229
+ 'core.hooksPath=/dev/null',
230
+ 'cherry-pick',
231
+ '--no-commit',
232
+ ...(input.mainline === undefined ? [] : ['-m', String(input.mainline)]),
233
+ input.change,
234
+ ])
235
+ if (picked.exitCode !== 0) {
236
+ const unmerged = await gitOut(exec, path, ['diff', '--name-only', '--diff-filter=U', '-z'])
237
+ if (unmerged === '')
238
+ throw new Error(
239
+ `mechanical replay of ${input.change} failed: ${picked.stderr.trim() || picked.stdout.trim()}`,
240
+ )
241
+ }
242
+ await gitOut(exec, path, ['add', '-A'])
243
+ return (await gitOut(exec, path, ['write-tree'])).trim()
244
+ } finally {
245
+ await run(exec, cwd, ['worktree', 'remove', '--force', path])
246
+ await run(exec, cwd, ['worktree', 'prune'])
247
+ }
248
+ }
249
+
250
+ /** The union of the paths each resolved head edits beyond its mechanical
251
+ * replay. Changes that arrived cleanly from the destination do not count. */
252
+ export async function computeResolutionPaths(
253
+ exec: Exec,
254
+ cwd: string,
255
+ items: readonly ResolutionInput[],
256
+ opts: { mergeBaseOption?: boolean } = {},
257
+ ): Promise<string[]> {
258
+ const paths: string[] = []
259
+ for (const item of items)
260
+ paths.push(
261
+ ...(await diffPaths(exec, cwd, await mechanicalTree(exec, cwd, item, opts), item.head)),
262
+ )
263
+ return sortedUnique(paths)
264
+ }
265
+
266
+ /** The base a leaf's landing candidate is judged against, exactly as
267
+ * `leafLandingCandidate` defines it; the contribution base before any. */
268
+ export async function leafLandingBase(
269
+ store: BuildStore,
270
+ slug: string,
271
+ restack: Pick<LeafRestackState, 'completed' | 'initialBase'>,
272
+ ): Promise<string> {
273
+ const base =
274
+ restack.completed?.targetBase ??
275
+ restack.initialBase ??
276
+ (await readBuildSelector(store, slug, 'verifyDiffBase'))
277
+ if (base === undefined)
278
+ throw new Error("cannot record the head's changed paths: this build has no landing base")
279
+ return base
280
+ }
281
+
282
+ // ── Recording ────────────────────────────────────────────────────────────────
283
+
284
+ export interface HeadPathsInput {
285
+ source: HeadPathsSource
286
+ head: string
287
+ destination: string
288
+ /** Reconcile-produced heads only. An empty list records an empty resolution;
289
+ * undefined records none. */
290
+ resolution?: readonly ResolutionInput[]
291
+ }
292
+
293
+ /** Compute the complete facts for one head. */
294
+ export async function computeHeadPaths(
295
+ exec: Exec,
296
+ cwd: string,
297
+ input: HeadPathsInput,
298
+ opts: { mergeBaseOption?: boolean } = {},
299
+ ): Promise<HeadPathsArtifact> {
300
+ const { mergeBase, paths } = await computeChangedPaths(exec, cwd, input)
301
+ return {
302
+ version: 1,
303
+ head: input.head,
304
+ destination: input.destination,
305
+ mergeBase,
306
+ paths,
307
+ ...(input.resolution === undefined
308
+ ? {}
309
+ : { resolution: { paths: await computeResolutionPaths(exec, cwd, input.resolution, opts) } }),
310
+ }
311
+ }
312
+
313
+ function summary(paths: readonly string[]) {
314
+ return { total: paths.length, preview: paths.slice(0, HEAD_PATHS_PREVIEW) }
315
+ }
316
+
317
+ /** The atomic deposit for computed facts: the complete artifact and the
318
+ * event carrying its bounded summary. */
319
+ export function headPathsWrite(
320
+ facts: HeadPathsArtifact,
321
+ source: HeadPathsSource,
322
+ actor: Actor,
323
+ ): {
324
+ artifacts: ArtifactInput[]
325
+ makeEvent: (deposited: ArtifactMeta[]) => EventWrite<'head.paths-recorded'>
326
+ } {
327
+ return {
328
+ artifacts: [{ kind: HEAD_PATHS_ARTIFACT, content: JSON.stringify(facts) }],
329
+ makeEvent: (deposited) => ({
330
+ actor,
331
+ type: 'head.paths-recorded',
332
+ payload: {
333
+ source,
334
+ head: facts.head,
335
+ destination: facts.destination,
336
+ mergeBase: facts.mergeBase,
337
+ ...summary(facts.paths),
338
+ ...(facts.resolution === undefined ? {} : { resolution: summary(facts.resolution.paths) }),
339
+ artifact: { kind: HEAD_PATHS_ARTIFACT, rev: deposited[0]!.revision },
340
+ },
341
+ }),
342
+ }
343
+ }
344
+
345
+ export type HeadPathsDeposit = (
346
+ artifacts: ArtifactInput[],
347
+ makeEvent: (deposited: ArtifactMeta[]) => EventWrite<'head.paths-recorded'>,
348
+ ) => Promise<{ event: EventEnvelope<'head.paths-recorded'> } | null>
349
+
350
+ export interface RecordHeadPathsDeps {
351
+ store: BuildStore
352
+ slug: string
353
+ exec: Exec
354
+ workspacePath: string
355
+ actor: Actor
356
+ }
357
+
358
+ /**
359
+ * Record a produced head's paths once. Returns the existing summary when the
360
+ * head is already recorded, the new envelope on a deposit, or null when a
361
+ * conditional deposit (`expectedSeq`) missed. Git and deposit failures throw:
362
+ * a head is never published silently unrecorded.
363
+ */
364
+ export async function recordHeadPaths(
365
+ deps: RecordHeadPathsDeps,
366
+ input: HeadPathsInput & {
367
+ /** Build state to dedupe against; read when omitted. */
368
+ state?: Pick<BuildState, 'headPaths'>
369
+ expectedSeq?: number
370
+ deposit?: HeadPathsDeposit
371
+ mergeBaseOption?: boolean
372
+ },
373
+ ): Promise<
374
+ | { recorded: 'existing'; record: HeadPathsSummary }
375
+ | {
376
+ recorded: 'appended'
377
+ event: EventEnvelope<'head.paths-recorded'>
378
+ /** The complete sets just deposited, so callers never re-read them. */
379
+ facts: HeadPathsArtifact
380
+ }
381
+ | null
382
+ > {
383
+ const state = input.state ?? (await readBuildFacts(deps.store, deps.slug)).value.state
384
+ const existing = headPathsFor(state, input.head)
385
+ if (existing.recorded) return { recorded: 'existing', record: existing.record }
386
+ const facts = await computeHeadPaths(deps.exec, deps.workspacePath, input, {
387
+ ...(input.mergeBaseOption === undefined ? {} : { mergeBaseOption: input.mergeBaseOption }),
388
+ })
389
+ const { artifacts, makeEvent } = headPathsWrite(facts, input.source, deps.actor)
390
+ const deposit: HeadPathsDeposit =
391
+ input.deposit ??
392
+ ((items, make) =>
393
+ input.expectedSeq === undefined
394
+ ? deps.store.appendWithArtifacts(deps.slug, items, make)
395
+ : deps.store.appendWithArtifactsIfCurrent(deps.slug, input.expectedSeq, items, make))
396
+ const deposited = await deposit(artifacts, makeEvent)
397
+ return deposited === null ? null : { recorded: 'appended', event: deposited.event, facts }
398
+ }
399
+
400
+ /** A non-null `recordHeadPaths` result. */
401
+ export type RecordedHeadPaths = NonNullable<Awaited<ReturnType<typeof recordHeadPaths>>>
@@ -0,0 +1,20 @@
1
+ import { createHash } from 'node:crypto'
2
+ import type { LandingRule } from '../config/schema'
3
+
4
+ function canonical(value: unknown): string {
5
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
6
+ if (value !== null && typeof value === 'object')
7
+ return `{${Object.entries(value)
8
+ .filter(([, v]) => v !== undefined)
9
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
10
+ .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)
11
+ .join(',')}}`
12
+ return JSON.stringify(value) ?? 'null'
13
+ }
14
+
15
+ /** A stable identity of the evaluated `[[merge]]` rules, independent of key
16
+ * order: a recorded landing deferral holds only while the policy is unchanged.
17
+ * Kept out of `landing-policy.ts`, which the web dashboard bundles. */
18
+ export function landingPolicyIdentity(rules: readonly LandingRule[]): string {
19
+ return `sha256:${createHash('sha256').update(canonical(rules)).digest('hex')}`
20
+ }
@@ -1,4 +1,6 @@
1
1
  import type { LandingRule } from '../config/schema'
2
+ import { compilePathSelectors } from '../config/path-selectors'
3
+ import { LANDING_MATCHED_PATHS_PREVIEW } from '../events/head-paths-limits'
2
4
 
3
5
  /** The frozen destination identity, never the source ticket's mutable parent. */
4
6
  export type LandingTarget = { kind: 'root' } | { kind: 'node'; ticket: string }
@@ -7,16 +9,40 @@ export interface LandingPolicyInput {
7
9
  into: LandingTarget
8
10
  labels: readonly string[]
9
11
  }
12
+ /**
13
+ * The candidate head's recorded changed paths. "Not recorded" is distinct from
14
+ * a recorded empty change. `complete: false` means only a bounded preview is
15
+ * known; the caller reads the complete set and evaluates again.
16
+ */
17
+ export type LandingPaths =
18
+ | { recorded: false }
19
+ | { recorded: true; complete: boolean; paths: readonly string[] }
10
20
  export interface LandingPolicyMatch {
11
21
  mode: 'auto' | 'consent'
12
22
  /** Zero-based position and complete rule as sampled at readiness. */
13
23
  rule: { index: number; snapshot: LandingRule } | { default: true }
24
+ /** Present only when the matched rule has a path predicate: the changed
25
+ * paths its selectors matched, sorted, bounded, with the exact total. */
26
+ paths?: { total: number; preview: string[] }
27
+ }
28
+ /** Evaluation reached a path-predicate rule it cannot decide yet. */
29
+ export interface LandingPolicyDeferral {
30
+ deferred: 'paths-unrecorded' | 'paths-incomplete'
31
+ rule: { index: number; snapshot: LandingRule }
14
32
  }
15
33
 
34
+ /**
35
+ * First match wins. `from`, `label` and `into` are checked before any path
36
+ * predicate, so a rule whose other predicates fail never defers. A rule with
37
+ * `paths` (any changed path matches) or `within` (at least one changed path,
38
+ * and every one matches) needs the candidate's complete recorded paths:
39
+ * unrecorded paths defer the decision rather than read as an empty change.
40
+ */
16
41
  export function evaluateLandingPolicy(
17
42
  rules: readonly LandingRule[],
18
43
  input: LandingPolicyInput,
19
- ): LandingPolicyMatch {
44
+ changed: LandingPaths = { recorded: false },
45
+ ): LandingPolicyMatch | LandingPolicyDeferral {
20
46
  for (const [index, rule] of rules.entries()) {
21
47
  if (rule.from !== undefined && rule.from !== input.from) continue
22
48
  if (rule.label !== undefined && !input.labels.includes(rule.label)) continue
@@ -27,7 +53,21 @@ export function evaluateLandingPolicy(
27
53
  if (input.into.kind !== 'node') continue
28
54
  } else if (input.into.kind !== 'node' || rule.into !== input.into.ticket) continue
29
55
  }
30
- return { mode: rule.mode, rule: { index, snapshot: { ...rule } } }
56
+ const snapshot = { ...rule }
57
+ if (rule.paths === undefined && rule.within === undefined)
58
+ return { mode: rule.mode, rule: { index, snapshot } }
59
+ if (!changed.recorded) return { deferred: 'paths-unrecorded', rule: { index, snapshot } }
60
+ if (!changed.complete) return { deferred: 'paths-incomplete', rule: { index, snapshot } }
61
+ const matched = matchPathPredicates(rule, changed.paths)
62
+ if (matched === undefined) continue
63
+ return {
64
+ mode: rule.mode,
65
+ rule: { index, snapshot },
66
+ paths: {
67
+ total: matched.length,
68
+ preview: matched.slice(0, LANDING_MATCHED_PATHS_PREVIEW),
69
+ },
70
+ }
31
71
  }
32
72
  return {
33
73
  mode: input.from === 'leaf' ? 'auto' : 'consent',
@@ -35,6 +75,19 @@ export function evaluateLandingPolicy(
35
75
  }
36
76
  }
37
77
 
78
+ /** The sorted, unique changed paths any of the rule's selectors match, or
79
+ * undefined when its path predicates do not hold. */
80
+ function matchPathPredicates(rule: LandingRule, changed: readonly string[]): string[] | undefined {
81
+ const describe = (field: string) => (selector: string, error: string) =>
82
+ `invalid [[merge]] ${field} selector ${JSON.stringify(selector)}: ${error}`
83
+ const any = rule.paths && compilePathSelectors(rule.paths, describe('paths'))
84
+ const all = rule.within && compilePathSelectors(rule.within, describe('within'))
85
+ const unique = [...new Set(changed)].sort()
86
+ if (any && !unique.some(any)) return undefined
87
+ if (all && (unique.length === 0 || !unique.every(all))) return undefined
88
+ return unique.filter((path) => any?.(path) || all?.(path))
89
+ }
90
+
38
91
  /** Policy decisions and native application receipts bind to this exact
39
92
  * readiness candidate. Operator consent instead binds to the landing. */
40
93
  export interface LandingCandidate {
@@ -1,12 +1,112 @@
1
1
  import type { BuildState } from './reducer'
2
2
  import { discardInFlight } from './reducer'
3
3
  import type { LeafRestackState } from './leaf-restack-state'
4
+ import type { LandingCandidate } from './landing-policy'
5
+ import { sameLandingCandidate } from './landing-state'
6
+ import { escalationsBeyondJanitor } from './janitor-failure'
7
+ import { compatibilityDiagnostic, mixedVersionDeferred } from './mixed-version'
4
8
  import {
5
9
  integrationCurrent,
6
10
  integrationCycleVerified,
7
11
  integrationCycleCurrent,
8
12
  } from './integration-state'
9
13
 
14
+ /** Pending controls a runner or dispatcher will still act on. A resume acts
15
+ * only on a paused build: one that cancelled a never-acknowledged pause stays
16
+ * queued (a late `build.paused` must still be resumed) but holds nothing back. */
17
+ export function actionableCommands(
18
+ state: Pick<BuildState, 'pendingCommands' | 'status'>,
19
+ ): BuildState['pendingCommands'] {
20
+ return state.pendingCommands.filter(
21
+ (command) => command.command !== 'resume' || state.status === 'paused',
22
+ )
23
+ }
24
+
25
+ /** The candidate the dispatcher decides landing for on a leaf: its PR head on
26
+ * the restacked base (or the initial base), keyed by finalize completion. */
27
+ export function leafLandingCandidate(
28
+ state: Pick<BuildState, 'pr' | 'finalizeCompletedSeq'>,
29
+ restack: LeafRestackState,
30
+ ): LandingCandidate | undefined {
31
+ return (
32
+ state.pr && {
33
+ head: state.pr.headSha,
34
+ parent: restack.completed?.targetBase ?? restack.initialBase ?? '',
35
+ cycle: String(state.finalizeCompletedSeq),
36
+ }
37
+ )
38
+ }
39
+
40
+ /** Why the dispatcher will not decide landing for this leaf on state alone, or
41
+ * undefined. The engine decision (`wait awaiting-pr`) and the candidate base are
42
+ * checked separately by the caller. */
43
+ export function leafLandingDeclineReason(state: BuildState): string | undefined {
44
+ const session = state.sessions.open[0]
45
+ if (session) return `session ${session.session} (${session.phase}) is still open`
46
+ if (state.status === 'paused') return 'the build is paused'
47
+ if (state.status === 'done' || state.status === 'aborted') return `the build is ${state.status}`
48
+ if (escalationsBeyondJanitor(state).length) return 'the build has open escalations to answer'
49
+ const command = actionableCommands(state)[0]
50
+ if (command) return `a ${command.command} request awaits acknowledgement`
51
+ return undefined
52
+ }
53
+
54
+ /** Why the merge decision for `candidate` is deferred, from the recorded
55
+ * `landing.deferred` fact naming it, or undefined. */
56
+ export function landingDeferralReason(
57
+ state: Pick<BuildState, 'landing'>,
58
+ candidate: LandingCandidate | undefined,
59
+ ): string | undefined {
60
+ const deferral = state.landing?.deferral
61
+ if (!deferral || !sameLandingCandidate(deferral.candidate, candidate)) return undefined
62
+ return `deferred — [[merge]] rule merge[${deferral.rule.index}] matches on changed paths, but the changed paths of head ${deferral.candidate.head.slice(0, 12)} are not recorded; the decision waits for a head this build records (heads pushed outside a build are never recorded)`
63
+ }
64
+
65
+ /** Why an open-PR leaf parked at awaiting-pr has no landing decision for its
66
+ * current candidate, in the order the dispatcher's refusals apply: state
67
+ * guards, compatibility deferral, a failed janitor episode (any exception on
68
+ * the landing path, with its backoff), an unreadable build pipeline, a
69
+ * decision deferred for unrecorded changed paths, a missing candidate base,
70
+ * else that the decision is due at the next poll. */
71
+ export function leafLandingUndecidedReason(
72
+ state: BuildState,
73
+ restack: LeafRestackState,
74
+ pipelineUnreadable?: string,
75
+ ): string {
76
+ const declined = leafLandingDeclineReason(state)
77
+ if (declined) return declined
78
+ if (mixedVersionDeferred(state))
79
+ return `deferred for compatibility — ${compatibilityDiagnostic(state.compatibility)}`
80
+ if (state.janitor)
81
+ return `dispatcher janitor attempt ${state.janitor.attempt} failed — ${state.janitor.message}; next attempt ${state.janitor.nextAttemptAt}${state.janitor.escalation ? ' (escalated)' : ''}`
82
+ if (pipelineUnreadable)
83
+ return `the dispatcher cannot read this build's pipeline configuration (${pipelineUnreadable}); landing decisions are withheld until it is restored`
84
+ const deferred = landingDeferralReason(state, leafLandingCandidate(state, restack))
85
+ if (deferred) return deferred
86
+ if (!leafLandingCandidate(state, restack)?.parent)
87
+ return 'no base is recorded for the merge candidate'
88
+ return 'no refusal is recorded; the dispatcher decides at its next janitor poll (repository-wide forge deferrals appear in ab repository status)'
89
+ }
90
+
91
+ /** The live head of the merge candidate: a node's integration cycle head, a
92
+ * leaf's PR head. */
93
+ export function currentCandidateHead(
94
+ state: Pick<BuildState, 'kind' | 'pr' | 'integration'>,
95
+ ): string | undefined {
96
+ return state.kind === 'node' ? state.integration?.cycle?.head : state.pr?.headSha
97
+ }
98
+
99
+ /** Whether an operator-given head names the live candidate head: an exact
100
+ * match, or a hexadecimal prefix of at least seven characters (forge UIs show
101
+ * abbreviated SHAs). Case-insensitive. */
102
+ export function candidateHeadMatches(given: string, current: string | undefined): boolean {
103
+ if (current === undefined) return false
104
+ const head = given.toLowerCase()
105
+ const live = current.toLowerCase()
106
+ if (head === live) return true
107
+ return /^[0-9a-f]{7,}$/.test(head) && live.startsWith(head)
108
+ }
109
+
10
110
  /** The deterministic part of land's guard. Live completeness and CAS remain at the write boundary. */
11
111
  export function landPreconditions(state: BuildState, restack: LeafRestackState): boolean {
12
112
  return landRefusalReason(state, restack) === undefined
@@ -25,12 +125,9 @@ export function landRefusalReason(
25
125
  if (state.status === 'paused') return 'the build is paused'
26
126
  if (state.currentPhase) return `phase ${state.currentPhase} is still running`
27
127
  if (state.openEscalations.length) return 'the build has open escalations to answer'
28
- if (state.pendingCommands.length) return 'earlier controls are awaiting acknowledgement'
128
+ if (actionableCommands(state).length) return 'earlier controls are awaiting acknowledgement'
29
129
  if (state.prState !== 'open') return `the pull request is ${state.prState ?? 'not open'}`
30
- if (
31
- (state.kind === 'node' ? state.integration?.cycle?.head : state.pr?.headSha) !==
32
- decision.candidate.head
33
- )
130
+ if (currentCandidateHead(state) !== decision.candidate.head)
34
131
  return "the merge candidate's head is stale"
35
132
  if (state.kind !== 'node' && restack.target && restack.target.sha !== decision.candidate.parent)
36
133
  return "the merge candidate's base is stale"
@@ -67,10 +164,8 @@ export function landingReady(state: BuildState, restack: LeafRestackState): bool
67
164
  )
68
165
  )
69
166
  return false
70
- return (
71
- candidate.cycle === String(state.finalizeCompletedSeq) &&
72
- candidate.parent === (restack.completed?.targetBase ?? restack.initialBase ?? '')
73
- )
167
+ const current = leafLandingCandidate(state, restack)
168
+ return candidate.cycle === current?.cycle && candidate.parent === current.parent
74
169
  }
75
170
 
76
171
  export function awaitsConsent(state: BuildState, restack: LeafRestackState): boolean {