@defrex/autobuild 1.11.1 → 1.12.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 (102) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +177 -54
  3. package/docs/answering-blocked-builds.md +10 -2
  4. package/docs/architecture.md +66 -6
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/configuration.md +13 -11
  7. package/docs/dispatcher.md +1 -1
  8. package/docs/integration-tree.md +28 -16
  9. package/docs/operator-api.md +4 -4
  10. package/docs/operator-surfaces.md +35 -0
  11. package/docs/optimization-nodes.md +3 -2
  12. package/docs/tickets.md +1 -1
  13. package/docs/troubleshooting.md +1 -1
  14. package/package.json +3 -3
  15. package/packages/core/src/cli/ambient-errors.ts +17 -0
  16. package/packages/core/src/cli/bounded-io.ts +174 -0
  17. package/packages/core/src/cli/dashboard/model.ts +81 -23
  18. package/packages/core/src/cli/dashboard/poll.ts +20 -31
  19. package/packages/core/src/cli/dashboard/render.ts +14 -37
  20. package/packages/core/src/cli/dashboard/row-text.ts +24 -7
  21. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  22. package/packages/core/src/cli/dashboard/vocabulary.ts +161 -20
  23. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  24. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  25. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  26. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  27. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  28. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  29. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  30. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  31. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  32. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  33. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  34. package/packages/core/src/cli/dispatch.ts +68 -5
  35. package/packages/core/src/cli/env.ts +2 -15
  36. package/packages/core/src/cli/help.ts +5 -4
  37. package/packages/core/src/cli/main.ts +4 -2
  38. package/packages/core/src/cli/production-store.ts +102 -0
  39. package/packages/core/src/cli/repo-state.ts +2 -3
  40. package/packages/core/src/cli/repository-status.ts +28 -22
  41. package/packages/core/src/cli/sessionless-store.ts +26 -0
  42. package/packages/core/src/cli/status.ts +169 -40
  43. package/packages/core/src/cli/store-opening.ts +15 -58
  44. package/packages/core/src/cli/store-ref.ts +6 -1
  45. package/packages/core/src/config/schema.ts +1 -1
  46. package/packages/core/src/distribution-packaging.ts +156 -18
  47. package/packages/core/src/events/catalog-identity.ts +28 -0
  48. package/packages/core/src/events/catalog.ts +3 -9
  49. package/packages/core/src/events/compatibility.ts +2 -30
  50. package/packages/core/src/events/payloads.ts +11 -0
  51. package/packages/core/src/events/policy.ts +3 -0
  52. package/packages/core/src/events/repository.ts +1 -1
  53. package/packages/core/src/events/sessions.ts +1 -1
  54. package/packages/core/src/events/validation-error.ts +12 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +9 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  59. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  60. package/packages/core/src/kernel/capacity-build.ts +21 -0
  61. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  62. package/packages/core/src/kernel/dispatch-capacity.ts +354 -147
  63. package/packages/core/src/kernel/engine.ts +2 -8
  64. package/packages/core/src/kernel/measurement.ts +24 -0
  65. package/packages/core/src/kernel/read-facts.ts +8 -370
  66. package/packages/core/src/kernel/reducer-registry.ts +40 -125
  67. package/packages/core/src/kernel/reducer-revisions.ts +3 -0
  68. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  69. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  70. package/packages/core/src/kernel/reducer.ts +57 -9
  71. package/packages/core/src/kernel/reopen-state.ts +10 -0
  72. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  73. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  74. package/packages/core/src/operator/presentation.ts +13 -0
  75. package/packages/core/src/operator/query.ts +40 -39
  76. package/packages/core/src/operator/registry.ts +3 -3
  77. package/packages/core/src/ports/workspace/fake.ts +15 -3
  78. package/packages/core/src/processes/dispatcher.ts +232 -75
  79. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  80. package/packages/core/src/store/local/capabilities.ts +115 -0
  81. package/packages/core/src/store/local/store.ts +86 -56
  82. package/packages/core/src/store/reduced-reads.ts +9 -1
  83. package/packages/core/src/store/reducer-value-read.ts +235 -0
  84. package/packages/core/src/store/reducer-value-shapes.json +1437 -1349
  85. package/packages/core/src/store/reducer-values.ts +36 -204
  86. package/packages/core/src/store/remote/released-clients.json +11 -0
  87. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  88. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  89. package/packages/core/src/store/rollup-lease.ts +41 -0
  90. package/packages/core/src/store/rollups.ts +7 -38
  91. package/packages/core/src/store/snapshots.ts +1 -1
  92. package/packages/core/src/testing/dispatch-read-budget.ts +265 -4
  93. package/packages/core/src/testing/import-graph.ts +78 -0
  94. package/packages/core/src/testing/reduced-read-budget.ts +221 -22
  95. package/packages/core/src/testing/slot-agreement.ts +52 -0
  96. package/packages/core/src/web/assets/app.js +5 -5
  97. package/skills/guide/SKILL.md +115 -44
  98. package/skills/guide/references/integration-tree.md +28 -16
  99. package/skills/guide/references/operator-api.md +4 -4
  100. package/skills/guide/references/optimization-nodes.md +3 -2
  101. package/skills/operate/SKILL.md +38 -20
  102. package/templates/hosted-service/package.json +2 -2
@@ -0,0 +1,375 @@
1
+ /** JSON-safe repository projections for persisted current-state consumers. */
2
+ import { ticketPreparationReducer } from './ticket-preparation'
3
+ import { ticketHandbacksReducer } from './ticket-handbacks'
4
+ import { ticketStartsReducer } from './ticket-starts'
5
+ import { ticketMigrationsReducer } from './ticket-migrations'
6
+ import { dispatchUpgradeReducer } from './dispatch-upgrade'
7
+ import {
8
+ advanceCompatibility,
9
+ initialCompatibility,
10
+ projectEvents,
11
+ type CompatibilityState,
12
+ } from '../events/compatibility'
13
+ import { defineReducer } from './incremental'
14
+
15
+ import type { RepositoryEvent } from '../events/repository'
16
+ import { repositoryAttentionReducer } from './repository-attention'
17
+ import { dispatchSettingsReducer } from './dispatch-settings'
18
+ import { harvestReducer } from './harvest'
19
+ import { forgeCredentialLimitsReducer, forgeHealthReducer } from './forge-health'
20
+ import { kernelGitHealthReducer } from './kernel-git'
21
+ import { openPrBackpressureReducer } from './open-pr-backpressure-state'
22
+ import { ticketSourceHealthReducer } from './ticket-source-health'
23
+ import { autoMergeDefaultReducer } from './auto-merge-default'
24
+ import { effectiveConfigReducer } from './service-facts'
25
+ import { sandboxStatesReducer } from '../processes/sandbox-state'
26
+ import { openHarvestExecutionsReducer } from '../processes/harvest-execution-state'
27
+ import {
28
+ dispatchStatusReducer,
29
+ foldReportedDispatch,
30
+ initialReportedDispatch,
31
+ RECENT_DISPATCH_RUN_LIMIT,
32
+ type ReportedDispatch,
33
+ } from './dispatch-status'
34
+
35
+ export { RECENT_DISPATCH_RUN_LIMIT } from './dispatch-status'
36
+ export interface RepositoryReadAcc {
37
+ missingAccounts: Record<string, import('../accounts/availability').MissingAccountCredential>
38
+ preparation: ReturnType<typeof ticketPreparationReducer.initial>
39
+ handbacks: ReturnType<typeof ticketHandbacksReducer.initial>
40
+ ticketStarts: ReturnType<typeof ticketStartsReducer.initial>
41
+ compatibility: CompatibilityState
42
+ presence: Record<
43
+ string,
44
+ Extract<RepositoryEvent, { type: 'change-presence.observed' }>['payload']
45
+ >
46
+
47
+ upgrades: ReturnType<typeof dispatchUpgradeReducer.initial>
48
+ openHarvest: ReturnType<typeof openHarvestExecutionsReducer.initial>
49
+ attention: ReturnType<typeof repositoryAttentionReducer.initial>
50
+ harvestFailures: Record<
51
+ string,
52
+ { count: number; latest: Extract<RepositoryEvent, { type: 'harvest.failed' }> }
53
+ >
54
+ harvestTerminals: Record<
55
+ string,
56
+ Extract<RepositoryEvent, { type: 'harvest.proposals.submitted' | 'harvest.review.verdict' }>
57
+ >
58
+ harvestVerdicts: Record<
59
+ string,
60
+ {
61
+ first: Extract<RepositoryEvent, { type: 'harvest.review.verdict' }>
62
+ latest: Extract<RepositoryEvent, { type: 'harvest.review.verdict' }>
63
+ }
64
+ >
65
+ harvestAuthorizations: Record<
66
+ string,
67
+ Extract<RepositoryEvent, { type: 'harvest.execution.authorized' }>
68
+ >
69
+ harvestExecutionStarts: Record<string, string>
70
+ latestHarvestResumedSeq: number
71
+ harvestSessionEndings: Record<string, number>
72
+ harvestSessions: (import('../cli/harvest').HarvestSessionStatusView & { run: string })[]
73
+ pendingHumanResume?: number
74
+ dismissedThrough: number
75
+ failedAt: Record<string, string>
76
+ settings: ReturnType<typeof dispatchSettingsReducer.initial>
77
+ harvest: ReturnType<typeof harvestReducer.initial>
78
+ forgeHealth: ReturnType<typeof forgeHealthReducer.initial>
79
+ forgeCredentialLimits: ReturnType<typeof forgeCredentialLimitsReducer.initial>
80
+ kernelGit: ReturnType<typeof kernelGitHealthReducer.initial>
81
+ openPrBackpressure: ReturnType<typeof openPrBackpressureReducer.initial>
82
+ ticketMigrations: ReturnType<typeof ticketMigrationsReducer.initial>
83
+ health: ReturnType<typeof ticketSourceHealthReducer.initial>
84
+ autoMerge: ReturnType<typeof autoMergeDefaultReducer.initial>
85
+ config: ReturnType<typeof effectiveConfigReducer.initial>
86
+ sandboxes: ReturnType<typeof sandboxStatesReducer.initial>
87
+ /** The dispatcher run the reduced status describes; see `foldReportedDispatch`. */
88
+ dispatch: ReportedDispatch
89
+ scanSeq?: number
90
+ scan?: Extract<RepositoryEvent, { type: 'dispatcher.ticket-scan-completed' }>['payload']
91
+ recentRuns: [string, DispatcherRunFacts][]
92
+ latestRun?: string
93
+ latestStoppedRun?: string
94
+ publications: Extract<RepositoryEvent, { type: 'orchestrator.sandbox.published' }>[]
95
+ }
96
+ export const repositoryReadFactsReducer = defineReducer({
97
+ rawEvents: true,
98
+ identity: 'repositoryReadFacts',
99
+ parts: [
100
+ ticketMigrationsReducer,
101
+ dispatchUpgradeReducer,
102
+ ticketPreparationReducer,
103
+ ticketHandbacksReducer,
104
+ ticketStartsReducer,
105
+ dispatcherRunFactsReducer('version'),
106
+ openHarvestExecutionsReducer,
107
+ forgeHealthReducer,
108
+ forgeCredentialLimitsReducer,
109
+ kernelGitHealthReducer,
110
+ openPrBackpressureReducer,
111
+ repositoryAttentionReducer,
112
+ dispatchSettingsReducer,
113
+ harvestReducer,
114
+ ticketSourceHealthReducer,
115
+ autoMergeDefaultReducer,
116
+ effectiveConfigReducer,
117
+ sandboxStatesReducer,
118
+ dispatchStatusReducer('version'),
119
+ ],
120
+ initial: (): RepositoryReadAcc => ({
121
+ missingAccounts: {},
122
+ compatibility: initialCompatibility(),
123
+ presence: {},
124
+ preparation: ticketPreparationReducer.initial(),
125
+ handbacks: ticketHandbacksReducer.initial(),
126
+ ticketStarts: ticketStartsReducer.initial(),
127
+ upgrades: dispatchUpgradeReducer.initial(),
128
+ recentRuns: [],
129
+ openHarvest: openHarvestExecutionsReducer.initial(),
130
+ attention: repositoryAttentionReducer.initial(),
131
+ dismissedThrough: 0,
132
+ failedAt: {},
133
+ harvestSessions: [],
134
+ harvestSessionEndings: {},
135
+ harvestFailures: {},
136
+ harvestTerminals: {},
137
+ harvestVerdicts: {},
138
+ harvestAuthorizations: {},
139
+ latestHarvestResumedSeq: 0,
140
+ harvestExecutionStarts: {},
141
+ settings: dispatchSettingsReducer.initial(),
142
+ harvest: harvestReducer.initial(),
143
+ forgeHealth: forgeHealthReducer.initial(),
144
+ forgeCredentialLimits: forgeCredentialLimitsReducer.initial(),
145
+ kernelGit: kernelGitHealthReducer.initial(),
146
+ openPrBackpressure: openPrBackpressureReducer.initial(),
147
+ ticketMigrations: ticketMigrationsReducer.initial(),
148
+ health: ticketSourceHealthReducer.initial(),
149
+ autoMerge: autoMergeDefaultReducer.initial(),
150
+ config: effectiveConfigReducer.initial(),
151
+ sandboxes: sandboxStatesReducer.initial(),
152
+ dispatch: initialReportedDispatch(),
153
+ publications: [],
154
+ }),
155
+ fold(acc: RepositoryReadAcc, events: readonly RepositoryEvent[]) {
156
+ acc.preparation = ticketPreparationReducer.advance(acc.preparation, events)
157
+ acc.handbacks = ticketHandbacksReducer.advance(acc.handbacks, events)
158
+ acc.ticketStarts = ticketStartsReducer.advance(acc.ticketStarts, events)
159
+ advanceCompatibility(acc.compatibility, events)
160
+ acc.upgrades = dispatchUpgradeReducer.advance(acc.upgrades, events)
161
+ acc.attention = repositoryAttentionReducer.advance(acc.attention, events)
162
+ acc.openHarvest = openHarvestExecutionsReducer.advance(acc.openHarvest, events)
163
+ acc.settings = dispatchSettingsReducer.advance(acc.settings, events)
164
+ acc.harvest = harvestReducer.advance(acc.harvest, events)
165
+ acc.forgeHealth = forgeHealthReducer.advance(acc.forgeHealth, events)
166
+ acc.forgeCredentialLimits = forgeCredentialLimitsReducer.advance(
167
+ acc.forgeCredentialLimits,
168
+ events,
169
+ )
170
+ acc.kernelGit = kernelGitHealthReducer.advance(acc.kernelGit, events)
171
+ acc.openPrBackpressure = openPrBackpressureReducer.advance(acc.openPrBackpressure, events)
172
+ acc.ticketMigrations = ticketMigrationsReducer.advance(acc.ticketMigrations, events)
173
+ acc.health = ticketSourceHealthReducer.advance(acc.health, events)
174
+ acc.autoMerge = autoMergeDefaultReducer.advance(acc.autoMerge, events)
175
+ acc.config = effectiveConfigReducer.advance(acc.config, events)
176
+ acc.sandboxes = sandboxStatesReducer.advance(acc.sandboxes, events)
177
+ for (const event of projectEvents(events)) {
178
+ if (event.type === 'account.credentials-unavailable')
179
+ acc.missingAccounts[event.payload.name] = event.payload
180
+ if (event.type === 'account.credentials-recovered')
181
+ delete acc.missingAccounts[event.payload.name]
182
+ if (event.type === 'change-presence.observed')
183
+ acc.presence[event.payload.destination] = event.payload
184
+ if (event.type === 'harvest.failed') {
185
+ const key = JSON.stringify([event.payload.run, event.payload.step, event.payload.round])
186
+ acc.harvestFailures[key] = {
187
+ count: (acc.harvestFailures[key]?.count ?? 0) + 1,
188
+ latest: event,
189
+ }
190
+ }
191
+ if (
192
+ (event.type === 'harvest.proposals.submitted' || event.type === 'harvest.review.verdict') &&
193
+ event.actor.kind === 'agent'
194
+ )
195
+ acc.harvestTerminals[event.actor.session] = event
196
+ if (event.type === 'harvest.review.verdict') {
197
+ const key = JSON.stringify([event.payload.run, event.payload.round])
198
+ acc.harvestVerdicts[key] = {
199
+ first: acc.harvestVerdicts[key]?.first ?? event,
200
+ latest: event,
201
+ }
202
+ }
203
+ if (event.type === 'harvest.execution.started')
204
+ acc.harvestExecutionStarts[String(event.seq)] = event.payload.execution
205
+ if (event.type === 'harvest.execution.authorized')
206
+ acc.harvestAuthorizations[JSON.stringify(event.payload.execution)] ??= event
207
+ if (event.type === 'harvest.resumed') acc.latestHarvestResumedSeq = event.seq
208
+ if (event.type === 'harvest.session.started' && event.payload.continuation) {
209
+ const prior = acc.harvestSessions.find(
210
+ (s) => s.session === event.payload.continuation!.predecessor,
211
+ )
212
+ if (prior) prior.status = 'ended'
213
+ }
214
+ if (event.type === 'harvest.session.started')
215
+ acc.harvestSessions.push({
216
+ run: event.payload.run,
217
+ session: event.payload.session,
218
+ role: event.payload.role,
219
+ step: event.payload.step,
220
+ round: event.payload.round,
221
+ status: 'open',
222
+ ...(event.payload.continuation ? { continuation: event.payload.continuation } : {}),
223
+ ...(event.payload.stream === undefined ? {} : { stream: event.payload.stream }),
224
+ streamStatus: event.payload.stream === undefined ? 'closed' : 'open',
225
+ })
226
+ if (event.type === 'harvest.session.ended' || event.type === 'harvest.session.suspended') {
227
+ acc.harvestSessionEndings[JSON.stringify(event.payload.session)] ??= event.seq
228
+ const session = acc.harvestSessions.findLast(
229
+ (session) => session.session === event.payload.session && session.status === 'open',
230
+ )
231
+ if (session) {
232
+ session.status = event.type === 'harvest.session.suspended' ? 'suspended' : 'ended'
233
+ session.transcript = event.payload.transcript
234
+ session.streamStatus = 'closed'
235
+ }
236
+ }
237
+ if (event.type === 'harvest.resume-requested' && event.actor.kind === 'human')
238
+ acc.pendingHumanResume = event.seq
239
+ if (event.type === 'harvest.pause-requested') delete acc.pendingHumanResume
240
+ if (event.type === 'harvest.resumed' && acc.pendingHumanResume !== undefined)
241
+ acc.dismissedThrough = Math.max(acc.dismissedThrough, acc.pendingHumanResume)
242
+ if (event.type === 'harvest.failed' && !event.payload.willRetry)
243
+ acc.failedAt[JSON.stringify(event.payload.run)] = event.ts
244
+ foldReportedDispatch(acc.dispatch, event)
245
+ if (event.type === 'dispatcher.ticket-scan-completed') {
246
+ acc.scan = event.payload
247
+ acc.scanSeq = event.seq
248
+ }
249
+ if (event.type === 'dispatcher.run-started') acc.latestRun = event.payload.run
250
+ if (event.type === 'dispatcher.run-stopped') acc.latestStoppedRun = event.payload.run
251
+ if (
252
+ event.type.startsWith('dispatcher.') &&
253
+ 'run' in event.payload &&
254
+ typeof event.payload.run === 'string'
255
+ ) {
256
+ const run = event.payload.run
257
+ let entry = acc.recentRuns.find(([id]) => id === run)
258
+ if (!entry) {
259
+ entry = [run, {}]
260
+ acc.recentRuns.push(entry)
261
+ }
262
+ foldDispatcherRunFact(entry[1], event)
263
+ while (acc.recentRuns.length > RECENT_DISPATCH_RUN_LIMIT) {
264
+ const index = acc.recentRuns.findIndex(
265
+ ([id]) => id !== acc.latestRun && id !== acc.latestStoppedRun,
266
+ )
267
+ acc.recentRuns.splice(index, 1)
268
+ }
269
+ }
270
+ if (event.type === 'orchestrator.sandbox.published') {
271
+ acc.publications = acc.publications.filter(
272
+ (prior) =>
273
+ prior.payload.operator !== event.payload.operator ||
274
+ prior.payload.branch !== event.payload.branch,
275
+ )
276
+ acc.publications.push(event)
277
+ }
278
+ }
279
+ },
280
+ finish: (acc: RepositoryReadAcc) => ({
281
+ missingAccounts: structuredClone(acc.missingAccounts),
282
+ compatibility: structuredClone(acc.compatibility),
283
+ presence: structuredClone(acc.presence),
284
+ preparation: ticketPreparationReducer.finish(acc.preparation),
285
+ handbacks: ticketHandbacksReducer.finish(acc.handbacks),
286
+ ticketStarts: ticketStartsReducer.finish(acc.ticketStarts),
287
+ upgrades: dispatchUpgradeReducer.finish(acc.upgrades),
288
+ harvestFailures: structuredClone(acc.harvestFailures),
289
+ harvestTerminals: structuredClone(acc.harvestTerminals),
290
+ harvestVerdicts: structuredClone(acc.harvestVerdicts),
291
+ harvestAuthorizations: structuredClone(acc.harvestAuthorizations),
292
+ harvestExecutionStarts: { ...acc.harvestExecutionStarts },
293
+ latestHarvestResumedSeq: acc.latestHarvestResumedSeq,
294
+ harvestSessionEndings: { ...acc.harvestSessionEndings },
295
+ harvestSessions: structuredClone(acc.harvestSessions),
296
+ attention: repositoryAttentionReducer.finish(acc.attention),
297
+ dismissedThrough: acc.dismissedThrough,
298
+ failedAt: { ...acc.failedAt },
299
+ openHarvest: openHarvestExecutionsReducer.finish(acc.openHarvest),
300
+ settings: dispatchSettingsReducer.finish(acc.settings),
301
+ harvest: harvestReducer.finish(acc.harvest),
302
+ forgeHealth: forgeHealthReducer.finish(acc.forgeHealth),
303
+ forgeCredentialLimits: forgeCredentialLimitsReducer.finish(acc.forgeCredentialLimits),
304
+ kernelGit: kernelGitHealthReducer.finish(acc.kernelGit),
305
+ openPrBackpressure: openPrBackpressureReducer.finish(acc.openPrBackpressure),
306
+ ticketMigrations: ticketMigrationsReducer.finish(acc.ticketMigrations),
307
+ health: ticketSourceHealthReducer.finish(acc.health),
308
+ autoMerge: autoMergeDefaultReducer.finish(acc.autoMerge),
309
+ config: effectiveConfigReducer.finish(acc.config),
310
+ sandboxes: sandboxStatesReducer.finish(acc.sandboxes),
311
+ status: acc.dispatch.run
312
+ ? dispatchStatusReducer(acc.dispatch.run).finish(acc.dispatch.status)
313
+ : undefined,
314
+ scan: acc.scan,
315
+ scanSeq: acc.scanSeq,
316
+ recentRuns: structuredClone(acc.recentRuns),
317
+ latestRun: acc.latestRun,
318
+ latestStoppedRun: acc.latestStoppedRun,
319
+ publications: structuredClone(acc.publications),
320
+ }),
321
+ })
322
+
323
+ import type { IncrementalReducer } from './incremental'
324
+ /** Companion for an optional finished answer: absence is represented by an
325
+ * omitted object field, never top-level undefined. */
326
+ export function optionalValue<A, E, V>(reducer: IncrementalReducer<A, E, V>) {
327
+ return {
328
+ ...reducer,
329
+ finish: (acc: A) => ({ value: reducer.finish(acc) }),
330
+ reduce: (events: readonly E[]) => ({ value: reducer.reduce(events) }),
331
+ }
332
+ }
333
+
334
+ /** One run's correlation facts. History for unrelated runs never enters this value. */
335
+ export interface DispatcherRunFacts {
336
+ runtime?: RepositoryEvent
337
+ start?: RepositoryEvent
338
+ latestStart?: RepositoryEvent
339
+ stop?: RepositoryEvent
340
+ tick?: RepositoryEvent
341
+ completed?: RepositoryEvent
342
+ boundary?: 'dispatcher.tick-started' | 'dispatcher.tick-completed' | 'dispatcher.tick-failed'
343
+ stopRequest?: Extract<RepositoryEvent, { type: 'dispatcher.stop-requested' }>
344
+ }
345
+ export function dispatcherRunFactsReducer(run: string) {
346
+ return defineReducer<DispatcherRunFacts, RepositoryEvent, DispatcherRunFacts>({
347
+ identity: 'dispatcherRunFacts',
348
+ initial: () => ({}),
349
+ fold(acc, events) {
350
+ for (const event of projectEvents(events)) {
351
+ if (!('run' in event.payload) || event.payload.run !== run) continue
352
+ foldDispatcherRunFact(acc, event)
353
+ }
354
+ },
355
+ finish: (acc) => structuredClone(acc),
356
+ })
357
+ }
358
+
359
+ function foldDispatcherRunFact(acc: DispatcherRunFacts, event: RepositoryEvent): void {
360
+ if (event.type === 'dispatcher.run-started') {
361
+ acc.start ??= event
362
+ acc.latestStart = event
363
+ } else if (event.type === 'dispatcher.runtime-recorded') acc.runtime = event
364
+ else if (event.type === 'dispatcher.run-stopped') acc.stop = event
365
+ else if (event.type === 'dispatcher.stop-requested') acc.stopRequest ??= event
366
+ else if (
367
+ event.type === 'dispatcher.tick-started' ||
368
+ event.type === 'dispatcher.tick-completed' ||
369
+ event.type === 'dispatcher.tick-failed'
370
+ ) {
371
+ acc.boundary = event.type
372
+ if (event.type !== 'dispatcher.tick-started') acc.tick = event
373
+ if (event.type === 'dispatcher.tick-completed') acc.completed = event
374
+ }
375
+ }
@@ -1,6 +1,5 @@
1
1
  import type { AbEvent } from '../events/catalog'
2
2
  import type { EventPayload } from '../events/payloads'
3
- import { normalizeVerifyCompletion } from '../events/payloads'
4
3
  import type { OpenEscalation, AnsweredEscalation } from './reducer'
5
4
 
6
5
  export interface VerifyMember extends EventPayload<'verify.started'> {
@@ -85,8 +84,7 @@ export function advanceVerifyStage(state: VerifyStageState, event: AbEvent): voi
85
84
  break
86
85
  }
87
86
  case 'verify.completed': {
88
- const result = normalizeVerifyCompletion(event.payload)
89
- const key = verifyMemberKey(result.step, result.attempt)
87
+ const key = verifyMemberKey(event.payload.step, event.payload.attempt)
90
88
  if (!state.cancellations[key]) state.outcomes[key] = event.seq
91
89
  break
92
90
  }
@@ -122,3 +120,147 @@ export function runningVerifyMembers(state: VerifyStageState, cycle: number): Ve
122
120
  )
123
121
  .map(([, member]) => member)
124
122
  }
123
+
124
+ /** What `escalationCarried` reads: reduced facts every `BuildState` carries,
125
+ * or the reducer's in-loop values at an answer. */
126
+ export interface EscalationCarryInput {
127
+ openEscalations: readonly Pick<
128
+ OpenEscalation,
129
+ 'source' | 'session' | 'wait' | 'seq' | 'policyCause'
130
+ >[]
131
+ verifyStage: VerifyStageState
132
+ /** The current verify cycle's boundary (`verify.cycleSince`). */
133
+ verifyCycle: number
134
+ maxAttemptSeen: number
135
+ /** Every `execution.started`, in log order. */
136
+ executions: readonly { seq: number }[]
137
+ /** The latest execution, while no `execution.ended` closed it. */
138
+ liveExecution?: { seq: number } | undefined
139
+ /** The latest admission: `build.created` or `slot.admitted`. */
140
+ slotAdmittedSeq?: number | undefined
141
+ /** The recorded launch failures, each list in log order: `dispatch.failed`,
142
+ * `infrastructure.failed` and `runner.setup-failed`. */
143
+ failures: readonly (readonly { seq: number }[])[]
144
+ }
145
+
146
+ /** The latest launch record, or undefined: the admission (`build.created` or
147
+ * `slot.admitted`) that precedes every launch of a build holding its slot.
148
+ * The dispatcher appends `slot.admitted` before every holding launch except
149
+ * one already in flight, and every claim's `build.created` is followed by its
150
+ * dispatch, so an acknowledgement launch, which holds no slot, is the only
151
+ * launch with no record of its own. */
152
+ export function launchRecordSeq(input: Pick<EscalationCarryInput, 'slotAdmittedSeq'>) {
153
+ return input.slotAdmittedSeq
154
+ }
155
+
156
+ /** (L) A launch in flight: its record is newer than the latest
157
+ * `execution.started`, every recorded launch failure and any open
158
+ * `execution-no-progress` escalation. Only the start (which hands over to the
159
+ * execution), a failure fact or that refusal ends it. The dispatcher's
160
+ * progress guard raises `execution-no-progress` in place of the launch, so
161
+ * that raise is a launch failure; no other escalation ends a launch, since
162
+ * none proves a provisioning or launching runner stopped. */
163
+ export function launchInFlight(
164
+ input: Pick<
165
+ EscalationCarryInput,
166
+ 'executions' | 'slotAdmittedSeq' | 'failures' | 'openEscalations'
167
+ >,
168
+ ): boolean {
169
+ const record = launchRecordSeq(input)
170
+ return (
171
+ record !== undefined &&
172
+ record > (input.executions.at(-1)?.seq ?? 0) &&
173
+ !launchEnded(input, record, Number.POSITIVE_INFINITY)
174
+ )
175
+ }
176
+
177
+ /** The launch recorded at `record` failed or was refused before `before`: a
178
+ * launch failure fact, or an open `execution-no-progress` escalation, lies
179
+ * between them. Such a record never qualifies a later execution, which is an
180
+ * acknowledgement's (SPEC §12: an acknowledgement confers no slot). */
181
+ function launchEnded(
182
+ input: Pick<EscalationCarryInput, 'failures' | 'openEscalations'>,
183
+ record: number,
184
+ before: number,
185
+ ): boolean {
186
+ const between = (seq: number) => seq > record && seq < before
187
+ return (
188
+ input.failures.some((failures) => {
189
+ const last = failures.findLast((failure) => failure.seq < before)
190
+ return last !== undefined && last.seq > record
191
+ }) ||
192
+ input.openEscalations.some(
193
+ (escalation) => escalation.policyCause === 'execution-no-progress' && between(escalation.seq),
194
+ )
195
+ )
196
+ }
197
+
198
+ /** Whether work Autobuild started for a blocked build still runs, so its open
199
+ * escalations do not stop it and it keeps its slot (SPEC §12 "What holds a
200
+ * slot"). Pure reduced state: no lease, marker or clock enters. True when
201
+ * any of these holds:
202
+ *
203
+ * - (A) stage carry: every open escalation is an agent escalation without a
204
+ * ticket wait whose session owns a current-cycle verify member at the
205
+ * highest attempt, and some other member still runs. This models the
206
+ * engine's stage exemption (`heldVerifier` and the open-escalation gate in
207
+ * `engine.ts`), which keeps the stage's other members running; the two
208
+ * change together.
209
+ * - (E) held execution: the open execution was launched while the build held
210
+ * its slot (its launch record lies between the previous start and its own,
211
+ * and no failure or refusal ended that launch before it started).
212
+ * - (L) launch in flight (`launchInFlight`).
213
+ * - (B) the open execution started before the earliest open raise.
214
+ *
215
+ * Only (A) looks at escalations, as part of its own definition, apart from
216
+ * (L)'s progress-guard refusal, which is a launch failure: (E), (L) and (B)
217
+ * rest on durable launch and execution facts, which no question contradicts.
218
+ * Stale evidence (a crashed runner's open execution, a launch
219
+ * that died without a failure fact) over-holds a slot the build already
220
+ * held; it never takes a new one. */
221
+ export function escalationCarried(input: EscalationCarryInput): boolean {
222
+ return stageCarried(input) || executionCarried(input) || launchInFlight(input)
223
+ }
224
+
225
+ function stageCarried(input: EscalationCarryInput): boolean {
226
+ const { openEscalations, verifyStage, verifyCycle, maxAttemptSeen } = input
227
+ if (openEscalations.length === 0) return false
228
+ const held = new Set<string>()
229
+ for (const escalation of openEscalations) {
230
+ if (
231
+ escalation.source !== 'agent' ||
232
+ escalation.wait !== undefined ||
233
+ escalation.session === undefined
234
+ )
235
+ return false
236
+ const key = verifyStage.owners[escalation.session]
237
+ const member = key === undefined ? undefined : verifyStage.members[key]
238
+ if (
239
+ key === undefined ||
240
+ member === undefined ||
241
+ member.seq <= verifyCycle ||
242
+ key !== verifyMemberKey(member.step, maxAttemptSeen)
243
+ )
244
+ return false
245
+ held.add(key)
246
+ }
247
+ return runningVerifyMembers(verifyStage, verifyCycle).some(
248
+ (member) => !held.has(verifyMemberKey(member.step, member.attempt)),
249
+ )
250
+ }
251
+
252
+ function executionCarried(input: EscalationCarryInput): boolean {
253
+ const live = input.liveExecution
254
+ if (live === undefined) return false
255
+ const record = launchRecordSeq(input)
256
+ const previous = input.executions.findLast((execution) => execution.seq < live.seq)?.seq ?? 0
257
+ if (
258
+ record !== undefined &&
259
+ record > previous &&
260
+ record < live.seq &&
261
+ !launchEnded(input, record, live.seq)
262
+ )
263
+ return true
264
+ if (input.openEscalations.length === 0) return false
265
+ return live.seq < Math.min(...input.openEscalations.map((escalation) => escalation.seq))
266
+ }
@@ -23,6 +23,19 @@ export type {
23
23
  StepState,
24
24
  StepTiming,
25
25
  } from '../cli/dashboard/model'
26
+ export {
27
+ BUILD_STATUS_TONE,
28
+ HARVEST_STATUS_TONE,
29
+ buildStatusText,
30
+ harvestStatusText,
31
+ } from '../cli/dashboard/vocabulary'
32
+ export type {
33
+ BuildStatusWord,
34
+ DashboardTone,
35
+ HarvestStatusWord,
36
+ StatusBasis,
37
+ StatusText,
38
+ } from '../cli/dashboard/vocabulary'
26
39
  export { parseTranscript } from '../cli/dashboard/transcript'
27
40
  export type {
28
41
  TranscriptPresentation,
@@ -1,16 +1,15 @@
1
1
  import { normalizeEffectiveConfigArtifact } from '../config/effective-artifact'
2
- import { migrationIdentity } from '../kernel/ticket-migrations'
3
2
  import { enrichDrainingRow, projectHandoffs } from '../cli/dashboard/handoff'
4
3
  import { repositoryQueueDepth } from '../cli/dashboard/header'
5
4
  import { enrichIntegrationRows } from '../cli/dashboard/integration-row'
6
5
  import {
7
6
  dispatchCapacity,
8
- slotRequest,
9
7
  startClaimDemand,
10
8
  urgentClaimDemand,
11
9
  type CapacityBuild,
12
10
  } from '../kernel/dispatch-capacity'
13
11
  import { landingRestackDue } from '../kernel/engine'
12
+ import { capacityBuildFromFacts } from '../kernel/capacity-build'
14
13
  import { forgeReadinessWarnings } from '../kernel/dispatch-status'
15
14
  import { readBuildDigests } from '../store/reduced-reads'
16
15
  import {
@@ -88,6 +87,19 @@ export async function listOperatorBuilds(opts: {
88
87
  return withOperatorView(opts.store, opts.repo, 'builds', (view) => listFromView(view, opts))
89
88
  }
90
89
 
90
+ /** A node's provisioning marker, for capacity; a leaf reads none. */
91
+ async function nodeProvisioning(
92
+ view: RepoViewStore,
93
+ slug: string,
94
+ state: BuildState,
95
+ ): Promise<{ provisioning: boolean; provisioningSeq?: number }> {
96
+ if (state.kind !== 'node') return { provisioning: false }
97
+ const marker = (await readBuildFacts(view, slug)).value.provisionMarker
98
+ return marker === undefined
99
+ ? { provisioning: false }
100
+ : { provisioning: true, provisioningSeq: marker.seq }
101
+ }
102
+
91
103
  async function listFromView(
92
104
  view: RepoViewStore,
93
105
  opts: { repo: string; scope: BuildListScope; now: Date },
@@ -113,24 +125,14 @@ async function listFromView(
113
125
  for (const record of records) {
114
126
  if (record.repo !== opts.repo) continue
115
127
  const facts = await view.buildFacts(record.slug)
116
- const projected = summarizeFrom(
128
+ const projected = summarizeFrom(record, facts.state, opts.now, {
117
129
  record,
118
- facts.state,
119
- opts.now,
120
- slotRequest(
121
- {
122
- record,
123
- state: facts.state,
124
- workspace: facts.workspace !== null,
125
- // Leaves rely on the continuation's lease; only nodes read the marker.
126
- provisioning:
127
- facts.state.kind === 'node' &&
128
- (await readBuildFacts(view, record.slug)).value.provisionMarker !== undefined,
129
- restackDue: landingRestackDue(facts.state, facts.log),
130
- },
131
- opts.now,
132
- ),
133
- )
130
+ state: facts.state,
131
+ workspace: facts.workspace !== null,
132
+ // The marker anchors runners launched before durable node admission.
133
+ ...(await nodeProvisioning(view, record.slug, facts.state)),
134
+ restackDue: landingRestackDue(facts.state, facts.log),
135
+ })
134
136
  if (statuses.has(projected.status)) output.push(projected)
135
137
  }
136
138
  return output.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
@@ -343,10 +345,17 @@ export async function getOperatorBuild(opts: {
343
345
  }
344
346
  }
345
347
  }
346
- return {
347
- detail: detailFromFacts(record, facts, opts.now),
348
- dashboardRow,
349
- }
348
+ const detail = detailFromFacts(
349
+ record,
350
+ facts,
351
+ opts.now,
352
+ undefined,
353
+ undefined,
354
+ undefined,
355
+ capacityBuildFromFacts(record, facts),
356
+ )
357
+ if (dashboardRow && detail.slot) dashboardRow.slot = detail.slot
358
+ return { detail, dashboardRow }
350
359
  }
351
360
 
352
361
  export async function getRepositoryStatus(
@@ -435,9 +444,7 @@ async function dashboardFromView(
435
444
  record,
436
445
  state: facts.state,
437
446
  workspace: facts.workspace !== null,
438
- provisioning:
439
- facts.state.kind === 'node' &&
440
- (await readBuildFacts(view, record.slug)).value.provisionMarker !== undefined,
447
+ ...(await nodeProvisioning(view, record.slug, facts.state)),
441
448
  restackDue: landingRestackDue(facts.state, facts.log),
442
449
  })
443
450
  if (projectsNoDashboardRow(facts.state)) continue
@@ -459,20 +466,14 @@ async function dashboardFromView(
459
466
  ...forgeReadinessWarnings(status),
460
467
  ...(status.warningNotice !== undefined ? [status.warningNotice] : []),
461
468
  ]
462
- const capacityProjection = dispatchCapacity(
463
- capacityBuilds,
464
- config.capacity,
465
- opts.clock(),
466
- migrationIdentity(repositoryEvents.ticketMigrations, config.tickets.source),
467
- {
468
- urgentClaims: urgentClaimDemand(repositoryEvents),
469
- openPrs: {
470
- policy: config.policy,
471
- engaged: repositoryEvents.openPrBackpressure !== undefined,
472
- },
473
- startRequests: startClaimDemand(repositoryEvents),
469
+ const capacityProjection = dispatchCapacity(capacityBuilds, config.capacity, opts.clock(), {
470
+ urgentClaims: urgentClaimDemand(repositoryEvents),
471
+ openPrs: {
472
+ policy: config.policy,
473
+ engaged: repositoryEvents.openPrBackpressure !== undefined,
474
474
  },
475
- )
475
+ startRequests: startClaimDemand(repositoryEvents),
476
+ })
476
477
  const model = buildDashboardFromProjected(
477
478
  enrichIntegrationRows(projected, await integrationRecords(view, opts.repo, projected, records)),
478
479
  {