@defrex/autobuild 1.5.0 → 1.7.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 (126) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +192 -24
  3. package/docs/agent-runtimes.md +1 -1
  4. package/docs/answering-blocked-builds.md +7 -4
  5. package/docs/architecture.md +100 -32
  6. package/docs/configuration-overview.md +10 -0
  7. package/docs/configuration.md +340 -10
  8. package/docs/dispatcher.md +2 -2
  9. package/docs/forges.md +1 -0
  10. package/docs/glossary.md +1 -1
  11. package/docs/operating.md +1 -1
  12. package/docs/operator-api.md +33 -10
  13. package/docs/operator-surfaces.md +6 -3
  14. package/docs/plugin-authoring.md +48 -6
  15. package/docs/remote-store-protocol.md +33 -10
  16. package/docs/restacking.md +16 -7
  17. package/docs/ticket-sources.md +34 -6
  18. package/docs/tickets.md +7 -1
  19. package/docs/troubleshooting.md +1 -1
  20. package/docs/workspaces.md +1 -1
  21. package/package.json +3 -3
  22. package/packages/core/src/cli/attention.ts +3 -0
  23. package/packages/core/src/cli/binary-direct.ts +1 -0
  24. package/packages/core/src/cli/dashboard/model.ts +14 -4
  25. package/packages/core/src/cli/dashboard/poll.ts +14 -0
  26. package/packages/core/src/cli/dashboard/render.ts +3 -0
  27. package/packages/core/src/cli/dispatch-frontend.ts +10 -14
  28. package/packages/core/src/cli/dispatch-preflight.ts +5 -1
  29. package/packages/core/src/cli/dispatch-repository-feed.ts +145 -109
  30. package/packages/core/src/cli/dispatch-tickets.ts +47 -0
  31. package/packages/core/src/cli/dispatch-upgrade-controller.ts +3 -0
  32. package/packages/core/src/cli/dispatch.ts +377 -101
  33. package/packages/core/src/cli/help.ts +15 -6
  34. package/packages/core/src/cli/init-validation.ts +14 -1
  35. package/packages/core/src/cli/repo-lease.ts +225 -0
  36. package/packages/core/src/cli/repository-status.ts +40 -3
  37. package/packages/core/src/cli/status.ts +21 -13
  38. package/packages/core/src/cli/ticket.ts +22 -4
  39. package/packages/core/src/cli/wait.ts +4 -1
  40. package/packages/core/src/cli/watch.ts +17 -4
  41. package/packages/core/src/config/live.ts +4 -0
  42. package/packages/core/src/config/profiles.ts +96 -0
  43. package/packages/core/src/config/ready-assignee.ts +43 -11
  44. package/packages/core/src/config/roles.ts +33 -10
  45. package/packages/core/src/config/schema.ts +204 -26
  46. package/packages/core/src/events/catalog.ts +2 -0
  47. package/packages/core/src/events/compatibility.ts +3 -1
  48. package/packages/core/src/events/forge-degradation-policy.ts +16 -2
  49. package/packages/core/src/events/payloads.ts +23 -0
  50. package/packages/core/src/events/policy.ts +3 -0
  51. package/packages/core/src/events/repository.ts +19 -0
  52. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +267 -352
  53. package/packages/core/src/kernel/build-creation.ts +29 -0
  54. package/packages/core/src/kernel/dispatch-capacity.ts +134 -30
  55. package/packages/core/src/kernel/engine.ts +13 -6
  56. package/packages/core/src/kernel/forge-health.ts +47 -0
  57. package/packages/core/src/kernel/generators/build-log.ts +9 -0
  58. package/packages/core/src/kernel/guarded-forge.ts +76 -18
  59. package/packages/core/src/kernel/incremental-fixtures.ts +1 -0
  60. package/packages/core/src/kernel/janitor-failure.ts +85 -5
  61. package/packages/core/src/kernel/leaf-restack-state.ts +4 -2
  62. package/packages/core/src/kernel/log-index.ts +1 -1
  63. package/packages/core/src/kernel/node-landing.ts +2 -1
  64. package/packages/core/src/kernel/node-parent.ts +2 -0
  65. package/packages/core/src/kernel/read-facts.ts +9 -1
  66. package/packages/core/src/kernel/reducer-registry.ts +6 -1
  67. package/packages/core/src/kernel/reducer.ts +75 -4
  68. package/packages/core/src/kernel/ticket-preparation.ts +15 -8
  69. package/packages/core/src/operator/protocol.ts +10 -0
  70. package/packages/core/src/operator/query.ts +16 -13
  71. package/packages/core/src/operator/registry.ts +25 -5
  72. package/packages/core/src/operator/sandbox-host.ts +3 -0
  73. package/packages/core/src/operator/tickets.ts +15 -3
  74. package/packages/core/src/plugin-sdk/index.ts +4 -0
  75. package/packages/core/src/ports/forge/create.ts +6 -0
  76. package/packages/core/src/ports/forge/github-transport.ts +40 -3
  77. package/packages/core/src/ports/forge/github.ts +12 -1
  78. package/packages/core/src/ports/forge/workspace-ancestry.ts +60 -0
  79. package/packages/core/src/ports/forge-failure.ts +31 -2
  80. package/packages/core/src/ports/runner/routing.ts +66 -5
  81. package/packages/core/src/ports/tickets/assignees.ts +54 -0
  82. package/packages/core/src/ports/tickets/contract.ts +164 -4
  83. package/packages/core/src/ports/tickets/create.ts +35 -7
  84. package/packages/core/src/ports/tickets/github-fake.ts +18 -2
  85. package/packages/core/src/ports/tickets/github.ts +247 -29
  86. package/packages/core/src/ports/tickets/hosted-index.ts +1 -0
  87. package/packages/core/src/ports/tickets/operations.ts +6 -1
  88. package/packages/core/src/ports/tickets/tree.ts +12 -2
  89. package/packages/core/src/ports/tickets/update.ts +6 -2
  90. package/packages/core/src/ports/types.ts +37 -3
  91. package/packages/core/src/ports/workspace/commit-preservation.ts +28 -12
  92. package/packages/core/src/ports/workspace/git-worktree.ts +3 -1
  93. package/packages/core/src/ports/workspace/harvest-execution.ts +4 -2
  94. package/packages/core/src/ports/workspace/vercel-sandbox.ts +12 -0
  95. package/packages/core/src/processes/build-child.ts +28 -7
  96. package/packages/core/src/processes/build-execution-state.ts +4 -1
  97. package/packages/core/src/processes/build-runner.ts +17 -2
  98. package/packages/core/src/processes/dispatcher.ts +329 -59
  99. package/packages/core/src/processes/execution-no-progress.ts +2 -0
  100. package/packages/core/src/processes/harvest-child.ts +8 -2
  101. package/packages/core/src/processes/harvest-execution-state.ts +104 -0
  102. package/packages/core/src/processes/harvest-runner.ts +251 -17
  103. package/packages/core/src/processes/repo-view.ts +2 -0
  104. package/packages/core/src/scenarios/harness.ts +160 -36
  105. package/packages/core/src/store/reduced-reads.ts +10 -0
  106. package/packages/core/src/store/reducer-value-shapes.json +3339 -2898
  107. package/packages/core/src/store/remote/client.ts +21 -8
  108. package/packages/core/src/store/remote/index.ts +4 -0
  109. package/packages/core/src/store/remote/protocol.ts +7 -0
  110. package/packages/core/src/store/remote/released-clients.json +22 -0
  111. package/packages/core/src/store/remote/released-reducer-values/1.6.0.json +27173 -0
  112. package/packages/core/src/store/remote/released-reducer-values/1.7.0.json +27366 -0
  113. package/packages/core/src/store/remote/released-reducer-values/index.ts +4 -0
  114. package/packages/core/src/store/repo-state-events.ts +1 -0
  115. package/packages/core/src/store/types.ts +11 -0
  116. package/packages/core/src/testing/dispatch-read-budget.ts +84 -58
  117. package/packages/core/src/testing/index.ts +2 -0
  118. package/packages/core/src/testing/reduced-read-budget.ts +411 -11
  119. package/skills/guide/SKILL.md +166 -35
  120. package/skills/guide/references/operator-api.md +33 -10
  121. package/skills/guide/references/plugin-authoring.md +48 -6
  122. package/skills/guide/references/remote-store-protocol.md +33 -10
  123. package/skills/guide/references/restacking.md +16 -7
  124. package/skills/operate/SKILL.md +79 -14
  125. package/skills/tickets/SKILL.md +22 -4
  126. package/templates/hosted-service/package.json +2 -2
@@ -0,0 +1,29 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ /** The grammar of a build-creation key: a preparation attempt id. */
4
+ export const CREATION_KEY = /^[A-Za-z0-9_-]{1,128}$/
5
+
6
+ /** The slug base an allocating store suffixes: the requested slug's first 60
7
+ * characters without trailing hyphens. */
8
+ export function projectBuildSlugBase(requestedSlug: string): string {
9
+ return requestedSlug.slice(0, 60).replace(/-+$/, '')
10
+ }
11
+
12
+ /**
13
+ * The canonical slug an allocating store gives a keyed creation. Client and
14
+ * server share this derivation, so a client that lost the create response can
15
+ * point-read the build its own key created and no other. Two keys collide only
16
+ * with the same repository, requested slug and 96-bit digest prefix; a store
17
+ * answers such a repeat with a conflict and never allocates a second identity.
18
+ */
19
+ export function creationBuildSlug(
20
+ repo: string,
21
+ requestedSlug: string,
22
+ creationKey: string,
23
+ ): string {
24
+ const digest = createHash('sha256')
25
+ .update(`autobuild-build-creation\0${repo}\0${requestedSlug}\0${creationKey}`)
26
+ .digest('hex')
27
+ .slice(0, 24)
28
+ return `${projectBuildSlugBase(requestedSlug)}-${digest}`
29
+ }
@@ -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 {
@@ -17,3 +17,50 @@ export const forgeHealthReducer = defineReducer<
17
17
  },
18
18
  finish: (acc) => acc.active,
19
19
  })
20
+
21
+ /** One process's latest rate limit outside the dispatcher's credential. */
22
+ export type ForgeCredentialLimit = RepositoryEventPayload<'forge.credential-limited'> & {
23
+ at: string
24
+ }
25
+
26
+ /** Retained credential-limit entries; the newest resets win. */
27
+ export const FORGE_CREDENTIAL_LIMIT_CAP = 16
28
+
29
+ /** Latest `forge.credential-limited` per (forge, process), bounded. Expiry
30
+ * is a read-time projection: callers keep only entries whose reset is ahead. */
31
+ export const forgeCredentialLimitsReducer = defineReducer<
32
+ { limits: Record<string, ForgeCredentialLimit> },
33
+ RepositoryEvent,
34
+ ForgeCredentialLimit[]
35
+ >({
36
+ version: 1,
37
+ initial: () => ({ limits: {} }),
38
+ fold(acc, events) {
39
+ for (const event of events) {
40
+ if (event.type !== 'forge.credential-limited') continue
41
+ acc.limits[`${event.payload.forge}\u0000${event.payload.process}`] = {
42
+ ...event.payload,
43
+ at: event.ts,
44
+ }
45
+ }
46
+ const entries = Object.entries(acc.limits)
47
+ if (entries.length > FORGE_CREDENTIAL_LIMIT_CAP)
48
+ acc.limits = Object.fromEntries(
49
+ entries
50
+ .sort(([, a], [, b]) => Date.parse(b.resetAt) - Date.parse(a.resetAt))
51
+ .slice(0, FORGE_CREDENTIAL_LIMIT_CAP),
52
+ )
53
+ },
54
+ finish: (acc) =>
55
+ Object.values(acc.limits)
56
+ .map((limit) => ({ ...limit }))
57
+ .sort((a, b) => a.resetAt.localeCompare(b.resetAt)),
58
+ })
59
+
60
+ /** Entries whose reset is still ahead of `now`. */
61
+ export function activeForgeCredentialLimits(
62
+ limits: readonly ForgeCredentialLimit[],
63
+ now: Date,
64
+ ): ForgeCredentialLimit[] {
65
+ return limits.filter((limit) => Date.parse(limit.resetAt) > now.getTime())
66
+ }
@@ -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', {
@@ -12,21 +12,33 @@ import { KERNEL } from '../events/envelope'
12
12
  /** Scheduling signal, never a failed attempt. */
13
13
  export class ForgeCooldown extends ForgeRequestDeferred {}
14
14
 
15
+ /** Whose rate limits a guard may record. `'repository'` is the dispatcher's
16
+ * own forge: its classified limits pause forge work repository-wide. A
17
+ * process scope (build runner, phase session) only obeys that cooldown; its
18
+ * own limits, like any unauthenticated limit, stay local to the guard and are
19
+ * reported as attention, because they say nothing about the dispatcher's
20
+ * credential. */
21
+ export type ForgeGuardScope = 'repository' | { process: string }
22
+
15
23
  /** Receiver bindings and optional plugin capabilities survive the wrapper.
16
24
  * Only trusted kernel composition receives the repository Store authority. */
17
- type GuardDeps = { store: BuildStore; repo: string; name: string; now?: () => Date; wait?: boolean }
25
+ type GuardDeps = {
26
+ store: BuildStore
27
+ repo: string
28
+ name: string
29
+ now?: () => Date
30
+ wait?: boolean
31
+ scope?: ForgeGuardScope
32
+ /** Test seam for cooldown waits. */
33
+ sleep?: (ms: number) => Promise<void>
34
+ }
18
35
  const guarded = new WeakMap<Forge, { raw: Forge; deps: GuardDeps }>()
19
36
 
20
- export function guardForge(
21
- forge: Forge,
22
- deps: {
23
- store: BuildStore
24
- repo: string
25
- name: string
26
- now?: () => Date
27
- wait?: boolean
28
- },
29
- ): Forge {
37
+ function scopeKey(scope: ForgeGuardScope | undefined): string {
38
+ return scope === undefined || scope === 'repository' ? 'repository' : `process:${scope.process}`
39
+ }
40
+
41
+ export function guardForge(forge: Forge, deps: GuardDeps): Forge {
30
42
  const previous = guarded.get(forge)
31
43
  if (previous) {
32
44
  if (
@@ -34,29 +46,75 @@ export function guardForge(
34
46
  previous.deps.repo === deps.repo &&
35
47
  previous.deps.name === deps.name &&
36
48
  previous.deps.wait === deps.wait &&
37
- previous.deps.now === deps.now
49
+ previous.deps.now === deps.now &&
50
+ previous.deps.sleep === deps.sleep &&
51
+ scopeKey(previous.deps.scope) === scopeKey(deps.scope)
38
52
  )
39
53
  return forge
40
54
  return guardForge(previous.raw, deps)
41
55
  }
42
56
  if (deps.name === 'local-git') return forge
43
57
  const now = deps.now ?? (() => new Date())
58
+ const sleep =
59
+ deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
60
+ const scope = deps.scope ?? 'repository'
44
61
  const health = () => readForgeHealth(deps.store, deps.repo)
62
+ const pause = (resetAt: string) =>
63
+ sleep(Math.max(1000, Math.min(30_000, Date.parse(resetAt) - now().getTime())))
64
+ /** This guard's own cooldown from a limit that is not repository-wide, and
65
+ * the latest reset it has already reported (one fact per episode). */
66
+ let local: { resetAt: string } | undefined
67
+ let reported: string | undefined
45
68
  const before = async () => {
69
+ while (local) {
70
+ if (Date.parse(local.resetAt) <= now().getTime()) {
71
+ local = undefined
72
+ break
73
+ }
74
+ if (!deps.wait) throw new ForgeCooldown(`Forge cooldown until ${local.resetAt}`)
75
+ await pause(local.resetAt)
76
+ }
46
77
  let active = await health()
47
78
  while (active && (deps.wait || Date.parse(active.resetAt) > now().getTime())) {
48
79
  if (!deps.wait) throw new ForgeCooldown(`Forge cooldown until ${active.resetAt}`)
49
- await new Promise((resolve) =>
50
- setTimeout(
51
- resolve,
52
- Math.max(1000, Math.min(30_000, Date.parse(active!.resetAt) - now().getTime())),
53
- ),
54
- )
80
+ await pause(active.resetAt)
55
81
  active = await health()
56
82
  }
57
83
  }
58
84
  const failed = async (error: unknown) => {
59
85
  if (!isForgeFailure(error) || error.details.kind !== 'rate-limited') return
86
+ const details = error.details
87
+ if (scope !== 'repository' || details.unauthenticated) {
88
+ // At least one second, so a stale reset cannot spin a waiting retry.
89
+ const until = Math.max(
90
+ Date.parse(details.resetAt),
91
+ local ? Date.parse(local.resetAt) : 0,
92
+ now().getTime() + 1000,
93
+ )
94
+ local = { resetAt: new Date(until).toISOString() }
95
+ if (reported !== undefined && Date.parse(reported) >= Date.parse(details.resetAt)) return
96
+ reported = details.resetAt
97
+ try {
98
+ await deps.store.appendRepo(deps.repo, {
99
+ actor: KERNEL,
100
+ type: 'forge.credential-limited',
101
+ payload: {
102
+ forge: deps.name,
103
+ process: scope === 'repository' ? 'dispatcher' : scope.process,
104
+ credential: details.unauthenticated ? 'unauthenticated' : 'process',
105
+ ...(details.unauthenticated
106
+ ? { missingCredential: details.unauthenticated.slice(0, 1000) }
107
+ : {}),
108
+ message: error.message.slice(0, 2000),
109
+ resetAt: details.resetAt,
110
+ },
111
+ })
112
+ } catch {
113
+ // Attention only: an older server or a missing repository must not
114
+ // turn the limited request into a different failure.
115
+ }
116
+ return
117
+ }
60
118
  const active = await health()
61
119
  if (active?.resetAt === error.details.resetAt && active.message === error.message) return
62
120
  // Runner/phase credentials cannot administer repositories; their repo
@@ -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 ||