@defrex/autobuild 1.11.0 → 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 (110) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +186 -57
  3. package/docs/answering-blocked-builds.md +10 -2
  4. package/docs/architecture.md +76 -10
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +13 -11
  8. package/docs/dispatcher.md +5 -4
  9. package/docs/integration-tree.md +28 -16
  10. package/docs/operator-api.md +4 -4
  11. package/docs/operator-surfaces.md +38 -3
  12. package/docs/optimization-nodes.md +3 -2
  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/ambient-errors.ts +17 -0
  17. package/packages/core/src/cli/bounded-io.ts +174 -0
  18. package/packages/core/src/cli/dashboard/header.ts +10 -0
  19. package/packages/core/src/cli/dashboard/model.ts +81 -23
  20. package/packages/core/src/cli/dashboard/poll.ts +24 -34
  21. package/packages/core/src/cli/dashboard/render.ts +44 -37
  22. package/packages/core/src/cli/dashboard/row-text.ts +24 -7
  23. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  24. package/packages/core/src/cli/dashboard/vocabulary.ts +161 -20
  25. package/packages/core/src/cli/dispatch-frontend.ts +12 -3
  26. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  27. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  28. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  29. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  30. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  31. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  32. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  33. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  34. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  35. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  36. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  37. package/packages/core/src/cli/dispatch.ts +70 -9
  38. package/packages/core/src/cli/env.ts +2 -15
  39. package/packages/core/src/cli/help.ts +5 -4
  40. package/packages/core/src/cli/main.ts +4 -2
  41. package/packages/core/src/cli/production-store.ts +102 -0
  42. package/packages/core/src/cli/repo-state.ts +2 -3
  43. package/packages/core/src/cli/repository-status.ts +36 -28
  44. package/packages/core/src/cli/sessionless-store.ts +26 -0
  45. package/packages/core/src/cli/status.ts +169 -40
  46. package/packages/core/src/cli/store-opening.ts +15 -58
  47. package/packages/core/src/cli/store-ref.ts +6 -1
  48. package/packages/core/src/config/schema.ts +1 -1
  49. package/packages/core/src/distribution-packaging.ts +156 -18
  50. package/packages/core/src/events/catalog-identity.ts +28 -0
  51. package/packages/core/src/events/catalog.ts +3 -9
  52. package/packages/core/src/events/compatibility.ts +2 -30
  53. package/packages/core/src/events/payloads.ts +11 -0
  54. package/packages/core/src/events/policy.ts +3 -0
  55. package/packages/core/src/events/repository.ts +1 -1
  56. package/packages/core/src/events/sessions.ts +1 -1
  57. package/packages/core/src/events/validation-error.ts +12 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +74 -30
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/46196d8f0076496a.json +97 -0
  61. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  62. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  63. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  64. package/packages/core/src/kernel/capacity-build.ts +21 -0
  65. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  66. package/packages/core/src/kernel/dispatch-capacity.ts +354 -147
  67. package/packages/core/src/kernel/dispatch-status.ts +139 -0
  68. package/packages/core/src/kernel/engine.ts +2 -8
  69. package/packages/core/src/kernel/measurement.ts +24 -0
  70. package/packages/core/src/kernel/read-facts.ts +9 -369
  71. package/packages/core/src/kernel/reducer-registry.ts +40 -125
  72. package/packages/core/src/kernel/reducer-revisions.ts +5 -0
  73. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  74. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  75. package/packages/core/src/kernel/reducer.ts +57 -9
  76. package/packages/core/src/kernel/reopen-state.ts +10 -0
  77. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  78. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  79. package/packages/core/src/operator/presentation.ts +13 -0
  80. package/packages/core/src/operator/query.ts +47 -41
  81. package/packages/core/src/operator/registry.ts +3 -3
  82. package/packages/core/src/ports/workspace/fake.ts +15 -3
  83. package/packages/core/src/processes/dispatcher.ts +232 -75
  84. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  85. package/packages/core/src/store/local/capabilities.ts +115 -0
  86. package/packages/core/src/store/local/store.ts +86 -56
  87. package/packages/core/src/store/reduced-reads.ts +9 -1
  88. package/packages/core/src/store/reducer-value-read.ts +235 -0
  89. package/packages/core/src/store/reducer-value-shapes.json +3796 -3670
  90. package/packages/core/src/store/reducer-values.ts +36 -204
  91. package/packages/core/src/store/remote/released-clients.json +22 -0
  92. package/packages/core/src/store/remote/released-reducer-values/1.11.1.json +35718 -0
  93. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  94. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  95. package/packages/core/src/store/rollup-lease.ts +41 -0
  96. package/packages/core/src/store/rollups.ts +7 -38
  97. package/packages/core/src/store/snapshots.ts +1 -1
  98. package/packages/core/src/testing/dispatch-journals.ts +117 -0
  99. package/packages/core/src/testing/dispatch-read-budget.ts +265 -4
  100. package/packages/core/src/testing/import-graph.ts +78 -0
  101. package/packages/core/src/testing/reduced-read-budget.ts +221 -22
  102. package/packages/core/src/testing/slot-agreement.ts +52 -0
  103. package/packages/core/src/web/assets/app.js +5 -5
  104. package/packages/core/src/web/repository-source.ts +6 -2
  105. package/skills/guide/SKILL.md +126 -47
  106. package/skills/guide/references/integration-tree.md +28 -16
  107. package/skills/guide/references/operator-api.md +4 -4
  108. package/skills/guide/references/optimization-nodes.md +3 -2
  109. package/skills/operate/SKILL.md +38 -20
  110. package/templates/hosted-service/package.json +2 -2
@@ -22,16 +22,14 @@ import {
22
22
  repositoryReadFactsReducer,
23
23
  optionalValue,
24
24
  } from './read-facts'
25
- import { validateAccumulator, encodeReducerValue } from '../store/reducer-value-validation'
26
25
  import {
27
26
  effectiveConfigReducer,
28
27
  buildDelegationReducer,
29
28
  harvestDelegationReducer,
30
29
  } from './service-facts'
31
- import { phaseSchema } from '../ontology'
32
- import { z } from 'zod'
33
30
  import { dispatchPlacementReducer } from './dispatch-placement'
34
31
  import type { ValueCatalogEntry } from '../store/reducer-values'
32
+ import { valueReadEntry, type RegisteredReducer } from './reducer-value-entry'
35
33
  import { dispatchFrontendReducer } from '../cli/dispatch-repository-feed'
36
34
  import { executionNoProgressReducer } from '../processes/execution-no-progress'
37
35
  import { summaryBoundaryReducer, summaryRequestsReducer } from './pr-summary'
@@ -79,7 +77,6 @@ import { currentDeferralObservationReducer } from './auto-merge'
79
77
  import { dispatchSettingsReducer } from './dispatch-settings'
80
78
  import { dispatchStatusReducer } from './dispatch-status'
81
79
  import { harvestReducer } from './harvest'
82
- import type { IncrementalReducer } from './incremental'
83
80
  import { logIndexReducer } from './log-index'
84
81
  import {
85
82
  currentPrAttachmentsReducer,
@@ -91,13 +88,7 @@ import { buildReducer } from './reducer'
91
88
  import type { AnyRollupDefinition } from './rollup'
92
89
  import { stepDurationsRollup } from './step-durations'
93
90
 
94
- export interface RegisteredReducer {
95
- valueRead: ValueCatalogEntry | { excluded: string }
96
- // biome-ignore lint/suspicious/noExplicitAny: the registry is heterogeneous
97
- reducer: IncrementalReducer<any, any, any>
98
- /** The whole-array functions (or private methods) this reducer backs. */
99
- covers: readonly string[]
100
- }
91
+ export type { RegisteredReducer } from './reducer-value-entry'
101
92
 
102
93
  /** Parameterized reducers are registered with representative arguments; the
103
94
  * accumulator shape does not depend on them. */
@@ -216,80 +207,16 @@ const REGISTERED: Record<string, Omit<RegisteredReducer, 'valueRead'>> = {
216
207
  dispatchPlacement: { reducer: dispatchPlacementReducer, covers: [] },
217
208
  }
218
209
 
219
- /** Qualification concerns the existing finished contract, including absence. */
220
- const valueExclusions: Record<string, string> = {
221
- dispatchFrontend: 'returns a list of raw repository journal events',
222
- journalView: 'returns a list of raw repository journal events',
223
- repositoryStateEvents: 'returns a list of raw repository journal events',
224
- session: 'consumes operator-session logs rather than build or repository events',
225
- publicationState: 'finished value contains executable selector functions',
226
- logIndex: 'finished value contains Maps and Sets',
227
- hostedPrAttachments: 'finished value is a Map',
228
- ...Object.fromEntries(
229
- [
230
- 'summaryBoundary',
231
- 'ticketSourceHealth',
232
- 'frozenPrImageHost',
233
- 'publishedBranchHead',
234
- 'verifyDiffBase',
235
- 'recordedBaseSha',
236
- 'baseBranch',
237
- 'provisionMarker',
238
- 'recoveryCheckpoint',
239
- ].map((name) => [name, 'finished contract can return top-level undefined, which is not JSON']),
240
- ),
241
- }
242
- const repositoryValues = new Set([
243
- 'dispatchPlacement',
244
- 'ticketPreparation',
245
- 'ticketHandbacks',
246
- 'ticketStarts',
247
- 'ticketMigrations',
248
- 'forgeHealthValue',
249
- 'repositoryReadFacts',
250
- 'dispatchUpgrade',
251
- 'dispatcherRunFacts',
252
- 'repositoryAttention',
253
- 'effectiveConfig',
254
- 'harvestDelegation',
255
- 'harvest',
256
- 'dispatchSettings',
257
- 'dispatchStatus',
258
- 'sandboxStates',
259
- 'openHarvestExecutions',
260
- 'hostedHarvestAuthority',
261
- 'openTick',
262
- 'autoMergeDefault',
263
- ])
264
- const noArgs = z.object({}).strict()
265
- const parameterized: Record<string, Pick<ValueCatalogEntry, 'args' | 'create'>> = {
266
- terminalGuard: {
267
- args: z
268
- .object({ phase: phaseSchema, round: z.number().int(), session: z.string().min(1) })
269
- .strict(),
270
- create: (args) => terminalGuardReducer(args),
271
- },
272
- dispatchStatus: {
273
- args: z.object({ run: z.string().min(1) }).strict(),
274
- create: ({ run }) => dispatchStatusReducer(run),
275
- },
276
- dispatcherRunFacts: {
277
- args: z.object({ run: z.string().min(1) }).strict(),
278
- create: ({ run }) => dispatcherRunFactsReducer(run),
279
- },
280
- openTick: {
281
- args: z.object({ run: z.string().min(1) }).strict(),
282
- create: ({ run }) => openTickReducer(run),
283
- },
284
- dispatchFailureBudget: {
285
- args: z.object({ infrastructureOwnsWorkspace: z.boolean() }).strict(),
286
- create: ({ infrastructureOwnsWorkspace }) =>
287
- dispatchFailureBudgetReducer(infrastructureOwnsWorkspace),
288
- },
289
- phaseFailures: {
290
- args: z.object({ phase: phaseSchema, round: z.number().int().nonnegative() }).strict(),
291
- create: ({ phase, round }) => phaseFailuresReducer(phase, round),
292
- },
210
+ /** Constructors of the parameterized reducers; `parameterizedArgs` holds their
211
+ * argument schemas. */
212
+ const parameterizedCreate: Record<string, ValueCatalogEntry['create']> = {
213
+ terminalGuard: (args) => terminalGuardReducer(args),
214
+ dispatchStatus: ({ run }) => dispatchStatusReducer(run),
215
+ dispatcherRunFacts: ({ run }) => dispatcherRunFactsReducer(run),
216
+ openTick: ({ run }) => openTickReducer(run),
217
+ dispatchFailureBudget: ({ infrastructureOwnsWorkspace }) =>
218
+ dispatchFailureBudgetReducer(infrastructureOwnsWorkspace),
219
+ phaseFailures: ({ phase, round }) => phaseFailuresReducer(phase, round),
293
220
  }
294
221
  /** The node slugs one digest row names: a `build.created` target, or either
295
222
  * side of a node parent move. Undecodable payloads name none. */
@@ -361,51 +288,39 @@ function digestTicketWaitOf(
361
288
  return {}
362
289
  }
363
290
 
291
+ /** The build digest folds compact rows rather than whole events. */
292
+ function adaptDigestRows(events: Parameters<ValueCatalogEntry['adapt']>[0]) {
293
+ return events.map((event) => ({
294
+ ...(decodeStoredEvent(event) === null ? { rawUnknown: event } : {}),
295
+ type: event.type,
296
+ seq: event.seq,
297
+ ts: event.ts,
298
+ ...(event.payload !== null && typeof event.payload === 'object' && 'hostedSeq' in event.payload
299
+ ? { hostedSeq: event.payload.hostedSeq }
300
+ : {}),
301
+ ...(event.type === 'integration.landed' ? { auditRequested: !!event.payload.operation } : {}),
302
+ ...(event.type === 'pr.merged' ? { mergedSha: event.payload.sha } : {}),
303
+ ...(event.type === 'node.contribution-recorded' ? { nodeContribution: event.payload } : {}),
304
+ ...(event.type === 'build.created' ? { kind: event.payload.kind } : {}),
305
+ ...digestNodeTargetsOf(event),
306
+ ...(event.payload !== null && typeof event.payload === 'object' && 'instance' in event.payload
307
+ ? { instance: event.payload.instance }
308
+ : {}),
309
+ ...digestTicketWaitOf(event),
310
+ ...digestAttemptOf(event),
311
+ ...digestOptimizationOf(event),
312
+ }))
313
+ }
314
+
364
315
  export const REDUCERS: Record<string, RegisteredReducer> = Object.fromEntries(
365
316
  Object.entries(REGISTERED).map(([name, entry]) => [
366
317
  name,
367
318
  {
368
319
  ...entry,
369
- valueRead: valueExclusions[name]
370
- ? { excluded: valueExclusions[name] }
371
- : {
372
- scope: repositoryValues.has(name) ? 'repo' : 'build',
373
- args: parameterized[name]?.args ?? noArgs,
374
- validate: (state: unknown) => validateAccumulator(name, state),
375
- value: encodeReducerValue,
376
- adapt: (events: Parameters<ValueCatalogEntry['adapt']>[0]) =>
377
- name === 'buildDigest'
378
- ? events.map((event) => ({
379
- ...(decodeStoredEvent(event) === null ? { rawUnknown: event } : {}),
380
- type: event.type,
381
- seq: event.seq,
382
- ts: event.ts,
383
- ...(event.payload !== null &&
384
- typeof event.payload === 'object' &&
385
- 'hostedSeq' in event.payload
386
- ? { hostedSeq: event.payload.hostedSeq }
387
- : {}),
388
- ...(event.type === 'integration.landed'
389
- ? { auditRequested: !!event.payload.operation }
390
- : {}),
391
- ...(event.type === 'pr.merged' ? { mergedSha: event.payload.sha } : {}),
392
- ...(event.type === 'node.contribution-recorded'
393
- ? { nodeContribution: event.payload }
394
- : {}),
395
- ...(event.type === 'build.created' ? { kind: event.payload.kind } : {}),
396
- ...digestNodeTargetsOf(event),
397
- ...(event.payload !== null &&
398
- typeof event.payload === 'object' &&
399
- 'instance' in event.payload
400
- ? { instance: event.payload.instance }
401
- : {}),
402
- ...digestTicketWaitOf(event),
403
- ...digestAttemptOf(event),
404
- ...digestOptimizationOf(event),
405
- }))
406
- : events,
407
- create: parameterized[name]?.create ?? (() => entry.reducer),
408
- },
320
+ valueRead: valueReadEntry(name, entry.reducer, {
321
+ ...(parameterizedCreate[name] ? { create: parameterizedCreate[name] } : {}),
322
+ ...(name === 'buildDigest' ? { adapt: adaptDigestRows } : {}),
323
+ }),
409
324
  },
410
325
  ]),
411
326
  )
@@ -72,4 +72,9 @@ export const REDUCER_REVISIONS: Readonly<Record<string, string>> = {
72
72
  'leafRestack/fold/5zq9n2zlit': '#1274 rewritten-target reprovision, accept waiver, episodes',
73
73
  'logIndex/fold/bwl7r7gjae': '#1274 rewritten-target reprovision, accept waiver, episodes',
74
74
  'verifyDiffBase/fold/p2si2x55v7': '#1274 rewritten-target reprovision, accept waiver, episodes',
75
+ 'repositoryReadFacts/shape/mggr8x6l5z': '#1279 reported dispatcher run tracks pending runs',
76
+ 'repositoryReadFacts/fold/vvcfmd23zp': '#1279 status describes the authority run',
77
+ 'build/shape/rclfl10h8j': 'Durable slot admission and release seqs (SPEC §12 What holds a slot)',
78
+ 'build/shape/i4uoqi67lx': 'Node slot admission names its need (#1340)',
79
+ 'build/fold/4hkypq2buv': '#1348 answers release a slot only when the build was not carried',
75
80
  }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The value-read entry every registered reducer is served through, built
3
+ * without the complete catalog. `reducer-registry.ts` builds `REDUCERS` with
4
+ * `valueReadEntry`, and `reducer-value-index.ts` builds the selectively loaded
5
+ * registrations with it, so both produce identical entries.
6
+ */
7
+ import { z } from 'zod'
8
+ import { phaseSchema } from '../ontology'
9
+ import { validateAccumulator, encodeReducerValue } from '../store/reducer-value-validation'
10
+ import type { ValueCatalogEntry } from '../store/reducer-value-read'
11
+ import type { IncrementalReducer } from './incremental'
12
+
13
+ export interface RegisteredReducer {
14
+ valueRead: ValueCatalogEntry | { excluded: string }
15
+ // biome-ignore lint/suspicious/noExplicitAny: the registry is heterogeneous
16
+ reducer: IncrementalReducer<any, any, any>
17
+ /** The whole-array functions (or private methods) this reducer backs. */
18
+ covers: readonly string[]
19
+ }
20
+
21
+ /** Qualification concerns the existing finished contract, including absence. */
22
+ export const valueExclusions: Record<string, string> = {
23
+ dispatchFrontend: 'returns a list of raw repository journal events',
24
+ journalView: 'returns a list of raw repository journal events',
25
+ repositoryStateEvents: 'returns a list of raw repository journal events',
26
+ session: 'consumes operator-session logs rather than build or repository events',
27
+ publicationState: 'finished value contains executable selector functions',
28
+ logIndex: 'finished value contains Maps and Sets',
29
+ hostedPrAttachments: 'finished value is a Map',
30
+ ...Object.fromEntries(
31
+ [
32
+ 'summaryBoundary',
33
+ 'ticketSourceHealth',
34
+ 'frozenPrImageHost',
35
+ 'publishedBranchHead',
36
+ 'verifyDiffBase',
37
+ 'recordedBaseSha',
38
+ 'baseBranch',
39
+ 'provisionMarker',
40
+ 'recoveryCheckpoint',
41
+ ].map((name) => [name, 'finished contract can return top-level undefined, which is not JSON']),
42
+ ),
43
+ }
44
+ export const repositoryValues = new Set([
45
+ 'dispatchPlacement',
46
+ 'ticketPreparation',
47
+ 'ticketHandbacks',
48
+ 'ticketStarts',
49
+ 'ticketMigrations',
50
+ 'forgeHealthValue',
51
+ 'repositoryReadFacts',
52
+ 'dispatchUpgrade',
53
+ 'dispatcherRunFacts',
54
+ 'repositoryAttention',
55
+ 'effectiveConfig',
56
+ 'harvestDelegation',
57
+ 'harvest',
58
+ 'dispatchSettings',
59
+ 'dispatchStatus',
60
+ 'sandboxStates',
61
+ 'openHarvestExecutions',
62
+ 'hostedHarvestAuthority',
63
+ 'openTick',
64
+ 'autoMergeDefault',
65
+ ])
66
+ export const noArgs = z.object({}).strict()
67
+ const run = z.object({ run: z.string().min(1) }).strict()
68
+ /** Arguments of the parameterized reducers; their `create` functions stay with
69
+ * the reducer modules that construct them. */
70
+ export const parameterizedArgs: Record<string, z.ZodType> = {
71
+ terminalGuard: z
72
+ .object({ phase: phaseSchema, round: z.number().int(), session: z.string().min(1) })
73
+ .strict(),
74
+ dispatchStatus: run,
75
+ dispatcherRunFacts: run,
76
+ openTick: run,
77
+ dispatchFailureBudget: z.object({ infrastructureOwnsWorkspace: z.boolean() }).strict(),
78
+ phaseFailures: z.object({ phase: phaseSchema, round: z.number().int().nonnegative() }).strict(),
79
+ }
80
+
81
+ /** One registered reducer's value-read entry. */
82
+ export function valueReadEntry(
83
+ name: string,
84
+ // biome-ignore lint/suspicious/noExplicitAny: the registry is heterogeneous
85
+ reducer: IncrementalReducer<any, any, any>,
86
+ options: Partial<Pick<ValueCatalogEntry, 'create' | 'adapt'>> = {},
87
+ ): RegisteredReducer['valueRead'] {
88
+ const excluded = valueExclusions[name]
89
+ if (excluded) return { excluded }
90
+ return {
91
+ scope: repositoryValues.has(name) ? 'repo' : 'build',
92
+ args: parameterizedArgs[name] ?? noArgs,
93
+ validate: (state: unknown) => validateAccumulator(name, state),
94
+ value: encodeReducerValue,
95
+ adapt: options.adapt ?? ((events) => events),
96
+ create: options.create ?? (() => reducer),
97
+ }
98
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Selective reducer lookup for value reads. The reducers short-lived readers
3
+ * request load only their own modules; every other name resolves through the
4
+ * complete `REDUCERS` catalog, loaded on first need. Both paths build entries
5
+ * with `valueReadEntry`, so identities, keys and validation are identical
6
+ * (`reducer-value-index.test.ts` pins each selective registration to its
7
+ * catalog entry). This module must never import the registry statically.
8
+ */
9
+ import { valueReadEntry, type RegisteredReducer } from './reducer-value-entry'
10
+
11
+ type Loader = () => Promise<RegisteredReducer>
12
+
13
+ /** Names whose registration is built from the reducer module alone. `covers`
14
+ * and representative arguments match `REGISTERED`. */
15
+ const SELECTIVE: Record<string, Loader> = {
16
+ dispatchUpgrade: async () => {
17
+ const { dispatchUpgradeReducer } = await import('./dispatch-upgrade')
18
+ return registration('dispatchUpgrade', dispatchUpgradeReducer)
19
+ },
20
+ repositoryReadFacts: async () => {
21
+ const { repositoryReadFactsReducer } = await import('./repository-read-facts')
22
+ return registration('repositoryReadFacts', repositoryReadFactsReducer)
23
+ },
24
+ dispatcherRunFacts: async () => {
25
+ const { dispatcherRunFactsReducer } = await import('./repository-read-facts')
26
+ return registration('dispatcherRunFacts', dispatcherRunFactsReducer('run-a'), {
27
+ create: ({ run }) => dispatcherRunFactsReducer(run),
28
+ })
29
+ },
30
+ }
31
+ export const SELECTIVE_VALUE_REGISTRATIONS: readonly string[] = Object.keys(SELECTIVE)
32
+
33
+ function registration(
34
+ name: string,
35
+ reducer: RegisteredReducer['reducer'],
36
+ options?: Parameters<typeof valueReadEntry>[2],
37
+ ): RegisteredReducer {
38
+ return { reducer, covers: [], valueRead: valueReadEntry(name, reducer, options) }
39
+ }
40
+
41
+ const loaded = new Map<string, Promise<RegisteredReducer>>()
42
+ const settled = new Map<string, RegisteredReducer>()
43
+ let catalog: Record<string, RegisteredReducer> | undefined
44
+
45
+ /** The registration `name` resolves to, or `undefined` for an unknown name. */
46
+ export async function loadValueRegistration(name: string): Promise<RegisteredReducer | undefined> {
47
+ if (!Object.hasOwn(SELECTIVE, name)) {
48
+ catalog ??= (await import('./reducer-registry')).REDUCERS
49
+ return Object.hasOwn(catalog, name) ? catalog[name] : undefined
50
+ }
51
+ let pending = loaded.get(name)
52
+ if (!pending) {
53
+ pending = SELECTIVE[name]!().then(
54
+ (registration) => {
55
+ settled.set(name, registration)
56
+ return registration
57
+ },
58
+ (error: unknown) => {
59
+ loaded.delete(name)
60
+ throw error
61
+ },
62
+ )
63
+ loaded.set(name, pending)
64
+ }
65
+ return pending
66
+ }
67
+
68
+ /** The answer `loadValueRegistration(name)` would give, synchronously, once
69
+ * the module it needs has loaded; `null` while it has not. A warm read then
70
+ * resolves with no added await, so its timing matches the static catalog. */
71
+ export function loadedValueRegistration(name: string): RegisteredReducer | undefined | null {
72
+ if (Object.hasOwn(SELECTIVE, name)) return settled.get(name) ?? null
73
+ if (!catalog) return null
74
+ return Object.hasOwn(catalog, name) ? catalog[name] : undefined
75
+ }
@@ -2,6 +2,7 @@ import type { SelectedAccount } from '../config/accounts'
2
2
  import { foldHeadPaths, type HeadPathsSummary } from './head-paths-state'
3
3
  import {
4
4
  advanceVerifyStage,
5
+ escalationCarried,
5
6
  initialVerifyStageState,
6
7
  verifyMemberKey,
7
8
  runningVerifyMembers,
@@ -458,6 +459,23 @@ export interface BuildState {
458
459
  * `wait awaiting-pr` decision (`pipeline.settled`); capacity evidence only,
459
460
  * never a pipeline decision input. */
460
461
  pipelineSettled?: number
462
+ /** seq of the latest admission into a slot: the build's `build.created` or
463
+ * the dispatcher's `slot.admitted` (SPEC §12 "What holds a slot"). Runner
464
+ * allocation never admits. Capacity evidence only. Omitted for an empty
465
+ * log, and by an older server. */
466
+ slotAdmittedSeq?: number
467
+ /** seq of the latest fact that released the slot or ended an outside wait
468
+ * whose runner must be admitted again: `pipeline.settled`, an answer that
469
+ * closes an open escalation while the build is not carried
470
+ * (`escalationCarried`), such a `wait.ended`, and `build.paused` (SPEC §12
471
+ * "What holds a slot"). Capacity evidence only. Omitted until one lands,
472
+ * and by an older server. */
473
+ slotReleasedSeq?: number
474
+ /** The node runner need the latest `slot.admitted` named (SPEC §12 "What
475
+ * holds a slot"): a node holds its slot while that need remains. Cleared by
476
+ * an admission that names none; `build.created` sets none. Capacity
477
+ * evidence only. */
478
+ slotAdmittedNeed?: string
461
479
  /** Full-log `finalize.step-completed` facts, in event order (§5).
462
480
  * Post-steps are failure-tolerant, so a completion counts whether `ok` is
463
481
  * true or false. Current-spec membership is determined by
@@ -593,15 +611,7 @@ export interface BuildState {
593
611
  failures: Record<string, number>
594
612
  }
595
613
 
596
- /** Whether the build carries an outstanding `discardRequest`. Present exactly
597
- * while the build is non-terminal and its discard is unsettled; the reducer
598
- * settles it only by terminal completion. This is the single predicate shared
599
- * by the auto-merge default fan-out (`autoMergeDefaultEligible`, AUT-418) and
600
- * the per-build consent guard (`controlBuild`'s `discard-pending` refusal), so
601
- * the two controls' discard exclusions cannot diverge silently. */
602
- export function discardInFlight(state: Pick<BuildState, 'discardRequest'>): boolean {
603
- return state.discardRequest !== undefined
604
- }
614
+ export { discardInFlight } from './discard-in-flight'
605
615
 
606
616
  /** The reducer's carried accumulator: everything `reduceBuild` folds, before
607
617
  * the final status derivation. Plain JSON-shaped data (the escalation and
@@ -694,6 +704,9 @@ export interface BuildAcc {
694
704
  priority?: TicketPriority
695
705
  finalizeCompletedSeq: number
696
706
  pipelineSettled?: number
707
+ slotAdmittedSeq?: number
708
+ slotReleasedSeq?: number
709
+ slotAdmittedNeed?: string
697
710
  finalizeSteps: BuildState['finalizeSteps']
698
711
  plan: BuildState['plan']
699
712
  implement: BuildState['implement']
@@ -773,6 +786,13 @@ function initialBuildAcc(): BuildAcc {
773
786
  function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
774
787
  advanceCompatibility(acc.compatibility, events)
775
788
  events = projectEvents(events)
789
+ // The open execution as of each event, for the answer fold's carry: read
790
+ // before the pre-pass below marks this batch's ended instances.
791
+ const latestExecution = acc.executions.at(-1)
792
+ let liveExecution =
793
+ latestExecution && !acc.endedExecutionInstances[latestExecution.instance]
794
+ ? latestExecution
795
+ : undefined
776
796
  for (const event of events) {
777
797
  if (event.type === 'build.compatibility-deferred')
778
798
  acc.compatibilityDeferredBoundary = event.payload.boundary
@@ -853,6 +873,19 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
853
873
  const suspended = new Map(acc.suspendedSessions.map((s) => [s.session, s]))
854
874
  const openSessions = new Map(acc.openSessions.map((s) => [s.session, s]))
855
875
  const failures = acc.failures
876
+ /** Work Autobuild started still outruns the open escalations, as of the
877
+ * event being folded: an answer then releases nothing (SPEC §12). */
878
+ const carried = () =>
879
+ escalationCarried({
880
+ openEscalations: [...openEscalations.values()],
881
+ verifyStage: acc.verifyStage,
882
+ verifyCycle: verify.cycleSince,
883
+ maxAttemptSeen: verify.maxAttemptSeen,
884
+ executions,
885
+ liveExecution,
886
+ slotAdmittedSeq: acc.slotAdmittedSeq,
887
+ failures: [dispatchFailures, infrastructureFailures, setupFailures],
888
+ })
856
889
 
857
890
  const start = (ctx: PhaseContext): void => {
858
891
  currentPhase = ctx
@@ -1079,6 +1112,7 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1079
1112
  prState = 'open'
1080
1113
  break
1081
1114
  case 'build.created':
1115
+ acc.slotAdmittedSeq = event.seq
1082
1116
  acc.kind = event.payload.kind
1083
1117
  acc.target = event.payload.target
1084
1118
  acc.baseBranch = event.payload.baseBranch
@@ -1196,9 +1230,11 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1196
1230
  break
1197
1231
  case 'execution.started':
1198
1232
  executions.push({ ...event.payload, seq: event.seq })
1233
+ liveExecution = executions.at(-1)
1199
1234
  infrastructureFailure = undefined
1200
1235
  break
1201
1236
  case 'execution.ended':
1237
+ if (liveExecution?.instance === event.payload.instance) liveExecution = undefined
1202
1238
  infrastructureFailure = undefined
1203
1239
  break
1204
1240
  case 'infrastructure.failed': {
@@ -1276,6 +1312,7 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1276
1312
  }
1277
1313
  break
1278
1314
  case 'build.paused':
1315
+ acc.slotReleasedSeq = event.seq
1279
1316
  pausedFlag = true
1280
1317
  pending.pause = []
1281
1318
  break
@@ -1592,6 +1629,12 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1592
1629
  break
1593
1630
  case 'pipeline.settled':
1594
1631
  acc.pipelineSettled = Math.max(acc.pipelineSettled ?? 0, event.payload.cycle)
1632
+ acc.slotReleasedSeq = event.seq
1633
+ break
1634
+ case 'slot.admitted':
1635
+ acc.slotAdmittedSeq = event.seq
1636
+ if (event.payload.need !== undefined) acc.slotAdmittedNeed = event.payload.need
1637
+ else delete acc.slotAdmittedNeed
1595
1638
  break
1596
1639
  case 'finalize.step-completed':
1597
1640
  // §5: post-steps are independent and failure-tolerant — a completion
@@ -1810,6 +1853,7 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1810
1853
  const wait = acc.wait
1811
1854
  if (wait?.id !== event.payload.id || wait.ended) break
1812
1855
  wait.ended = { cause: event.payload.cause, seq: event.seq, message: event.payload.message }
1856
+ if (!carried()) acc.slotReleasedSeq = event.seq
1813
1857
  const open = openEscalations.get(wait.escalation)
1814
1858
  if (open) {
1815
1859
  openEscalations.delete(open.id)
@@ -1881,6 +1925,7 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1881
1925
  // with no open raise is ignored (total over any prefix).
1882
1926
  const open = openEscalations.get(event.payload.id)
1883
1927
  if (open) {
1928
+ if (!carried()) acc.slotReleasedSeq = event.seq
1884
1929
  openEscalations.delete(event.payload.id)
1885
1930
  answeredEscalations.push({
1886
1931
  ...open,
@@ -2047,6 +2092,9 @@ function finishBuild(acc: BuildAcc): BuildState {
2047
2092
  autoMerge: acc.autoMerge,
2048
2093
  finalizeCompletedSeq: acc.finalizeCompletedSeq,
2049
2094
  ...(acc.pipelineSettled !== undefined ? { pipelineSettled: acc.pipelineSettled } : {}),
2095
+ ...(acc.slotAdmittedSeq !== undefined ? { slotAdmittedSeq: acc.slotAdmittedSeq } : {}),
2096
+ ...(acc.slotReleasedSeq !== undefined ? { slotReleasedSeq: acc.slotReleasedSeq } : {}),
2097
+ ...(acc.slotAdmittedNeed !== undefined ? { slotAdmittedNeed: acc.slotAdmittedNeed } : {}),
2050
2098
  finalizeSteps: acc.finalizeSteps,
2051
2099
  lastEvent,
2052
2100
  lastSeq: Math.max(lastEvent?.seq ?? 0, acc.compatibility.lastSeq),
@@ -42,6 +42,16 @@ export function reopenUnsettled(
42
42
  )
43
43
  }
44
44
 
45
+ /** An answered `revise-spec` escalation still waits for its revision: no
46
+ * `spec.revised` has landed since the answer (§6.3). */
47
+ export function reviseSpecPending(
48
+ state: Pick<BuildState, 'answeredEscalations' | 'restartSince'>,
49
+ ): boolean {
50
+ return state.answeredEscalations.some(
51
+ (e) => e.resolution === 'revise-spec' && e.answeredSeq > state.restartSince,
52
+ )
53
+ }
54
+
45
55
  /** Where a reopen sends the leaf. */
46
56
  export function reopenRoute(reopen: NonNullable<BuildState['reopen']>): 'implement' | 'plan' {
47
57
  return reopen.spec !== undefined ? 'plan' : 'implement'