@defrex/autobuild 1.12.0 → 1.13.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 (159) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +435 -160
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +25 -3
  5. package/docs/architecture.md +124 -53
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +110 -15
  8. package/docs/dispatcher.md +19 -8
  9. package/docs/integration-overview.md +1 -1
  10. package/docs/integration-tree.md +12 -9
  11. package/docs/merge-policy.md +7 -2
  12. package/docs/operating.md +5 -3
  13. package/docs/operator-api.md +46 -23
  14. package/docs/operator-surfaces.md +7 -6
  15. package/docs/optimization-nodes.md +7 -6
  16. package/docs/plugin-authoring.md +46 -18
  17. package/docs/remote-store-protocol.md +51 -12
  18. package/docs/remote-ticket-protocol.md +85 -38
  19. package/docs/restacking.md +48 -3
  20. package/docs/setup.md +2 -1
  21. package/docs/ticket-migration.md +2 -2
  22. package/docs/ticket-sources.md +23 -8
  23. package/docs/tickets.md +4 -4
  24. package/docs/troubleshooting.md +17 -2
  25. package/docs/verification.md +3 -1
  26. package/package.json +3 -3
  27. package/packages/core/src/cli/build-control.ts +72 -6
  28. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  29. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  30. package/packages/core/src/cli/dashboard/model.ts +14 -8
  31. package/packages/core/src/cli/dashboard/poll.ts +218 -10
  32. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  33. package/packages/core/src/cli/dashboard/row-text.ts +2 -1
  34. package/packages/core/src/cli/dashboard/vocabulary.ts +5 -1
  35. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  36. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  37. package/packages/core/src/cli/dispatch.ts +527 -144
  38. package/packages/core/src/cli/help.ts +38 -24
  39. package/packages/core/src/cli/main.ts +7 -5
  40. package/packages/core/src/cli/publication-settlement.ts +4 -0
  41. package/packages/core/src/cli/remote-poll.ts +22 -5
  42. package/packages/core/src/cli/repository-status.ts +19 -9
  43. package/packages/core/src/cli/status.ts +23 -11
  44. package/packages/core/src/cli/store-opening.ts +12 -0
  45. package/packages/core/src/cli/ticket-start.ts +3 -3
  46. package/packages/core/src/cli/ticket.ts +12 -11
  47. package/packages/core/src/cli/wait.ts +8 -28
  48. package/packages/core/src/cli/watch.ts +113 -50
  49. package/packages/core/src/config/reference-metadata.ts +7 -1
  50. package/packages/core/src/config/reference.ts +5 -2
  51. package/packages/core/src/config/schema.ts +51 -16
  52. package/packages/core/src/events/payloads.ts +74 -14
  53. package/packages/core/src/events/repository.ts +14 -3
  54. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +27 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  61. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  62. package/packages/core/src/kernel/dispatch-capacity.ts +243 -107
  63. package/packages/core/src/kernel/done-escalations.ts +269 -0
  64. package/packages/core/src/kernel/engine.ts +28 -9
  65. package/packages/core/src/kernel/integration-landing.ts +24 -4
  66. package/packages/core/src/kernel/integration-stack.ts +39 -0
  67. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  68. package/packages/core/src/kernel/log-index-value.ts +3 -0
  69. package/packages/core/src/kernel/log-index.ts +41 -2
  70. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  71. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  72. package/packages/core/src/kernel/reducer-revisions.ts +15 -0
  73. package/packages/core/src/kernel/reducer.ts +27 -7
  74. package/packages/core/src/kernel/repository-attention.ts +14 -5
  75. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  76. package/packages/core/src/kernel/verify-stages.ts +46 -7
  77. package/packages/core/src/operator/attention.ts +28 -3
  78. package/packages/core/src/operator/done-escalations.ts +38 -0
  79. package/packages/core/src/operator/presentation.ts +1 -1
  80. package/packages/core/src/operator/protocol.ts +8 -5
  81. package/packages/core/src/operator/query.ts +33 -19
  82. package/packages/core/src/operator/registry.ts +17 -13
  83. package/packages/core/src/operator/ticket-start.ts +8 -7
  84. package/packages/core/src/operator/tickets.ts +28 -9
  85. package/packages/core/src/plugin-sdk/index.ts +10 -0
  86. package/packages/core/src/plugins/manifest.ts +14 -1
  87. package/packages/core/src/ports/forge/create.ts +8 -0
  88. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  89. package/packages/core/src/ports/forge/github.ts +3 -0
  90. package/packages/core/src/ports/tickets/contract.ts +147 -76
  91. package/packages/core/src/ports/tickets/create.ts +47 -7
  92. package/packages/core/src/ports/tickets/fake.ts +8 -4
  93. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  94. package/packages/core/src/ports/tickets/file.ts +7 -3
  95. package/packages/core/src/ports/tickets/github.ts +1 -0
  96. package/packages/core/src/ports/tickets/grants.ts +11 -3
  97. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  98. package/packages/core/src/ports/tickets/linear.ts +28 -9
  99. package/packages/core/src/ports/tickets/migration.ts +4 -4
  100. package/packages/core/src/ports/tickets/operations.ts +4 -2
  101. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  102. package/packages/core/src/ports/tickets/priority.ts +127 -21
  103. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  104. package/packages/core/src/ports/tickets/remote.ts +104 -11
  105. package/packages/core/src/ports/tickets/revision.ts +5 -3
  106. package/packages/core/src/ports/tickets/search.ts +9 -0
  107. package/packages/core/src/ports/tickets/tree.ts +8 -6
  108. package/packages/core/src/ports/types.ts +30 -15
  109. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  110. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  111. package/packages/core/src/ports/workspace/create.ts +16 -3
  112. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  113. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  114. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  115. package/packages/core/src/processes/build-execution-state.ts +4 -0
  116. package/packages/core/src/processes/build-runner.ts +14 -1
  117. package/packages/core/src/processes/dispatcher.ts +544 -212
  118. package/packages/core/src/processes/execution-settlement.ts +1 -0
  119. package/packages/core/src/processes/harvest-runner.ts +12 -7
  120. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  121. package/packages/core/src/processes/invocation-budget.ts +176 -0
  122. package/packages/core/src/processes/publication-loss.ts +38 -3
  123. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  124. package/packages/core/src/store/contract.ts +81 -3
  125. package/packages/core/src/store/event-reads.ts +30 -1
  126. package/packages/core/src/store/reduced-reads.ts +23 -0
  127. package/packages/core/src/store/reducer-value-shapes.json +6628 -6469
  128. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  129. package/packages/core/src/store/remote/client.ts +169 -29
  130. package/packages/core/src/store/remote/compatibility.ts +113 -56
  131. package/packages/core/src/store/remote/credentials.ts +4 -1
  132. package/packages/core/src/store/remote/protocol.ts +3 -0
  133. package/packages/core/src/store/remote/released-clients.json +11 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  135. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  136. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  137. package/packages/core/src/store/remote/retry.ts +406 -0
  138. package/packages/core/src/testing/dispatch-read-budget.ts +144 -10
  139. package/packages/core/src/testing/index.ts +2 -0
  140. package/packages/core/src/testing/invocation-budget.ts +42 -0
  141. package/packages/core/src/testing/reduced-read-budget.ts +381 -18
  142. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  143. package/packages/core/src/web/overview-source.ts +19 -6
  144. package/skills/guide/SKILL.md +138 -67
  145. package/skills/guide/references/integration-tree.md +12 -9
  146. package/skills/guide/references/merge-policy.md +7 -2
  147. package/skills/guide/references/operator-api.md +46 -23
  148. package/skills/guide/references/optimization-nodes.md +7 -6
  149. package/skills/guide/references/plugin-authoring.md +46 -18
  150. package/skills/guide/references/remote-store-protocol.md +51 -12
  151. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  152. package/skills/guide/references/restacking.md +48 -3
  153. package/skills/guide/references/setup.md +2 -1
  154. package/skills/guide/references/ticket-migration.md +2 -2
  155. package/skills/operate/SKILL.md +82 -51
  156. package/skills/plan/SKILL.md +4 -3
  157. package/skills/spec/SKILL.md +9 -5
  158. package/skills/tickets/SKILL.md +25 -17
  159. package/templates/hosted-service/package.json +2 -2
@@ -0,0 +1,269 @@
1
+ /**
2
+ * `doneEscalations`, a rollup (SPEC §7.7): every `done` build with an open
3
+ * escalation, the post-completion escalations operator surfaces list until an
4
+ * operator acknowledges them. Completion closes no escalation, so a build
5
+ * completed while blocked (abort cleanup included) is listed too.
6
+ *
7
+ * - `doneEscalationEntry` is the build-scope reducer it reads: the build's
8
+ * kind, its latest terminal fact and its open escalation ids.
9
+ * It mirrors
10
+ * exactly the build reducer's open-escalation rules (`kernel/reducer.ts`):
11
+ * raises, deferrals, janitor escalations and ticket waits open; answers,
12
+ * wait ends, janitor recovery, `wait-unresolvable` and verify supersession
13
+ * close. A tiny reducer of its own keeps the rollup's version independent of
14
+ * the build reducer's frequent revisions, so a `build` revision never
15
+ * re-reduces every finished build in every project.
16
+ * - The accumulator holds only the listed builds; nothing expires.
17
+ * - No key or read-time arguments: one key per repository.
18
+ *
19
+ * Surfaces confirm each listed build against its reduced state
20
+ * (`openOnDone`), so the rollup is a bounded index and row text always comes
21
+ * from the build reducer.
22
+ *
23
+ * Pure and browser-safe.
24
+ */
25
+ import { z } from 'zod'
26
+ import type { AbEvent } from '../events/catalog'
27
+ import { defineReducer } from './incremental'
28
+ import { reducerVersion } from './reducer-identity'
29
+ import type { RollupDefinition } from './rollup'
30
+ import { verifyMemberKey } from './verify-stage-state'
31
+
32
+ /** A `done` build with an open escalation: the one predicate every operator
33
+ * surface and the shared projection use. */
34
+ export function openOnDone(state: {
35
+ status: string
36
+ openEscalations: readonly unknown[]
37
+ }): boolean {
38
+ return state.status === 'done' && state.openEscalations.length > 0
39
+ }
40
+
41
+ export type DoneEscalationKind = 'work' | 'node'
42
+
43
+ /** One build's entry: `open` lists its open escalation ids in raise order,
44
+ * exactly the build reducer's `openEscalations` ids. */
45
+ export interface DoneEscalationEntry {
46
+ kind: DoneEscalationKind
47
+ terminal?: 'done' | 'aborted'
48
+ open: string[]
49
+ }
50
+
51
+ interface OpenEntry {
52
+ id: string
53
+ session?: string
54
+ janitor?: true
55
+ wait?: string
56
+ }
57
+
58
+ interface EntryAcc {
59
+ kind: DoneEscalationKind
60
+ terminal?: 'done' | 'aborted'
61
+ /** Insertion-ordered, like the reducer's map: a re-raise keeps its place. */
62
+ open: OpenEntry[]
63
+ /** The latest agent `wait.requested`, and whether it was answered. */
64
+ waitRequest?: { id: string; session: string; settled?: true }
65
+ /** The latest entered ticket wait. */
66
+ wait?: { id: string; escalation: string; ended?: true }
67
+ /** The verify-stage slice supersession reads (`advanceVerifyStage`). */
68
+ members: Record<string, true>
69
+ owners: Record<string, string>
70
+ completed: Record<string, true>
71
+ cancelled: Record<string, true>
72
+ }
73
+
74
+ function setOpen(acc: EntryAcc, entry: OpenEntry): void {
75
+ const at = acc.open.findIndex((open) => open.id === entry.id)
76
+ if (at >= 0) acc.open[at] = entry
77
+ else acc.open.push(entry)
78
+ }
79
+
80
+ function closeOpen(acc: EntryAcc, id: string): OpenEntry | undefined {
81
+ const at = acc.open.findIndex((open) => open.id === id)
82
+ if (at < 0) return undefined
83
+ return acc.open.splice(at, 1)[0]
84
+ }
85
+
86
+ function superseded(acc: EntryAcc, session: string | undefined): boolean {
87
+ const key = session === undefined ? undefined : acc.owners[session]
88
+ return key !== undefined && acc.cancelled[key] === true
89
+ }
90
+
91
+ /** The slice of `advanceVerifyStage` that decides verify supersession. */
92
+ function advanceVerify(acc: EntryAcc, event: AbEvent): void {
93
+ switch (event.type) {
94
+ case 'verify.started':
95
+ acc.members[verifyMemberKey(event.payload.step, event.payload.attempt)] = true
96
+ break
97
+ case 'session.started': {
98
+ const { phase, round, session } = event.payload
99
+ if (phase?.startsWith('verify:') && round !== undefined) {
100
+ const key = verifyMemberKey(phase.slice(7), round)
101
+ if (acc.members[key]) acc.owners[session] = key
102
+ }
103
+ break
104
+ }
105
+ case 'verify.completed': {
106
+ const key = verifyMemberKey(event.payload.step, event.payload.attempt)
107
+ if (!acc.cancelled[key]) acc.completed[key] = true
108
+ break
109
+ }
110
+ case 'verify.cancelled': {
111
+ const key = verifyMemberKey(event.payload.step, event.payload.attempt)
112
+ if (!acc.completed[key]) acc.cancelled[key] = true
113
+ break
114
+ }
115
+ }
116
+ }
117
+
118
+ export const doneEscalationEntryReducer = defineReducer<EntryAcc, AbEvent, DoneEscalationEntry>({
119
+ identity: 'doneEscalationEntry',
120
+ initial: () => ({
121
+ kind: 'work',
122
+ open: [],
123
+ members: {},
124
+ owners: {},
125
+ completed: {},
126
+ cancelled: {},
127
+ }),
128
+ fold(acc, events) {
129
+ for (const event of events) {
130
+ // The reducer's order: janitor recovery, then the verify stage and its
131
+ // supersession, then the event's own case.
132
+ if (event.type === 'build.janitor-recovered') acc.open = acc.open.filter((e) => !e.janitor)
133
+ advanceVerify(acc, event)
134
+ if (event.type === 'verify.cancelled')
135
+ acc.open = acc.open.filter((open) => !superseded(acc, open.session))
136
+ switch (event.type) {
137
+ case 'build.created':
138
+ acc.kind = event.payload.kind ?? 'work'
139
+ break
140
+ // Terminal, latest wins: an in-order overwrite, cleared by nothing.
141
+ case 'build.completed':
142
+ acc.terminal = 'done'
143
+ break
144
+ case 'build.aborted':
145
+ acc.terminal = 'aborted'
146
+ break
147
+ case 'phase.deferral-escalated':
148
+ setOpen(acc, { id: event.payload.id })
149
+ break
150
+ case 'wait.requested':
151
+ if (event.actor.kind !== 'agent') break
152
+ acc.waitRequest = { id: event.payload.id, session: event.actor.session }
153
+ break
154
+ case 'wait.refused':
155
+ if (acc.waitRequest?.id === event.payload.id && !acc.waitRequest.settled)
156
+ acc.waitRequest.settled = true
157
+ break
158
+ case 'wait.entered': {
159
+ const request = acc.waitRequest
160
+ if (request?.id !== event.payload.id || request.settled) break
161
+ request.settled = true
162
+ acc.wait = { id: request.id, escalation: event.payload.escalation }
163
+ setOpen(acc, { id: event.payload.escalation, session: request.session, wait: request.id })
164
+ break
165
+ }
166
+ case 'wait.ended': {
167
+ const wait = acc.wait
168
+ if (wait?.id !== event.payload.id || wait.ended) break
169
+ wait.ended = true
170
+ closeOpen(acc, wait.escalation)
171
+ break
172
+ }
173
+ case 'build.janitor-escalated':
174
+ if (!acc.open.some((open) => open.id === event.payload.id))
175
+ acc.open.push({ id: event.payload.id, janitor: true })
176
+ break
177
+ case 'escalation.raised': {
178
+ const entry: OpenEntry = {
179
+ id: event.payload.id,
180
+ ...(event.actor.kind === 'agent' ? { session: event.actor.session } : {}),
181
+ }
182
+ const wait = acc.wait
183
+ if (
184
+ event.payload.source === 'policy' &&
185
+ event.payload.policyCause === 'wait-unresolvable' &&
186
+ wait !== undefined &&
187
+ !wait.ended &&
188
+ acc.open.some((open) => open.id === wait.escalation)
189
+ ) {
190
+ wait.ended = true
191
+ closeOpen(acc, wait.escalation)
192
+ entry.wait = wait.id
193
+ }
194
+ if (!superseded(acc, entry.session)) setOpen(acc, entry)
195
+ break
196
+ }
197
+ case 'escalation.answered': {
198
+ const open = closeOpen(acc, event.payload.id)
199
+ if (open?.wait !== undefined && acc.wait?.id === open.wait) acc.wait.ended = true
200
+ break
201
+ }
202
+ }
203
+ }
204
+ },
205
+ finish: (acc) => ({
206
+ kind: acc.kind,
207
+ ...(acc.terminal !== undefined ? { terminal: acc.terminal } : {}),
208
+ open: acc.open.map((open) => open.id),
209
+ }),
210
+ })
211
+
212
+ const position = z.string().regex(/^(0|[1-9][0-9]*)$/)
213
+ const entrySchema = z.object({ slug: z.string().min(1), kind: z.enum(['work', 'node']) }).strict()
214
+ export type DoneEscalatedBuild = z.infer<typeof entrySchema>
215
+ export type DoneEscalationsContribution = DoneEscalatedBuild
216
+
217
+ const accSchema = z.object({ builds: z.record(z.string().min(1), entrySchema) }).strict()
218
+ export type DoneEscalationsAcc = z.infer<typeof accSchema>
219
+
220
+ const valueSchema = z.object({ position, builds: z.array(entrySchema) }).strict()
221
+ export interface DoneEscalationsValue {
222
+ /** The repository change position the answer reflects. */
223
+ position: string
224
+ /** Every `done` build with an open escalation, by slug. */
225
+ builds: DoneEscalatedBuild[]
226
+ }
227
+
228
+ const noArgs = z.object({}).strict()
229
+ type NoArgs = z.infer<typeof noArgs>
230
+
231
+ const order = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
232
+
233
+ export const doneEscalationsRollup: RollupDefinition<
234
+ NoArgs,
235
+ NoArgs,
236
+ DoneEscalationsAcc,
237
+ DoneEscalationsContribution,
238
+ DoneEscalationsValue
239
+ > = {
240
+ identity: 'doneEscalations',
241
+ version: reducerVersion('doneEscalations', [doneEscalationEntryReducer]),
242
+ buildReducer: 'doneEscalationEntry',
243
+ args: noArgs,
244
+ read: noArgs,
245
+ accSchema,
246
+ contributionSchema: entrySchema,
247
+ valueSchema,
248
+ initial: () => ({ builds: {} }),
249
+ contribute(value, _args, _now, slug) {
250
+ const entry = value as DoneEscalationEntry
251
+ return openOnDone({ status: entry.terminal ?? 'live', openEscalations: entry.open })
252
+ ? { slug, kind: entry.kind }
253
+ : null
254
+ },
255
+ add(acc, contribution) {
256
+ acc.builds[contribution.slug] = { ...contribution }
257
+ },
258
+ subtract(acc, contribution) {
259
+ delete acc.builds[contribution.slug]
260
+ },
261
+ expired: () => false,
262
+ prune: () => false,
263
+ finish: (acc, _read, _now, at) => ({
264
+ position: at,
265
+ builds: Object.values(acc.builds)
266
+ .map((entry) => ({ ...entry }))
267
+ .sort((a, b) => order(a.slug, b.slug)),
268
+ }),
269
+ }
@@ -1,5 +1,9 @@
1
1
  import { resolveApprovedVerifySelection } from './plan-verify-selection'
2
- import { activeVerifyStage, leafVerifyCycleInputs } from './verify-stages'
2
+ import {
3
+ activeVerifyStage,
4
+ cleanRestackPolicyInForce,
5
+ leafVerifyCycleInputs,
6
+ } from './verify-stages'
3
7
  import { verifyBudgetExhaustedQuestion } from './verify-budget'
4
8
  import { verifyMemberKey } from './verify-stage-state'
5
9
  import { mixedVersionDeferred } from './mixed-version'
@@ -96,7 +100,7 @@ export type VerifyMemberDecision =
96
100
  step: string
97
101
  attempt: number
98
102
  reason: string
99
- skipCause?: 'post-reconcile-policy'
103
+ skipCause?: import('../events/payloads').VerifySkipCause
100
104
  }
101
105
  export type Decision =
102
106
  | { kind: 'record-verify-selection-drift'; summary: string }
@@ -148,7 +152,7 @@ export type Decision =
148
152
  step: string
149
153
  attempt: number
150
154
  reason: string
151
- skipCause?: 'post-reconcile-policy'
155
+ skipCause?: import('../events/payloads').VerifySkipCause
152
156
  }
153
157
  | { kind: 'run-finalize-step'; step: string; action: FinalizeAction }
154
158
  | {
@@ -581,11 +585,13 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
581
585
  }
582
586
 
583
587
  // Verify cycle (§15.6-A): results only count after the latest of (last
584
- // code-review approval, reconcile completion, configuration boundary, or a
585
- // clean wait-resume restack after a verify:* or finalize wait). The stage
586
- // selection's `stageCycle` above shares these inputs. Replay identity
587
- // remains separate: refreshing config or resuming a wait neither restacks
588
- // the workspace again nor discards its post-reconcile policy.
588
+ // code-review approval, reconcile completion, configuration boundary, a
589
+ // clean wait-resume restack after a verify:* or finalize wait, or a clean
590
+ // awaiting-landing restack that froze an opted-in clean-restack policy).
591
+ // The stage selection's `stageCycle` above shares these inputs. Replay
592
+ // identity remains separate: refreshing config, resuming a wait, or
593
+ // re-verifying a clean restack neither restacks the workspace again nor
594
+ // discards its post-reconcile policy.
589
595
  // An accepted rewritten target opens a replay boundary like a completed
590
596
  // reconcile: the build's own commits restack onto the current target before
591
597
  // any further verification.
@@ -768,8 +774,12 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
768
774
  // Freeze only a fresh reconcile cycle. A newer code-review approval restores
769
775
  // ordinary verification. Already-started historical cycles have no snapshot:
770
776
  // preserve their rerun-all policy, including after a crashed verify start.
777
+ // A clean-restack cycle after an epilogue reconcile is its own cycle: the
778
+ // reconcile policy neither captures nor applies there.
771
779
  const reconcileCycle =
772
- log.lastReconcileCompletedSeq > Math.max(log.code.latestApproveSeq, log.restartSeq)
780
+ log.lastReconcileCompletedSeq >
781
+ Math.max(log.code.latestApproveSeq, log.restartSeq, log.cleanRestackVerifyBoundary)
782
+ const cleanPolicy = cleanRestackPolicyInForce(log)
773
783
  const policy =
774
784
  reconcileCycle &&
775
785
  !log.restack.initialVerification &&
@@ -824,6 +834,15 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
824
834
  skipCause: 'post-reconcile-policy',
825
835
  reason: `skipped by post-reconcile policy: ${exclusion.source} = false`,
826
836
  }
837
+ const cleanExclusion = cleanPolicy?.steps.find((s) => s.step === step && !s.enabled)
838
+ if (cleanExclusion !== undefined)
839
+ return {
840
+ kind: 'skip-verify',
841
+ step,
842
+ attempt,
843
+ skipCause: 'clean-restack-policy',
844
+ reason: `skipped by clean-restack policy: ${cleanExclusion.source} = false`,
845
+ }
827
846
 
828
847
  // Missing selection data is the historical default-all behavior. For a
829
848
  // current explicit selection, exclusion precedes path evaluation and any
@@ -7,6 +7,7 @@ import type { Exec } from '../ports/workspace/git-worktree'
7
7
  import type { BuildStore } from '../store/types'
8
8
  import { readBuildFacts } from '../store/reduced-reads'
9
9
  import {
10
+ emptyStackIdentities,
10
11
  inspectIntegrationStack,
11
12
  IntegrationStackViolation,
12
13
  raiseIntegrationStackAttention,
@@ -255,7 +256,10 @@ export async function landIntegrationRoot(deps: IntegrationLandingDeps): Promise
255
256
  }
256
257
  }
257
258
 
258
- /** Audit immutable merge-result commits, including after build completion. */
259
+ /** Audit immutable merge-result commits, including after build completion.
260
+ * An identity whose verified commit was empty and that is absent from a
261
+ * tree-identical result is accounted for, since forge rebase merges drop
262
+ * empty commits; duplicates, non-empty omissions and tree mismatches raise. */
259
263
  export async function auditIntegrationLanding(
260
264
  deps: Pick<IntegrationLandingDeps, 'store' | 'forge' | 'exec' | 'workspacePath' | 'slug' | 'id'>,
261
265
  ): Promise<void> {
@@ -302,9 +306,25 @@ export async function auditIntegrationLanding(
302
306
  const landedIdentities = messages
303
307
  ? messages.stdout.split('\0').flatMap((message) => buildTrailers(message))
304
308
  : []
305
- const missing = identities.filter(
306
- (identity) => landedIdentities.filter((value) => value === identity).length !== 1,
307
- )
309
+ const landedCount = (identity: string) =>
310
+ landedIdentities.filter((value) => value === identity).length
311
+ let missing = identities.filter((identity) => landedCount(identity) !== 1)
312
+ // A forge rebase merge drops empty commits: an identity whose verified commit
313
+ // was empty is accounted for when it is absent from a tree-identical result.
314
+ if (
315
+ intent &&
316
+ !violation &&
317
+ trees[0] === trees[1] &&
318
+ missing.some((identity) => landedCount(identity) === 0)
319
+ ) {
320
+ const empty = await emptyStackIdentities(
321
+ deps.exec,
322
+ deps.workspacePath,
323
+ intent.parent,
324
+ landing.head,
325
+ )
326
+ missing = missing.filter((identity) => landedCount(identity) !== 0 || !empty.has(identity))
327
+ }
308
328
  if (trees[0] !== trees[1] || missing.length || violation) {
309
329
  const id = `integration-audit-${landing.operation}`
310
330
  if (![...state.openEscalations, ...state.answeredEscalations].some((item) => item.id === id))
@@ -137,3 +137,42 @@ export async function raiseIntegrationStackAttention(
137
137
  },
138
138
  })
139
139
  }
140
+
141
+ /** Identities in `parent..head` whose single-trailer commit is empty: its tree
142
+ * equals its first parent's. A forge rebase merge drops empty commits, so the
143
+ * post-landing audit accounts for these identities when the landed tree equals
144
+ * the verified tree. Git failures stay plain errors so the janitor retries. */
145
+ export async function emptyStackIdentities(
146
+ exec: Exec,
147
+ cwd: string,
148
+ parent: string,
149
+ head: string,
150
+ ): Promise<Set<string>> {
151
+ const git = { exec, workspacePath: cwd }
152
+ const range = await history(git, [`${parent}..${head}`])
153
+ const trees = await exec(
154
+ ['git', 'log', '--no-show-signature', '--format=%H %T', `${parent}..${head}`, '--'],
155
+ { cwd },
156
+ )
157
+ if (trees.exitCode !== 0) throw new Error('cannot read integration stack trees')
158
+ // The first commit's parent is outside the range; resolve it to its SHA too.
159
+ const base = await exec(
160
+ ['git', 'log', '-1', '--no-show-signature', '--format=%H %T', `${parent}^{commit}`, '--'],
161
+ { cwd },
162
+ )
163
+ if (base.exitCode !== 0) throw new Error('cannot read integration stack parent tree')
164
+ const tree = new Map<string, string>()
165
+ for (const line of `${base.stdout}\n${trees.stdout}`.split('\n')) {
166
+ const [sha, value] = line.trim().split(' ')
167
+ if (sha && value) tree.set(sha, value)
168
+ }
169
+ const empty = new Set<string>()
170
+ for (const commit of range) {
171
+ const identities = buildTrailers(commit.message)
172
+ if (identities.length !== 1) continue
173
+ const own = tree.get(commit.sha)
174
+ const before = commit.parents[0] === undefined ? undefined : tree.get(commit.parents[0])
175
+ if (own !== undefined && before !== undefined && own === before) empty.add(identities[0]!)
176
+ }
177
+ return empty
178
+ }
@@ -4,11 +4,15 @@ import type { BuildStore } from '../store/types'
4
4
  import { DISPATCHER } from '../events/envelope'
5
5
  import { isForgeFailure } from '../ports/forge-failure'
6
6
  import { ForgeRequestDeferred } from '../ports/forge-request-context'
7
+ import { isRecoveryDeferred } from '../ports/workspace/recovery-step'
7
8
 
8
- /** Repository-level scheduling signals: not a janitor failure, never aged as one. */
9
+ /** Repository-level scheduling signals: not a janitor failure, never aged as
10
+ * one. Workspace recovery the invocation deadline cut short retries next
11
+ * invocation the same way. */
9
12
  export function janitorDeferral(error: unknown): boolean {
10
13
  return (
11
14
  error instanceof ForgeRequestDeferred ||
15
+ isRecoveryDeferred(error) ||
12
16
  (isForgeFailure(error) && error.details.kind === 'rate-limited')
13
17
  )
14
18
  }
@@ -54,6 +58,21 @@ export function janitorStatus(state: StatusState): BuildStatus {
54
58
  return state.statusWithoutJanitorEscalation ?? state.status
55
59
  }
56
60
 
61
+ /** A leaf whose pending abort the dispatcher acknowledges itself: queued (its
62
+ * janitor escalation aside), paused or blocked, so no runner is attached to
63
+ * hear the command. Nodes take their own janitor path. Lease liveness is the
64
+ * caller's responsibility: a live execution lease means a runner may still
65
+ * acknowledge, and the dispatcher must stand aside. */
66
+ export function dispatcherAcknowledgesAbort(
67
+ state: Pick<BuildState, 'kind' | 'status' | 'statusWithoutJanitorEscalation' | 'pendingCommands'>,
68
+ ): boolean {
69
+ return (
70
+ state.kind !== 'node' &&
71
+ state.pendingCommands.some((command) => command.command === 'abort') &&
72
+ (janitorStatus(state) === 'queued' || state.status === 'paused' || state.status === 'blocked')
73
+ )
74
+ }
75
+
57
76
  export function janitorBlocked(state: StatusState): boolean {
58
77
  return janitorStatus(state) === 'blocked'
59
78
  }
@@ -33,6 +33,9 @@ export function decodeLog(log: JsonLogIndex): LogIndex {
33
33
  ...log,
34
34
  // Values persisted before reopen existed carry no code boundary.
35
35
  codeRestartSeq: log.codeRestartSeq ?? log.restartSeq,
36
+ // Values persisted before clean-restack re-verification carry no boundary.
37
+ cleanRestackVerifyBoundary: log.cleanRestackVerifyBoundary ?? 0,
38
+ cleanRestackVerifyCycle: log.cleanRestackVerifyCycle ?? 0,
36
39
  plan: loop(log.plan),
37
40
  code: loop(log.code),
38
41
  finalizeStepsDone: new Set(log.finalizeStepsDone),
@@ -19,7 +19,12 @@ import { leafRestackReducer, type LeafRestackState } from './leaf-restack-state'
19
19
  * order — including shuffled — reproduces the whole-array result exactly.
20
20
  */
21
21
  import type { AbEvent } from '../events/catalog'
22
- import { normalizeVerifyCompletion, type EventPayload } from '../events/payloads'
22
+ import {
23
+ normalizeVerifyCompletion,
24
+ type CleanRestackPolicy,
25
+ type EventPayload,
26
+ type VerifySkipCause,
27
+ } from '../events/payloads'
23
28
  import {
24
29
  verifyPhase,
25
30
  type ArtifactRef,
@@ -103,7 +108,7 @@ export interface VerifyRecord {
103
108
  attempt: number
104
109
  outcome: VerifyOutcome
105
110
  report?: ArtifactRef
106
- skipCause?: 'post-reconcile-policy'
111
+ skipCause?: VerifySkipCause
107
112
  reason?: string
108
113
  }
109
114
 
@@ -177,6 +182,17 @@ export interface LogIndex {
177
182
  waitResumeVerifyBoundary: number
178
183
  /** That completion's restack cycle (its `restack.gates` key), else 0. */
179
184
  waitResumeVerifyCycle: number
185
+ /** seq of the latest post-restart leaf `restack.completed` that carries a
186
+ * frozen `cleanRestackPolicy`, else 0 — a verify cycle boundary: the
187
+ * cleanly restacked head re-runs the opted-in steps before landing (SPEC
188
+ * §16 "Clean-restack verification policy"). Deliberately not a replay
189
+ * boundary. */
190
+ cleanRestackVerifyBoundary: number
191
+ /** That completion's restack cycle (its `restack.gates` key), else 0. */
192
+ cleanRestackVerifyCycle: number
193
+ /** That completion's frozen policy; the engine applies it only while the
194
+ * boundary is the newest code boundary. */
195
+ cleanRestackPolicy?: CleanRestackPolicy
180
196
  /** seq of the latest post-restart `implement.completed` — a verify failure
181
197
  * with an implement round after it was already routed (§15.6-A). */
182
198
  lastImplementCompletedSeq: number
@@ -250,6 +266,7 @@ export type LogIndexCandidate =
250
266
  | { kind: 'reconcile-completed'; seq: number }
251
267
  | { kind: 'config-superseded'; seq: number }
252
268
  | { kind: 'wait-resume-restacked'; seq: number; cycle: number }
269
+ | { kind: 'clean-restack-restacked'; seq: number; cycle: number; policy: CleanRestackPolicy }
253
270
 
254
271
  export interface LogIndexAcc {
255
272
  readDeferrals: ReadDeferralsAcc
@@ -529,6 +546,13 @@ function foldLogIndex(acc: LogIndexAcc, events: readonly AbEvent[]): void {
529
546
  seq: event.seq,
530
547
  cycle: event.payload.cycle,
531
548
  })
549
+ if (event.payload.cleanRestackPolicy !== undefined)
550
+ acc.candidates.push({
551
+ kind: 'clean-restack-restacked',
552
+ seq: event.seq,
553
+ cycle: event.payload.cycle,
554
+ policy: event.payload.cleanRestackPolicy,
555
+ })
532
556
  break
533
557
  case 'reconcile.publish-intended':
534
558
  if (acc.activeReconcileStart?.attempt === event.payload.attempt)
@@ -597,6 +621,9 @@ function finishLogIndex(acc: LogIndexAcc): LogIndex {
597
621
  let lastReconcileCompletedSeq = 0
598
622
  let waitResumeVerifyBoundary = 0
599
623
  let waitResumeVerifyCycle = 0
624
+ let cleanRestackVerifyBoundary = 0
625
+ let cleanRestackVerifyCycle = 0
626
+ let cleanRestackPolicy: CleanRestackPolicy | undefined
600
627
  let lastImplementCompletedSeq = 0
601
628
  let finalizeCompleted = false
602
629
  let openFinalizeStep: LogIndex['openFinalizeStep']
@@ -710,6 +737,13 @@ function finishLogIndex(acc: LogIndexAcc): LogIndex {
710
737
  waitResumeVerifyCycle = candidate.cycle
711
738
  }
712
739
  break
740
+ case 'clean-restack-restacked':
741
+ if (candidate.seq > cleanRestackVerifyBoundary) {
742
+ cleanRestackVerifyBoundary = candidate.seq
743
+ cleanRestackVerifyCycle = candidate.cycle
744
+ cleanRestackPolicy = candidate.policy
745
+ }
746
+ break
713
747
  }
714
748
  }
715
749
 
@@ -779,6 +813,11 @@ function finishLogIndex(acc: LogIndexAcc): LogIndex {
779
813
  lastReconcileCompletedSeq,
780
814
  waitResumeVerifyBoundary,
781
815
  waitResumeVerifyCycle,
816
+ cleanRestackVerifyBoundary,
817
+ cleanRestackVerifyCycle,
818
+ ...(cleanRestackPolicy === undefined
819
+ ? {}
820
+ : { cleanRestackPolicy: structuredClone(cleanRestackPolicy) }),
782
821
  lastImplementCompletedSeq,
783
822
  finalizeCompleted,
784
823
  finalizeStepsDone,
@@ -13,7 +13,7 @@ export interface OpenPrBackpressurePolicy {
13
13
  }
14
14
 
15
15
  /** Open-PR backpressure as the dispatcher will decide it next tick: whether
16
- * normal-priority intake is paused, and the count and watermarks behind it. */
16
+ * high, normal and low intake is paused, and the count and watermarks behind it. */
17
17
  export interface OpenPrBackpressure extends OpenPrBackpressurePolicy {
18
18
  active: boolean
19
19
  openPrs: number
@@ -121,13 +121,13 @@ export function backpressureTransition(
121
121
  * lines and the dispatcher's ticket diagnostics; `''` when inactive. */
122
122
  export function backpressureExplanation(backpressure?: OpenPrBackpressure): string {
123
123
  if (!backpressure?.active) return ''
124
- return `open-PR backpressure: ${backpressure.openPrs} open root PR${backpressure.openPrs === 1 ? '' : 's'} ≥ maxOpenPrs ${backpressure.maxOpenPrs}; normal claims paused until ≤ ${backpressure.resumeOpenPrs} (urgent still claimed)${backpressure.excludeHeld ? '; held PRs excluded' : ''}`
124
+ return `open-PR backpressure: ${backpressure.openPrs} open root PR${backpressure.openPrs === 1 ? '' : 's'} ≥ maxOpenPrs ${backpressure.maxOpenPrs}; high, normal and low claims paused until ≤ ${backpressure.resumeOpenPrs} (urgent still claimed)${backpressure.excludeHeld ? '; held PRs excluded' : ''}`
125
125
  }
126
126
 
127
127
  /** The `ab repository status` line for configured backpressure, active or not. */
128
128
  export function backpressureStatusLine(backpressure: OpenPrBackpressure): string {
129
129
  const counts = `${backpressure.openPrs} open root PR${backpressure.openPrs === 1 ? '' : 's'} (max ${backpressure.maxOpenPrs}, resume ${backpressure.resumeOpenPrs}${backpressure.excludeHeld ? ', held excluded' : ''})`
130
130
  return backpressure.active
131
- ? `open-PR backpressure: active — ${counts}; normal-priority claims paused, urgent still claimed`
131
+ ? `open-PR backpressure: active — ${counts}; high, normal and low claims paused, urgent still claimed`
132
132
  : `open-PR backpressure: inactive — ${counts}`
133
133
  }
@@ -73,6 +73,7 @@ import { sessionReducer } from '../store/session-reducer'
73
73
  import { pinnedAssetsReducer } from '../store/ticket-assets'
74
74
  import { autoMergeDefaultReducer } from './auto-merge-default'
75
75
  import { buildRosterEntryReducer, buildRosterRollup } from './build-roster'
76
+ import { doneEscalationEntryReducer, doneEscalationsRollup } from './done-escalations'
76
77
  import { currentDeferralObservationReducer } from './auto-merge'
77
78
  import { dispatchSettingsReducer } from './dispatch-settings'
78
79
  import { dispatchStatusReducer } from './dispatch-status'
@@ -201,6 +202,7 @@ const REGISTERED: Record<string, Omit<RegisteredReducer, 'valueRead'>> = {
201
202
  },
202
203
  buildTimeline: { reducer: buildTimelineReducer, covers: [] },
203
204
  buildRosterEntry: { reducer: buildRosterEntryReducer, covers: [] },
205
+ doneEscalationEntry: { reducer: doneEscalationEntryReducer, covers: [] },
204
206
  autoMergeDefault: { reducer: autoMergeDefaultReducer, covers: ['latestAutoMergeDefault'] },
205
207
  pinnedAssets: { reducer: pinnedAssetsReducer, covers: ['findPinnedRevision'] },
206
208
  forgeHealthValue: { reducer: optionalValue(forgeHealthReducer), covers: [] },
@@ -332,6 +334,7 @@ export const REDUCERS: Record<string, RegisteredReducer> = Object.fromEntries(
332
334
  export const ROLLUPS: Record<string, AnyRollupDefinition> = {
333
335
  stepDurations: stepDurationsRollup,
334
336
  buildRoster: buildRosterRollup,
337
+ doneEscalations: doneEscalationsRollup,
335
338
  }
336
339
 
337
340
  /** Event-array functions that are deliberately not reducers, each with the
@@ -77,4 +77,19 @@ export const REDUCER_REVISIONS: Readonly<Record<string, string>> = {
77
77
  'build/shape/rclfl10h8j': 'Durable slot admission and release seqs (SPEC §12 What holds a slot)',
78
78
  'build/shape/i4uoqi67lx': 'Node slot admission names its need (#1340)',
79
79
  'build/fold/4hkypq2buv': '#1348 answers release a slot only when the build was not carried',
80
+ 'build/shape/h19l48la2y': '#1359 clean-restack verify policy and boundary',
81
+ 'leafRestack/shape/k7h2nawq9o': '#1359 clean-restack verify policy and boundary',
82
+ 'logIndex/shape/e562ii8zcc': '#1359 clean-restack verify policy and boundary',
83
+ 'publicationState/shape/6hw8qpns3s': '#1359 clean-restack verify policy and boundary',
84
+ 'build/fold/rn0n0mihd9': '#1359 clean-restack re-verification boundary',
85
+ 'logIndex/fold/3yvjztpvdb': '#1359 clean-restack re-verification boundary',
86
+ 'repositoryAttention/fold/u6bhzf2af0': '#1357 tick-failure episodes span one-tick runs',
87
+ 'repositoryReadFacts/fold/4gnmhbji3n': '#1357 tick-failure episodes span one-tick runs',
88
+ 'build/shape/dtklvw6hfs': '#1354 four-level build and start priority',
89
+ 'ticketStarts/shape/dzxrbuuq7e': '#1354 four-level build and start priority',
90
+ 'repositoryReadFacts/shape/5yo149tiqz': '#1354 four-level build and start priority',
91
+ 'build/fold/zdrl0ibew9': '#1354 high and low levels refine build and start priority',
92
+ 'ticketStarts/fold/8fp156vze2': '#1354 high and low levels refine build and start priority',
93
+ 'doneEscalationEntry/shape/4d674ku017': 'Track outcome; abort cleanup is never listed',
94
+ 'doneEscalationEntry/shape/j7xarl33s3': 'Drop outcome; completion closes nothing',
80
95
  }