@defrex/autobuild 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +85 -14
  3. package/docs/answering-blocked-builds.md +7 -4
  4. package/docs/architecture.md +38 -10
  5. package/docs/configuration.md +55 -5
  6. package/docs/dispatcher.md +2 -2
  7. package/docs/glossary.md +1 -1
  8. package/docs/operating.md +1 -1
  9. package/docs/operator-api.md +14 -2
  10. package/docs/plugin-authoring.md +4 -0
  11. package/docs/remote-store-protocol.md +14 -4
  12. package/docs/restacking.md +4 -0
  13. package/docs/tickets.md +1 -1
  14. package/docs/troubleshooting.md +1 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/attention.ts +2 -0
  17. package/packages/core/src/cli/dashboard/model.ts +14 -4
  18. package/packages/core/src/cli/dashboard/poll.ts +14 -0
  19. package/packages/core/src/cli/dashboard/render.ts +3 -0
  20. package/packages/core/src/cli/dispatch-preflight.ts +4 -1
  21. package/packages/core/src/cli/dispatch-tickets.ts +47 -0
  22. package/packages/core/src/cli/dispatch-upgrade-controller.ts +3 -0
  23. package/packages/core/src/cli/dispatch.ts +368 -98
  24. package/packages/core/src/cli/help.ts +4 -2
  25. package/packages/core/src/cli/repo-lease.ts +225 -0
  26. package/packages/core/src/cli/repository-status.ts +3 -1
  27. package/packages/core/src/cli/status.ts +13 -13
  28. package/packages/core/src/cli/wait.ts +4 -1
  29. package/packages/core/src/cli/watch.ts +15 -4
  30. package/packages/core/src/config/schema.ts +38 -2
  31. package/packages/core/src/events/catalog.ts +2 -0
  32. package/packages/core/src/events/payloads.ts +15 -0
  33. package/packages/core/src/events/policy.ts +2 -0
  34. package/packages/core/src/events/repository.ts +2 -0
  35. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +196 -230
  36. package/packages/core/src/kernel/dispatch-capacity.ts +134 -30
  37. package/packages/core/src/kernel/engine.ts +13 -6
  38. package/packages/core/src/kernel/generators/build-log.ts +9 -0
  39. package/packages/core/src/kernel/incremental-fixtures.ts +1 -0
  40. package/packages/core/src/kernel/janitor-failure.ts +85 -5
  41. package/packages/core/src/kernel/leaf-restack-state.ts +4 -2
  42. package/packages/core/src/kernel/log-index.ts +1 -1
  43. package/packages/core/src/kernel/node-landing.ts +2 -1
  44. package/packages/core/src/kernel/reducer-registry.ts +6 -1
  45. package/packages/core/src/kernel/reducer.ts +58 -4
  46. package/packages/core/src/kernel/ticket-preparation.ts +11 -7
  47. package/packages/core/src/operator/query.ts +15 -12
  48. package/packages/core/src/ports/tickets/create.ts +19 -5
  49. package/packages/core/src/ports/types.ts +4 -0
  50. package/packages/core/src/ports/workspace/commit-preservation.ts +28 -12
  51. package/packages/core/src/ports/workspace/git-worktree.ts +3 -1
  52. package/packages/core/src/ports/workspace/harvest-execution.ts +4 -2
  53. package/packages/core/src/ports/workspace/vercel-sandbox.ts +3 -0
  54. package/packages/core/src/processes/build-runner.ts +2 -1
  55. package/packages/core/src/processes/dispatcher.ts +231 -41
  56. package/packages/core/src/processes/execution-no-progress.ts +2 -0
  57. package/packages/core/src/processes/harvest-child.ts +4 -2
  58. package/packages/core/src/processes/harvest-execution-state.ts +104 -0
  59. package/packages/core/src/processes/harvest-runner.ts +246 -17
  60. package/packages/core/src/scenarios/harness.ts +145 -35
  61. package/packages/core/src/store/reduced-reads.ts +10 -0
  62. package/packages/core/src/store/reducer-value-shapes.json +1463 -1215
  63. package/packages/core/src/store/remote/released-clients.json +11 -0
  64. package/packages/core/src/store/remote/released-reducer-values/1.6.0.json +27173 -0
  65. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  66. package/packages/core/src/testing/reduced-read-budget.ts +339 -2
  67. package/skills/guide/SKILL.md +53 -17
  68. package/skills/guide/references/operator-api.md +14 -2
  69. package/skills/guide/references/plugin-authoring.md +4 -0
  70. package/skills/guide/references/remote-store-protocol.md +14 -4
  71. package/skills/guide/references/restacking.md +4 -0
  72. package/skills/operate/SKILL.md +50 -11
  73. package/skills/tickets/SKILL.md +4 -2
  74. package/templates/hosted-service/package.json +2 -2
@@ -3,15 +3,23 @@ import type { BuildRecord } from '../store/types'
3
3
  import type { BuildState } from './reducer'
4
4
  import { integrationAdmissible, integrationNeedsRunner } from './integration-state'
5
5
 
6
- /** Repository-scoped, reduced facts. Provisioning reserves a slot before a workspace exists. */
6
+ /** Repository-scoped, reduced facts. Provisioning reserves a slot before a workspace exists.
7
+ *
8
+ * `capacity` counts builds running work. A leaf that has finished its pipeline
9
+ * (settled, see `epilogueLeaf`) and holds no runner is parked: it waits for a
10
+ * merge decision, merge gates or the forge and holds no slot, though it keeps
11
+ * its workspace. Every other unfinished leaf holds a slot, paused or blocked
12
+ * included. Nodes hold a slot only while they need a runner. */
7
13
  export interface CapacityBuild {
8
14
  record: BuildRecord
9
15
  state: BuildState
10
16
  workspace: boolean
11
17
  provisioning?: boolean
18
+ /** The engine's awaiting-landing restack is due (`landingRestackDue`); omitted means false. */
19
+ restackDue?: boolean
12
20
  }
13
21
 
14
- /** The runner a node has durably requested and does not yet hold. */
22
+ /** The runner a node or parked leaf has durably requested and does not yet hold. */
15
23
  export type SlotRequest = 'verification' | 'reconcile'
16
24
 
17
25
  export interface DispatchCapacity {
@@ -21,33 +29,103 @@ export interface DispatchCapacity {
21
29
  borrowingNodes: string[]
22
30
  /** Nodes admitted ahead of new ticket claims; omitted when none wait, and by an older server. */
23
31
  waitingNodes?: { slug: string; request: SlotRequest }[]
32
+ /** Parked leaves admitted ahead of new ticket claims; omitted when none wait, and by an older server. */
33
+ waitingBuilds?: { slug: string; request: SlotRequest }[]
24
34
  }
25
35
 
26
- /** A workspace, a provisioning marker or a live lease holds runner capacity. */
27
- function allocated(build: CapacityBuild, now: Date): boolean {
36
+ /** A provisioning marker or continuation, or a live lease: a runner is working. */
37
+ function runnerAllocated(build: CapacityBuild, now: Date): boolean {
28
38
  return (
29
- build.workspace ||
30
39
  !!build.provisioning ||
31
40
  (build.record.lease !== undefined && Date.parse(build.record.lease.expiresAt) > now.getTime())
32
41
  )
33
42
  }
34
43
 
44
+ /** A workspace, a provisioning marker or a live lease holds runner capacity. */
45
+ function allocated(build: CapacityBuild, now: Date): boolean {
46
+ return build.workspace || runnerAllocated(build, now)
47
+ }
48
+
49
+ /** The position the dispatcher records as settled: the later of the current
50
+ * verify cycle's start and the latest finalize completion. A reconcile,
51
+ * restack or config supersession opens a new cycle and so a new key. */
52
+ export function settlementKey(state: BuildState): number {
53
+ return Math.max(state.verify.cycleSince, state.finalizeCompletedSeq)
54
+ }
55
+
56
+ function terminal(state: BuildState): boolean {
57
+ return state.status === 'done' || state.status === 'aborted'
58
+ }
59
+
60
+ /** A nonterminal leaf that finished its pipeline (every verify step and
61
+ * finalize post-step) for the current spec at least once, as recorded by
62
+ * `pipeline.settled`. A spec revision after settlement makes it unfinished. */
63
+ export function epilogueLeaf(state: BuildState): boolean {
64
+ return (
65
+ state.kind !== 'node' && !terminal(state) && (state.pipelineSettled ?? 0) > state.restartSince
66
+ )
67
+ }
68
+
69
+ /** A provider-observable execution (one with a command id) stays open until
70
+ * supervision records its end on provider proof, so it holds its runner past
71
+ * an expired lease, unknown liveness included. A local execution's liveness
72
+ * is its lease. */
73
+ function executionOpen(state: BuildState): boolean {
74
+ return state.openExecution?.commandId !== undefined
75
+ }
76
+
77
+ /** A finished leaf with no runner working. It holds no slot; its workspace does not count. */
78
+ export function parkedLeaf(build: CapacityBuild, now: Date): boolean {
79
+ return epilogueLeaf(build.state) && !runnerAllocated(build, now) && !executionOpen(build.state)
80
+ }
81
+
82
+ /** A finished leaf whose latest verify cycle or finalize has not been settled
83
+ * since: it must re-verify before it waits for its merge decision again. */
84
+ export function epilogueUnsettled(state: BuildState): boolean {
85
+ return epilogueLeaf(state) && (state.pipelineSettled ?? 0) < settlementKey(state)
86
+ }
87
+
88
+ /** The dispatcher should record a `pipeline.settled` fact when the engine's
89
+ * decision for this leaf is `wait awaiting-pr`. */
90
+ export function settlementDue(state: BuildState): boolean {
91
+ return (
92
+ state.kind !== 'node' &&
93
+ !terminal(state) &&
94
+ state.finalizeCompletedSeq > state.restartSince &&
95
+ (state.pipelineSettled ?? 0) < settlementKey(state)
96
+ )
97
+ }
98
+
35
99
  export function occupiesCapacity(build: CapacityBuild, now: Date): boolean {
36
100
  const { state } = build
37
- if (state.status === 'done' || state.status === 'aborted') return false
38
- return (
39
- state.kind !== 'node' ||
40
- !!state.nodeRestack?.conflict ||
41
- (integrationNeedsRunner(state) && allocated(build, now))
101
+ if (terminal(state)) return false
102
+ if (state.kind !== 'node') return !parkedLeaf(build, now)
103
+ return !!state.nodeRestack?.conflict || (integrationNeedsRunner(state) && allocated(build, now))
104
+ }
105
+
106
+ /** A parked leaf's durable request for a runner, or undefined. */
107
+ function leafSlotRequest(build: CapacityBuild, now: Date): SlotRequest | undefined {
108
+ const { state } = build
109
+ if (
110
+ !parkedLeaf(build, now) ||
111
+ state.status === 'paused' ||
112
+ state.status === 'blocked' ||
113
+ (state.compatibility?.decisiveFacts ?? 0) > 0 ||
114
+ state.targetRewrite !== undefined
42
115
  )
116
+ return undefined
117
+ if (state.prState === 'conflicted') return 'reconcile'
118
+ if (build.restackDue || epilogueUnsettled(state)) return 'verification'
119
+ return undefined
43
120
  }
44
121
 
45
- /** A node's durable request for a runner it does not hold yet. Admission
46
- * outranks new ticket claims, so this never depends on when a tick saw it. */
122
+ /** A node's or parked leaf's durable request for a runner it does not hold
123
+ * yet. Admission outranks new ticket claims, so this never depends on when a
124
+ * tick saw it. */
47
125
  export function slotRequest(build: CapacityBuild, now: Date): SlotRequest | undefined {
48
126
  const { state } = build
127
+ if (state.kind !== 'node') return leafSlotRequest(build, now)
49
128
  if (
50
- state.kind !== 'node' ||
51
129
  state.status === 'done' ||
52
130
  state.status === 'aborted' ||
53
131
  state.status === 'paused' ||
@@ -138,44 +216,70 @@ export function dispatchCapacity(
138
216
  })
139
217
  .map((build) => build.record.slug)
140
218
  .sort()
141
- const waitingNodes = unique
142
- .flatMap((build) => {
143
- const request = slotRequest(build, now)
144
- return request ? [{ slug: build.record.slug, request }] : []
145
- })
146
- .sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0))
219
+ const waiting = (kind: 'node' | 'leaf') =>
220
+ unique
221
+ .flatMap((build) => {
222
+ if ((build.state.kind === 'node') !== (kind === 'node')) return []
223
+ const request = slotRequest(build, now)
224
+ return request ? [{ slug: build.record.slug, request }] : []
225
+ })
226
+ .sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0))
227
+ const waitingNodes = waiting('node')
228
+ const waitingBuilds = waiting('leaf')
147
229
  return {
148
230
  configured,
149
231
  occupied,
150
232
  effective: borrowingNodes.length ? Math.max(configured, occupied) : configured,
151
233
  borrowingNodes,
152
234
  ...(waitingNodes.length ? { waitingNodes } : {}),
235
+ ...(waitingBuilds.length ? { waitingBuilds } : {}),
153
236
  }
154
237
  }
155
238
 
156
- /** Slots left for new ticket claims. A verification request reserves one slot
157
- * until the node holds it; a reconcile request already occupies one. Never
158
- * more than the configured budget minus occupied builds. */
159
- export function intakeCapacity(capacity: DispatchCapacity): number {
160
- const reserved = (capacity.waitingNodes ?? []).filter(
239
+ /** Slots left for new ticket claims. A node verification request reserves one
240
+ * slot until the node holds it; a node reconcile request already occupies one.
241
+ * A parked build's request occupies nothing, so every one reserves a slot.
242
+ * Never more than the configured budget minus occupied builds.
243
+ *
244
+ * The dispatcher refines the projection with its own decisions this tick:
245
+ * `settled` drops waiters it found waiting for their PR, `denied` adds
246
+ * builds its admission gate turned away. Status surfaces omit `adjust`. */
247
+ export function intakeCapacity(
248
+ capacity: DispatchCapacity,
249
+ adjust: { settled?: ReadonlySet<string>; denied?: ReadonlySet<string> } = {},
250
+ ): number {
251
+ const nodes = (capacity.waitingNodes ?? []).filter(
161
252
  (node) => node.request === 'verification',
162
253
  ).length
163
- return capacity.configured - capacity.occupied - reserved
254
+ const builds = new Set(
255
+ (capacity.waitingBuilds ?? [])
256
+ .map((build) => build.slug)
257
+ .filter((slug) => !adjust.settled?.has(slug)),
258
+ )
259
+ for (const slug of adjust.denied ?? []) builds.add(slug)
260
+ return capacity.configured - capacity.occupied - nodes - builds.size
164
261
  }
165
262
 
166
- /** Shared wording for one node waiting on a runner slot. */
263
+ /** Shared wording for one node or parked build waiting on a runner slot. */
167
264
  export function slotWaitText(request: SlotRequest): string {
168
265
  return `${request} waiting for a slot ahead of new ticket claims`
169
266
  }
170
267
 
171
- /** Shared wording for every node waiting on a runner slot, or `''`. */
268
+ /** Shared wording for every node and parked build waiting on a runner slot, or `''`. */
172
269
  export function waitingExplanation(
173
270
  capacity?: DispatchCapacity,
174
271
  opts: { requests?: boolean } = {},
175
272
  ): string {
176
- const waiting = capacity?.waitingNodes ?? []
177
- if (!waiting.length) return ''
178
- return `${waiting.length} node${waiting.length === 1 ? '' : 's'} waiting for a slot ahead of new ticket claims: ${waiting.map((node) => (opts.requests ? `${node.slug} (${node.request})` : node.slug)).join(', ')}`
273
+ const clause = (noun: string, waiting: { slug: string; request: SlotRequest }[]) =>
274
+ waiting.length
275
+ ? [
276
+ `${waiting.length} ${noun}${waiting.length === 1 ? '' : 's'} waiting for a slot ahead of new ticket claims: ${waiting.map((entry) => (opts.requests ? `${entry.slug} (${entry.request})` : entry.slug)).join(', ')}`,
277
+ ]
278
+ : []
279
+ return [
280
+ ...clause('node', capacity?.waitingNodes ?? []),
281
+ ...clause('parked build', capacity?.waitingBuilds ?? []),
282
+ ].join('; ')
179
283
  }
180
284
 
181
285
  /** Shared wording for the terminal and browser control lines. */
@@ -782,12 +782,7 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
782
782
  state.reconcileAttempts
783
783
  return { kind: 'run-phase', phase: 'reconcile', round: attempt, reconcile: { attempt } }
784
784
  }
785
- if (
786
- log.restack.target !== undefined &&
787
- (log.restack.target.sha !== (log.restack.completed?.targetBase ?? log.restack.initialBase) ||
788
- (state.target !== undefined &&
789
- (log.restack.postStepAt ?? 0) > (log.restack.completedAt ?? 0)))
790
- ) {
785
+ if (landingRestackDue(state, log)) {
791
786
  return { kind: 'restack', trigger: 'awaiting-landing', cycle: cycleBoundary }
792
787
  }
793
788
  if (state.prState === 'conflicted' && log.lastConflict !== undefined) {
@@ -841,6 +836,18 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
841
836
  return { kind: 'wait', reason: 'awaiting-pr' }
842
837
  }
843
838
 
839
+ /** The §9 awaiting-landing restack condition: the target moved since the
840
+ * build's last restack base, or a target post-step landed after it. Shared
841
+ * with dispatch capacity, which admits a parked build that must restack. */
842
+ export function landingRestackDue(state: BuildState, log: Pick<LogIndex, 'restack'>): boolean {
843
+ return (
844
+ log.restack.target !== undefined &&
845
+ (log.restack.target.sha !== (log.restack.completed?.targetBase ?? log.restack.initialBase) ||
846
+ (state.target !== undefined &&
847
+ (log.restack.postStepAt ?? 0) > (log.restack.completedAt ?? 0)))
848
+ )
849
+ }
850
+
844
851
  // ── Review-loop transition (rules 5 and 6 share one structure — §10) ─────────
845
852
 
846
853
  interface LoopArgs {
@@ -48,6 +48,15 @@ function randomWrite(rand: () => number): EventWrite {
48
48
  nextAttemptAt: '2026-01-01T00:01:00.000Z',
49
49
  }),
50
50
  () => w('build.janitor-failing', { message: 'forge unavailable' }),
51
+ () =>
52
+ w('build.janitor-escalated', {
53
+ id: 'janitor:2026-01-01T00:00:00.000Z',
54
+ operation: 'PR check',
55
+ message: 'forge unavailable',
56
+ attempt,
57
+ firstFailureAt: '2026-01-01T00:00:00.000Z',
58
+ question: 'Janitor PR check has failed.',
59
+ }),
51
60
  () => w('build.janitor-recovered', {}),
52
61
  () =>
53
62
  w('landing.application-failed', {
@@ -167,6 +167,7 @@ export function randomBuildItem(rand: Rand): readonly [string, Record<string, un
167
167
  () => ['observation.recorded', { id: 'o', kind: 'followup', summary: 's', refs: [marker] }],
168
168
  () => ['observation.recorded', { id: 'o2', kind: 'refactor', summary: 's' }],
169
169
  () => ['session.started', { session: 's', role: 'r', runner: 'c', phase: 'plan' }],
170
+ () => ['pipeline.settled', { cycle: 1 + Math.floor(rand() * 40) }],
170
171
  ]
171
172
  return pick(rand, templates)()
172
173
  }
@@ -1,4 +1,5 @@
1
1
  import type { BuildState } from './reducer'
2
+ import type { BuildStatus } from '../ontology'
2
3
  import type { BuildStore } from '../store/types'
3
4
  import { DISPATCHER } from '../events/envelope'
4
5
  import { isForgeFailure } from '../ports/forge-failure'
@@ -12,16 +13,77 @@ export function janitorDeferral(error: unknown): boolean {
12
13
  )
13
14
  }
14
15
 
16
+ /** The janitor stage an attempt was in when it failed, named in the escalation. */
17
+ export type JanitorOperation =
18
+ | 'build state read'
19
+ | 'native auto-merge cancellation'
20
+ | 'integration landing audit'
21
+ | 'PR attachment reclaim'
22
+ | 'control command'
23
+ | 'node integration'
24
+ | 'node cascade'
25
+ | 'empty node poll'
26
+ | 'abort cleanup'
27
+ | 'discard cleanup'
28
+ | 'target observation'
29
+ | 'PR check'
30
+
31
+ /** A build's janitor attempt is due: no episode, an answered escalation asked
32
+ * for a retry, or the backoff has elapsed. */
33
+ export function janitorDue(janitor: BuildState['janitor'], now: Date): boolean {
34
+ return (
35
+ !janitor ||
36
+ janitor.retryRequested === true ||
37
+ Date.parse(janitor.nextAttemptAt) <= now.getTime()
38
+ )
39
+ }
40
+
41
+ /** One escalation per episode, identified by the episode's first failure. */
42
+ export function janitorEscalationId(firstFailureAt: string): string {
43
+ return `janitor:${firstFailureAt}`
44
+ }
45
+
46
+ type StatusState = Pick<BuildState, 'status' | 'statusWithoutJanitorEscalation'>
47
+
48
+ /** The status the janitor acts on: its own escalation never gates the work
49
+ * that would recover it, so a build blocked only by that escalation reads as
50
+ * it would without it. Every other case is the build's status. */
51
+ export function janitorStatus(state: StatusState): BuildStatus {
52
+ return state.statusWithoutJanitorEscalation ?? state.status
53
+ }
54
+
55
+ export function janitorBlocked(state: StatusState): boolean {
56
+ return janitorStatus(state) === 'blocked'
57
+ }
58
+
59
+ export function escalationsBeyondJanitor(state: Pick<BuildState, 'openEscalations'>) {
60
+ return state.openEscalations.filter((e) => !e.janitor)
61
+ }
62
+
63
+ /** The build as the janitor's landing decisions see it: without its janitor
64
+ * escalation, so a failing landing step is retried rather than skipped. */
65
+ export function withoutJanitorEscalation(state: BuildState): BuildState {
66
+ if (state.statusWithoutJanitorEscalation === undefined) return state
67
+ const { statusWithoutJanitorEscalation: status, ...rest } = state
68
+ return { ...rest, status, openEscalations: escalationsBeyondJanitor(state) }
69
+ }
70
+
15
71
  export async function recordJanitorFailure(
16
72
  store: BuildStore,
17
73
  slug: string,
18
74
  previous: BuildState['janitor'],
19
75
  message: string,
20
76
  now: Date,
21
- policy: { janitorBackoffMaxSeconds: number; janitorFailureAttentionSeconds: number },
77
+ policy: {
78
+ janitorBackoffMaxSeconds: number
79
+ janitorFailureAttentionSeconds: number
80
+ janitorFailureEscalationSeconds: number
81
+ },
82
+ operation: JanitorOperation,
22
83
  ): Promise<void> {
23
84
  const attempt = (previous?.attempt ?? 0) + 1
24
85
  const firstFailureAt = previous?.firstFailureAt ?? now.toISOString()
86
+ const age = now.getTime() - Date.parse(firstFailureAt)
25
87
  await store.append(slug, {
26
88
  actor: DISPATCHER,
27
89
  type: 'build.janitor-attempt-failed',
@@ -35,13 +97,31 @@ export async function recordJanitorFailure(
35
97
  ).toISOString(),
36
98
  },
37
99
  })
38
- if (
39
- !previous?.attention &&
40
- now.getTime() - Date.parse(firstFailureAt) >= policy.janitorFailureAttentionSeconds * 1000
41
- )
100
+ if (!previous?.attention && age >= policy.janitorFailureAttentionSeconds * 1000)
42
101
  await store.append(slug, {
43
102
  actor: DISPATCHER,
44
103
  type: 'build.janitor-failing',
45
104
  payload: { message },
46
105
  })
106
+ // Wall-clock from the episode's first failure, checked only on a failed
107
+ // attempt; a deferral never reaches here. A crash after the appends above
108
+ // leaves `escalation` unset, so the next failure raises it.
109
+ if (previous && !previous.escalation && age >= policy.janitorFailureEscalationSeconds * 1000) {
110
+ const line = message.replace(/\s+/g, ' ').trim()
111
+ await store.append(slug, {
112
+ actor: DISPATCHER,
113
+ type: 'build.janitor-escalated',
114
+ payload: {
115
+ id: janitorEscalationId(firstFailureAt),
116
+ operation,
117
+ message,
118
+ attempt,
119
+ firstFailureAt,
120
+ question:
121
+ `Janitor ${operation} has failed ${attempt} consecutive attempts since ${firstFailureAt}. ` +
122
+ `Last error: ${line}. The janitor keeps retrying and closes this escalation when an ` +
123
+ 'attempt succeeds. Fix the cause, then answer with a bare retry to attempt now.',
124
+ },
125
+ })
126
+ }
47
127
  }
@@ -21,7 +21,9 @@ export interface LeafRestackState {
21
21
  }
22
22
  export function advanceLeafRestack(state: LeafRestackState, events: readonly AbEvent[]) {
23
23
  for (const event of events) {
24
- if (event.type !== 'target.distance') state.activityAt = event.ts
24
+ // Advisory dispatcher bookkeeping is not lifecycle activity.
25
+ if (event.type !== 'target.distance' && event.type !== 'pipeline.settled')
26
+ state.activityAt = event.ts
25
27
  switch (event.type) {
26
28
  case 'workspace.provisioned':
27
29
  state.initialBase ??= event.payload.base.sha
@@ -113,7 +115,7 @@ export function advanceLeafRestack(state: LeafRestackState, events: readonly AbE
113
115
  }
114
116
  }
115
117
  export const leafRestackReducer = defineReducer<LeafRestackState, AbEvent, LeafRestackState>({
116
- version: 8,
118
+ version: 9,
117
119
  initial: () => ({ gates: {} }),
118
120
  fold: advanceLeafRestack,
119
121
  finish: (state) => structuredClone(state),
@@ -196,7 +196,7 @@ export interface LogIndex {
196
196
  guidanceDeliveries: GuidanceDelivery[]
197
197
  }
198
198
 
199
- export const LOG_INDEX_REDUCER_VERSION = 9
199
+ export const LOG_INDEX_REDUCER_VERSION = 10
200
200
 
201
201
  type ReviewVerdictPayload = EventPayload<'plan-review.verdict'>
202
202
 
@@ -2,6 +2,7 @@ import { observeTarget } from './target-observation'
2
2
  import { deferMixedVersion, MixedVersionDeferral } from './mixed-version'
3
3
  import { inspectIntegrationStack } from './integration-stack'
4
4
  import { integrationFailed } from './integration-state'
5
+ import { janitorBlocked } from './janitor-failure'
5
6
  import type { BuildStore } from '../store/types'
6
7
  import { readBuildFacts } from '../store/reduced-reads'
7
8
  import type { Forge, AutoMergeDeferralReason } from '../ports/types'
@@ -83,7 +84,7 @@ export async function landIntoNode(
83
84
  state.status === 'aborted' ||
84
85
  state.status === 'done' ||
85
86
  state.status === 'paused' ||
86
- (state.status === 'blocked' && !integrationFailed(state)) ||
87
+ (janitorBlocked(state) && !integrationFailed(state)) ||
87
88
  state.prState === 'closed' ||
88
89
  state.prState === 'merged' ||
89
90
  state.pendingCommands.length ||
@@ -53,7 +53,10 @@ import {
53
53
  lastExecutionOutcomeReducer,
54
54
  openExecutionReducer,
55
55
  } from '../processes/execution-settlement'
56
- import { openHarvestExecutionsReducer } from '../processes/harvest-execution-state'
56
+ import {
57
+ hostedHarvestAuthorityReducer,
58
+ openHarvestExecutionsReducer,
59
+ } from '../processes/harvest-execution-state'
57
60
  import { infrastructureFailureResetReducer } from '../processes/infrastructure-failure-budget'
58
61
  import { publicationStateReducer } from '../processes/publication-state'
59
62
  import { sandboxStatesReducer } from '../processes/sandbox-state'
@@ -152,6 +155,7 @@ const REGISTERED: Record<string, Omit<RegisteredReducer, 'valueRead'>> = {
152
155
  reducer: openHarvestExecutionsReducer,
153
156
  covers: ['openHarvestExecutions'],
154
157
  },
158
+ hostedHarvestAuthority: { reducer: hostedHarvestAuthorityReducer, covers: [] },
155
159
  openTick: { reducer: openTickReducer('run-a'), covers: ['hasOpenTick'] },
156
160
  dispatchFailureBudget: {
157
161
  reducer: dispatchFailureBudgetReducer(false),
@@ -234,6 +238,7 @@ const repositoryValues = new Set([
234
238
  'dispatchStatus',
235
239
  'sandboxStates',
236
240
  'openHarvestExecutions',
241
+ 'hostedHarvestAuthority',
237
242
  'openTick',
238
243
  'autoMergeDefault',
239
244
  ])
@@ -75,6 +75,9 @@ export interface OpenEscalation {
75
75
  /** Policy guard identity. Absent only on historical policy raises. */
76
76
  policyCause?: PolicyEscalationCause
77
77
  deferral?: 'own-build-read'
78
+ /** Raised by `build.janitor-escalated`. Its routing is inert (`setup`
79
+ * target, no cause); the janitor's recovery closes it unanswered. */
80
+ janitor?: true
78
81
  question: string
79
82
  refs?: string[]
80
83
  /** seq of the `escalation.raised` event — what `spec.revised` cites (§15.3). */
@@ -253,6 +256,10 @@ export interface BuildState {
253
256
  * a still-blocked build reports 'blocked' again. No information is lost.
254
257
  */
255
258
  status: BuildStatus
259
+ /** The status this build would have without its janitor escalation; present
260
+ * only while one is open. The janitor reads it so its own escalation never
261
+ * gates the work that would recover it. */
262
+ statusWithoutJanitorEscalation?: BuildStatus
256
263
  /** From `build.completed` — present only once status is 'done'. */
257
264
  outcome?: BuildOutcome
258
265
  /** currentPhase if one is started-but-not-completed, else the latest
@@ -286,6 +293,10 @@ export interface BuildState {
286
293
  message: string
287
294
  nextAttemptAt: string
288
295
  attention?: true
296
+ /** Id of this episode's escalation, once raised. */
297
+ escalation?: string
298
+ /** The escalation was answered: attempt again without waiting out backoff. */
299
+ retryRequested?: true
289
300
  }
290
301
  landing?: LandingState
291
302
  /** Historical auto-merge controls retained for replay compatibility. */
@@ -297,6 +308,10 @@ export interface BuildState {
297
308
  * read it. Compare this against `restartSince`, exactly as engine.ts:707-708
298
309
  * post-filters its own `finalizeCompleted`. */
299
310
  finalizeCompletedSeq: number
311
+ /** Largest settlement key the dispatcher observed at the engine's leaf
312
+ * `wait awaiting-pr` decision (`pipeline.settled`); capacity evidence only,
313
+ * never a pipeline decision input. */
314
+ pipelineSettled?: number
300
315
  /** Full-log `finalize.step-completed` facts, in event order (§5).
301
316
  * Post-steps are failure-tolerant, so a completion counts whether `ok` is
302
317
  * true or false. Current-spec membership is determined by
@@ -392,6 +407,8 @@ export interface BuildState {
392
407
  dispatchFailures: Array<EventPayload<'dispatch.failed'> & { seq: number }>
393
408
  /** Provider identities and failures are durable even after recovery clears the current error. */
394
409
  executions: Array<EventPayload<'execution.started'> & { seq: number }>
410
+ /** The latest execution, while no instance-matched `execution.ended` follows it. */
411
+ openExecution?: EventPayload<'execution.started'> & { seq: number }
395
412
  infrastructureFailures: Array<EventPayload<'infrastructure.failed'> & { seq: number }>
396
413
  infrastructureFailure?: EventPayload<'infrastructure.failed'> & { seq: number }
397
414
  cleanupAttempts: Array<EventPayload<'infrastructure.cleanup-attempted'> & { seq: number }>
@@ -467,6 +484,10 @@ export interface BuildAcc {
467
484
  message: string
468
485
  nextAttemptAt: string
469
486
  attention?: true
487
+ /** Id of this episode's escalation, once raised. */
488
+ escalation?: string
489
+ /** The escalation was answered: attempt again without waiting out backoff. */
490
+ retryRequested?: true
470
491
  }
471
492
  landing?: LandingState
472
493
  autoMerge: AutoMergeProjection
@@ -476,6 +497,7 @@ export interface BuildAcc {
476
497
  issueLinks: BuildIssueLink[]
477
498
  issueLinksSealedSeq?: number
478
499
  finalizeCompletedSeq: number
500
+ pipelineSettled?: number
479
501
  finalizeSteps: BuildState['finalizeSteps']
480
502
  plan: BuildState['plan']
481
503
  implement: BuildState['implement']
@@ -505,7 +527,7 @@ export interface BuildAcc {
505
527
  }
506
528
 
507
529
  /** Bump when `BuildAcc`'s shape or the fold's semantics change. */
508
- export const BUILD_REDUCER_VERSION = 30
530
+ export const BUILD_REDUCER_VERSION = 32
509
531
 
510
532
  function initialBuildAcc(): BuildAcc {
511
533
  return {
@@ -667,9 +689,16 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
667
689
  acc.janitor = {
668
690
  ...event.payload,
669
691
  ...(acc.janitor?.attention ? { attention: true as const } : {}),
692
+ ...(acc.janitor?.escalation ? { escalation: acc.janitor.escalation } : {}),
670
693
  }
671
694
  if (event.type === 'build.janitor-failing' && acc.janitor) acc.janitor.attention = true
672
- if (event.type === 'build.janitor-recovered') delete acc.janitor
695
+ if (event.type === 'build.janitor-escalated' && acc.janitor)
696
+ acc.janitor.escalation = event.payload.id
697
+ if (event.type === 'build.janitor-recovered') {
698
+ delete acc.janitor
699
+ for (const escalation of [...openEscalations.values()])
700
+ if (escalation.janitor) openEscalations.delete(escalation.id)
701
+ }
673
702
  if (event.type === 'target.rewritten') acc.targetRewrite = event
674
703
  if (
675
704
  event.type === 'target.moved' ||
@@ -1177,6 +1206,9 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1177
1206
  finalizeCompletedSeq = event.seq
1178
1207
  complete('finalize', event.seq)
1179
1208
  break
1209
+ case 'pipeline.settled':
1210
+ acc.pipelineSettled = Math.max(acc.pipelineSettled ?? 0, event.payload.cycle)
1211
+ break
1180
1212
  case 'finalize.step-completed':
1181
1213
  // §5: post-steps are independent and failure-tolerant — a completion
1182
1214
  // counts whether `ok` is true or false. Retain full-log history with
@@ -1260,6 +1292,17 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1260
1292
  seq: event.seq,
1261
1293
  })
1262
1294
  break
1295
+ case 'build.janitor-escalated':
1296
+ if (!openEscalations.has(event.payload.id))
1297
+ openEscalations.set(event.payload.id, {
1298
+ id: event.payload.id,
1299
+ phase: 'setup',
1300
+ source: 'policy',
1301
+ janitor: true,
1302
+ question: event.payload.question,
1303
+ seq: event.seq,
1304
+ })
1305
+ break
1263
1306
  case 'escalation.raised': {
1264
1307
  const escalation: OpenEscalation = {
1265
1308
  id: event.payload.id,
@@ -1298,6 +1341,7 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1298
1341
  : {}),
1299
1342
  answeredSeq: event.seq,
1300
1343
  })
1344
+ if (open.janitor && acc.janitor?.escalation === open.id) acc.janitor.retryRequested = true
1301
1345
  if (
1302
1346
  event.payload.reviewRoundCeiling !== undefined &&
1303
1347
  open.source === 'policy' &&
@@ -1380,21 +1424,26 @@ function finishBuild(acc: BuildAcc): BuildState {
1380
1424
  discardRequest,
1381
1425
  pending,
1382
1426
  } = acc
1427
+ const latestExecution = acc.executions.at(-1)
1383
1428
 
1384
1429
  // §15.5 precedence: aborted/done (terminal, latest wins) > paused >
1385
1430
  // blocked > running > queued. See BuildState.status for the paused+blocked
1386
1431
  // overlap rule.
1387
- const status: BuildStatus =
1432
+ const statusOf = (escalations: readonly OpenEscalation[]): BuildStatus =>
1388
1433
  terminal ??
1389
1434
  (pausedFlag
1390
1435
  ? 'paused'
1391
- : acc.openEscalations.length > 0 || integrationFailed(acc)
1436
+ : escalations.length > 0 || integrationFailed(acc)
1392
1437
  ? 'blocked'
1393
1438
  : acc.kind === 'node' && acc.nodeOpened !== undefined
1394
1439
  ? 'collecting'
1395
1440
  : attached
1396
1441
  ? 'running'
1397
1442
  : 'queued')
1443
+ const status = statusOf(acc.openEscalations)
1444
+ const statusWithoutJanitorEscalation = acc.openEscalations.some((e) => e.janitor)
1445
+ ? statusOf(acc.openEscalations.filter((e) => !e.janitor))
1446
+ : undefined
1398
1447
 
1399
1448
  const active = currentPhase ?? lastCompletedPhase
1400
1449
 
@@ -1412,6 +1461,7 @@ function finishBuild(acc: BuildAcc): BuildState {
1412
1461
  ...(acc.nodeIssueLinks !== undefined ? { nodeIssueLinks: acc.nodeIssueLinks } : {}),
1413
1462
  nodeRestack: acc.nodeRestack,
1414
1463
  status,
1464
+ ...(statusWithoutJanitorEscalation !== undefined ? { statusWithoutJanitorEscalation } : {}),
1415
1465
  outcome: acc.outcome,
1416
1466
  phase: active?.phase,
1417
1467
  round: acc.round,
@@ -1427,6 +1477,7 @@ function finishBuild(acc: BuildAcc): BuildState {
1427
1477
  landing: acc.landing,
1428
1478
  autoMerge: acc.autoMerge,
1429
1479
  finalizeCompletedSeq: acc.finalizeCompletedSeq,
1480
+ ...(acc.pipelineSettled !== undefined ? { pipelineSettled: acc.pipelineSettled } : {}),
1430
1481
  finalizeSteps: acc.finalizeSteps,
1431
1482
  lastEvent,
1432
1483
  lastSeq: Math.max(lastEvent?.seq ?? 0, acc.compatibility.lastSeq),
@@ -1455,6 +1506,9 @@ function finishBuild(acc: BuildAcc): BuildState {
1455
1506
  setupFailure: acc.setupFailure,
1456
1507
  dispatchFailures: acc.dispatchFailures,
1457
1508
  executions: acc.executions,
1509
+ ...(latestExecution && !acc.endedExecutionInstances[latestExecution.instance]
1510
+ ? { openExecution: latestExecution }
1511
+ : {}),
1458
1512
  infrastructureFailures: acc.infrastructureFailures,
1459
1513
  infrastructureFailure: acc.infrastructureFailure,
1460
1514
  cleanupAttempts: acc.cleanupAttempts,