@defrex/autobuild 1.0.0-beta.2 → 1.0.0-beta.4

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 (145) hide show
  1. package/SPEC.md +342 -23
  2. package/bin/ab-dispatch-generation.ts +93 -0
  3. package/docs/answering-blocked-builds.md +21 -3
  4. package/docs/architecture.md +170 -7
  5. package/docs/configuration.md +173 -5
  6. package/docs/integration-tree.md +91 -4
  7. package/docs/integration.md +54 -0
  8. package/docs/operator-api.md +58 -5
  9. package/docs/remote-store-protocol.md +9 -1
  10. package/docs/remote-ticket-protocol.md +5 -0
  11. package/docs/restacking.md +4 -1
  12. package/docs/setup.md +24 -0
  13. package/docs/spec-standard.md +94 -5
  14. package/docs/ticket-migration.md +50 -4
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/artifact.ts +5 -4
  17. package/packages/core/src/cli/attention.ts +2 -0
  18. package/packages/core/src/cli/binary-direct.ts +190 -0
  19. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  20. package/packages/core/src/cli/binary.ts +24 -210
  21. package/packages/core/src/cli/build-control.ts +108 -5
  22. package/packages/core/src/cli/context.ts +41 -1
  23. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  24. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  25. package/packages/core/src/cli/dashboard/integration-detail.ts +11 -6
  26. package/packages/core/src/cli/dashboard/integration-row.ts +15 -8
  27. package/packages/core/src/cli/dashboard/model.ts +41 -10
  28. package/packages/core/src/cli/dashboard/render.ts +24 -2
  29. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  30. package/packages/core/src/cli/dispatch-args.ts +53 -0
  31. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  32. package/packages/core/src/cli/dispatch-frontend.ts +57 -5
  33. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  34. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  35. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  36. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  38. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  39. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  40. package/packages/core/src/cli/dispatch-process.ts +22 -90
  41. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +6 -1
  43. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  44. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  45. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  46. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  47. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  48. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  49. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  50. package/packages/core/src/cli/dispatch.ts +609 -60
  51. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  52. package/packages/core/src/cli/harvest.ts +28 -11
  53. package/packages/core/src/cli/help.ts +7 -3
  54. package/packages/core/src/cli/installation.ts +5 -3
  55. package/packages/core/src/cli/main-checkout.ts +59 -0
  56. package/packages/core/src/cli/main.ts +26 -53
  57. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  58. package/packages/core/src/cli/repo-state.ts +3 -58
  59. package/packages/core/src/cli/repository-status.ts +74 -4
  60. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  61. package/packages/core/src/cli/status.ts +57 -3
  62. package/packages/core/src/cli/ticket.ts +35 -11
  63. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  64. package/packages/core/src/cli/wait.ts +3 -0
  65. package/packages/core/src/cli/watch.ts +7 -0
  66. package/packages/core/src/config/live.ts +1 -0
  67. package/packages/core/src/config/schema.ts +8 -4
  68. package/packages/core/src/distribution-packaging.ts +116 -0
  69. package/packages/core/src/events/catalog.ts +6 -0
  70. package/packages/core/src/events/payloads.ts +55 -9
  71. package/packages/core/src/events/policy.ts +26 -0
  72. package/packages/core/src/events/repository.ts +205 -4
  73. package/packages/core/src/events/runtime.ts +16 -0
  74. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +6537 -4053
  75. package/packages/core/src/kernel/change-presence.ts +7 -1
  76. package/packages/core/src/kernel/dispatch-capacity.ts +12 -4
  77. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  78. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  79. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  80. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  81. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  82. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  83. package/packages/core/src/kernel/harvest.ts +98 -4
  84. package/packages/core/src/kernel/integration-attention.ts +20 -0
  85. package/packages/core/src/kernel/integration-completeness.ts +54 -16
  86. package/packages/core/src/kernel/integration-state.ts +80 -11
  87. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  88. package/packages/core/src/kernel/mixed-version.ts +34 -0
  89. package/packages/core/src/kernel/node-parent.ts +35 -10
  90. package/packages/core/src/kernel/node-polling.ts +160 -0
  91. package/packages/core/src/kernel/read-facts.ts +47 -5
  92. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  93. package/packages/core/src/kernel/reducer.ts +75 -14
  94. package/packages/core/src/kernel/service-facts.ts +11 -4
  95. package/packages/core/src/kernel/ticket-migrations.ts +139 -0
  96. package/packages/core/src/operator/presentation.ts +7 -0
  97. package/packages/core/src/operator/query.ts +13 -3
  98. package/packages/core/src/operator/registry.ts +1 -1
  99. package/packages/core/src/operator/tickets.ts +30 -26
  100. package/packages/core/src/plugins/load.ts +4 -1
  101. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  102. package/packages/core/src/ports/forge/contract.ts +29 -0
  103. package/packages/core/src/ports/forge/github.ts +189 -61
  104. package/packages/core/src/ports/forge-failure.ts +1 -0
  105. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  106. package/packages/core/src/ports/runner/session-env.ts +1 -0
  107. package/packages/core/src/ports/tickets/linear.ts +180 -12
  108. package/packages/core/src/ports/tickets/migration.ts +92 -9
  109. package/packages/core/src/ports/types.ts +17 -0
  110. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  111. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  112. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  113. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  114. package/packages/core/src/processes/build-child-exit.ts +5 -26
  115. package/packages/core/src/processes/build-runner.ts +81 -11
  116. package/packages/core/src/processes/dispatcher.ts +418 -59
  117. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  118. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  119. package/packages/core/src/processes/execution-settlement.ts +16 -7
  120. package/packages/core/src/processes/harvest-runner.ts +328 -292
  121. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  122. package/packages/core/src/runtime-identity.ts +22 -3
  123. package/packages/core/src/store/contract.ts +183 -0
  124. package/packages/core/src/store/local/store.ts +197 -72
  125. package/packages/core/src/store/reduced-reads.ts +8 -0
  126. package/packages/core/src/store/reducer-value-shapes.json +8915 -6344
  127. package/packages/core/src/store/remote/client.ts +43 -0
  128. package/packages/core/src/store/repo-state-events.ts +21 -3
  129. package/packages/core/src/store/types.ts +7 -0
  130. package/packages/core/src/testing/dispatch-read-budget.ts +3 -2
  131. package/skills/guide/SKILL.md +234 -24
  132. package/skills/guide/references/integration-tree.md +91 -4
  133. package/skills/guide/references/operator-api.md +53 -4
  134. package/skills/guide/references/plugin-authoring.md +45 -4
  135. package/skills/guide/references/remote-store-protocol.md +9 -1
  136. package/skills/guide/references/remote-ticket-protocol.md +5 -0
  137. package/skills/guide/references/restacking.md +4 -1
  138. package/skills/guide/references/setup.md +24 -0
  139. package/skills/guide/references/spec-standard.md +94 -5
  140. package/skills/guide/references/ticket-migration.md +50 -4
  141. package/skills/harvest/SKILL.md +4 -0
  142. package/skills/harvest-review/SKILL.md +4 -0
  143. package/skills/operate/SKILL.md +78 -8
  144. package/skills/spec/SKILL.md +35 -5
  145. package/skills/tickets/SKILL.md +19 -0
@@ -1,3 +1,9 @@
1
+ import { migrationIdentity, ticketMigrationsReducer } from '../kernel/ticket-migrations'
2
+ import type { DispatchUpgradeState } from '../kernel/dispatch-upgrade'
3
+ import { releaseDispatchPresentation } from './dispatch-presentation-ownership'
4
+ import { readDispatchUpgrade } from '../store/reduced-reads'
5
+ import { DISPATCHER } from '../events/envelope'
6
+ import { launchContext } from './dispatch-launch-contract'
1
7
  import { dispatchCapacity } from '../kernel/dispatch-capacity'
2
8
  import { forgeReadinessWarnings } from '../kernel/dispatch-status'
3
9
  import { RepositoryPollCache } from './dashboard/repository-poll'
@@ -121,13 +127,13 @@ export interface DispatchFrontendOptions {
121
127
  * BuildStore, immutable repository identity, clock, and child supervision. */
122
128
  export class DispatchFrontend {
123
129
  private readonly standbyResolver: StandbyIdentityResolver
124
- private readonly runId = crypto.randomUUID()
130
+ private readonly runId: string
125
131
  private readonly clock: Clock
126
132
  private readonly region: LiveRegion
127
133
  private readonly keyboard
128
134
  private child: DispatchChildHandle | undefined
129
135
  private readonly repositoryFeed: DispatchRepositoryFeed
130
- private dispatchStatus: DispatchStatus = reduceDispatchStatus([], this.runId)
136
+ private dispatchStatus: DispatchStatus
131
137
  private eventRefreshTail: Promise<void> = Promise.resolve()
132
138
  private cache: DashboardBuildPollCache | undefined
133
139
  private config: Config | undefined
@@ -156,6 +162,8 @@ export class DispatchFrontend {
156
162
  private operatorStopRequested = false
157
163
 
158
164
  constructor(private readonly opts: DispatchFrontendOptions) {
165
+ this.runId = launchContext(opts.env)?.run ?? crypto.randomUUID()
166
+ this.dispatchStatus = reduceDispatchStatus([], this.runId)
159
167
  this.reader = presentationReader(opts.store, () => this.refresh?.admitted ?? true)
160
168
  this.clock = opts.clock ?? systemClock
161
169
  this.repositoryFeed = new DispatchRepositoryFeed(this.reader, opts.repo, this.clock)
@@ -270,6 +278,7 @@ export class DispatchFrontend {
270
278
  }
271
279
 
272
280
  private paint(): void {
281
+ if (this.presentationRestored) return
273
282
  if (this.refresh !== undefined && !this.refresh.painting) return
274
283
  if (this.model === undefined) return
275
284
  const renderer = this.opts.resolveDashboardRenderer?.() ?? renderDashboard
@@ -302,6 +311,7 @@ export class DispatchFrontend {
302
311
 
303
312
  private readonly repositoryPoll = new RepositoryPollCache<{
304
313
  repositoryEvents: RepositoryEvent[]
314
+ upgrades: DispatchUpgradeState
305
315
  status: DispatchStatus
306
316
  config: Config
307
317
  observationCount: number
@@ -320,6 +330,9 @@ export class DispatchFrontend {
320
330
  nextPollMs: this.refresh?.intervalMs ?? 0,
321
331
  read: async ({ fullEnrichment }) => {
322
332
  const repositoryEvents = await this.events()
333
+ // Authority and rollback holds need the full durable reduction, not the
334
+ // low-volume replay feed (which deliberately discards per-tick facts).
335
+ const upgrades = (await readDispatchUpgrade(this.reader, this.opts.repo)).value
323
336
  const status = this.dispatchStatus
324
337
  const ref = status.effectiveConfig
325
338
  if (ref === undefined) {
@@ -347,11 +360,11 @@ export class DispatchFrontend {
347
360
  await this.standbyResolver.refresh(this.runId, status.yieldedHolder, this.clock())
348
361
  await this.repositoryFeed.save()
349
362
  if (!this.cache.isCurrent(snapshot)) return undefined
350
- return { repositoryEvents, status, config, observationCount, snapshot }
363
+ return { repositoryEvents, upgrades, status, config, observationCount, snapshot }
351
364
  },
352
365
  })
353
366
  if (frame === undefined) return
354
- let { repositoryEvents, status } = frame
367
+ let { repositoryEvents, upgrades, status } = frame
355
368
  const { config, snapshot } = frame
356
369
  const standby = this.opts.once
357
370
  ? undefined
@@ -371,6 +384,7 @@ export class DispatchFrontend {
371
384
  if (!validAbortConfirmation(snapshot.states.get(slug))) {
372
385
  await this.dismissStaleAbortConfirmation(slug)
373
386
  repositoryEvents = await this.events()
387
+ upgrades = (await readDispatchUpgrade(this.reader, this.opts.repo)).value
374
388
  status = this.dispatchStatus
375
389
  }
376
390
  }
@@ -395,6 +409,10 @@ export class DispatchFrontend {
395
409
  snapshot.capacityBuilds ?? [],
396
410
  config.capacity,
397
411
  this.clock(),
412
+ migrationIdentity(
413
+ ticketMigrationsReducer.reduce(repositoryEvents),
414
+ config.tickets.source,
415
+ ),
398
416
  ),
399
417
  observationCount: this.observationCount,
400
418
  observationLimit: config.policy.harvestThreshold,
@@ -404,6 +422,7 @@ export class DispatchFrontend {
404
422
  ...(warningLines.length > 0 ? { warningLines } : {}),
405
423
  },
406
424
  repositoryEvents,
425
+ upgrades,
407
426
  )
408
427
  this.selection = reconcileSelection(previous, dashboardSelections(projected), this.selection)
409
428
  if (
@@ -1055,7 +1074,7 @@ export class DispatchFrontend {
1055
1074
  } catch {
1056
1075
  // Final presentation remains best-effort.
1057
1076
  } finally {
1058
- this.region.finish()
1077
+ if (!this.presentationRestored) this.region.finish()
1059
1078
  }
1060
1079
  }
1061
1080
 
@@ -1093,6 +1112,36 @@ export class DispatchFrontend {
1093
1112
  env: this.opts.env,
1094
1113
  options,
1095
1114
  })
1115
+ let releaseWork: Promise<void> | undefined
1116
+ let releaseAcknowledged = false
1117
+ const releaseTimer = setInterval(() => {
1118
+ if (releaseWork || releaseAcknowledged || this.operatorStopRequested) return
1119
+ releaseWork = (async () => {
1120
+ const state = (await readDispatchUpgrade(this.opts.store, this.opts.repo)).value.runs[
1121
+ this.runId
1122
+ ]
1123
+ if (!state?.request || !state.handoff || state.failure) return
1124
+ if (state.released) {
1125
+ releaseAcknowledged = true
1126
+ return
1127
+ }
1128
+ if (!this.presentationRestored) {
1129
+ await this.finishPresentation()
1130
+ this.presentationRestored = true
1131
+ releaseDispatchPresentation()
1132
+ }
1133
+ await this.opts.store.appendRepo(this.opts.repo, {
1134
+ actor: DISPATCHER,
1135
+ type: 'dispatcher.terminal-released',
1136
+ payload: state.prepared!.payload,
1137
+ })
1138
+ releaseAcknowledged = true
1139
+ })()
1140
+ .catch(() => {})
1141
+ .finally(() => {
1142
+ releaseWork = undefined
1143
+ })
1144
+ }, 1_000)
1096
1145
  const stop = (): void => this.requestOperatorStop()
1097
1146
  this.opts.signal?.addEventListener('abort', stop, { once: true })
1098
1147
  try {
@@ -1100,6 +1149,7 @@ export class DispatchFrontend {
1100
1149
  if (this.opts.signal?.aborted) this.requestOperatorStop()
1101
1150
  const result = await this.child.completed
1102
1151
  if (
1152
+ !this.presentationRestored &&
1103
1153
  !(result.outcome === 'normal' && result.exitCode === 0) &&
1104
1154
  !(result.outcome === 'forced' && this.operatorStopRequested)
1105
1155
  ) {
@@ -1114,6 +1164,8 @@ export class DispatchFrontend {
1114
1164
  )
1115
1165
  }
1116
1166
  } finally {
1167
+ clearInterval(releaseTimer)
1168
+ await releaseWork
1117
1169
  this.opts.signal?.removeEventListener('abort', stop)
1118
1170
  await this.child.stop()
1119
1171
  await this.finishPresentation()
@@ -0,0 +1,276 @@
1
+ import { rollbackRuntimeRetained } from './dispatch-runtime-use'
2
+ import { join, resolve, dirname } from 'node:path'
3
+ import { openSessionlessStore, openProductionStore, type StoreOpener } from './store-opening'
4
+ import { projectToken } from './project-credentials'
5
+ import { spawnExec } from '../ports/workspace/git-worktree'
6
+ import { parseDispatchArgs } from './dispatch-args'
7
+ import { readDispatchUpgrade, readDispatcherRunFacts } from '../store/reduced-reads'
8
+ import { cachedRuntime } from './dispatch-runtime-cache'
9
+ import type { GenerationLaunch } from './dispatch-launch-contract'
10
+ import type { Handoff } from '../kernel/dispatch-upgrade'
11
+
12
+ /** Once a held run identifies its journal, readers retain that transport
13
+ * identity across rejected configuration edits. It conveys no lifecycle result. */
14
+ export async function openGenerationStore(
15
+ launch: GenerationLaunch,
16
+ argv: string[],
17
+ env: Record<string, string | undefined>,
18
+ openStore?: StoreOpener,
19
+ ) {
20
+ if (launch.journal) {
21
+ const { storeRef, repo } = launch.journal
22
+ const token = /^https?:/i.test(storeRef) ? projectToken(storeRef, repo, env) : env.AB_TOKEN
23
+ return { store: (openStore ?? openProductionStore)(storeRef, token), storeRef, repo }
24
+ }
25
+ const args = parseDispatchArgs(argv.slice(1), env)
26
+ return openSessionlessStore({
27
+ targetRepo: launch.checkout,
28
+ exec: spawnExec,
29
+ env,
30
+ storeRef: args.storeRef,
31
+ ...(openStore ? { openStore } : {}),
32
+ })
33
+ }
34
+
35
+ /** Initial transport bootstrap: initialize/read the repository record, without
36
+ * claiming its lease or starting dispatch work, then return its query identity. */
37
+ export async function readGenerationJournal(
38
+ launch: GenerationLaunch,
39
+ argv: string[],
40
+ env: Record<string, string | undefined>,
41
+ ) {
42
+ const opened = await openGenerationStore(launch, argv, env)
43
+ try {
44
+ await opened.store.ensureRepo(opened.repo)
45
+ return {
46
+ version: 1,
47
+ rollbackVersion: 1,
48
+ journal: { storeRef: opened.storeRef, repo: (await opened.store.getRepo(opened.repo))!.repo },
49
+ }
50
+ } finally {
51
+ await opened.store.close()
52
+ }
53
+ }
54
+
55
+ /** Runtime-owned store reader. The filesystem-only launcher consumes this versioned result. */
56
+ export async function readHandoff(
57
+ launch: GenerationLaunch,
58
+ argv: string[],
59
+ env: Record<string, string | undefined>,
60
+ live = false,
61
+ ): Promise<Handoff | undefined> {
62
+ if (!launch.run || !launch.lineage) return undefined
63
+ const opened = await openGenerationStore(launch, argv, env)
64
+ try {
65
+ if (!(await opened.store.getRepo(opened.repo))) return undefined
66
+ const state = (await readDispatchUpgrade(opened.store, opened.repo)).value.runs[launch.run]
67
+ const selected = live ? state?.prepared : state?.handoff
68
+ if (!selected || (!live && state?.completed) || state?.failure) return undefined
69
+ const facts = (await readDispatcherRunFacts(opened.store, opened.repo, launch.run)).value
70
+ const handoff = selected.payload
71
+ if (
72
+ (!live &&
73
+ (facts.stop?.type !== 'dispatcher.run-stopped' ||
74
+ facts.stop.payload.outcome !== 'normal' ||
75
+ facts.stop.payload.signal !== undefined)) ||
76
+ facts.stopRequest ||
77
+ handoff.lineage !== launch.lineage
78
+ )
79
+ return undefined
80
+ const expected = join(launch.checkout, '.autobuild/runtime', handoff.cacheId, 'distribution')
81
+ if (
82
+ resolve(handoff.root) !== expected ||
83
+ dirname(dirname(handoff.root)) !== join(launch.checkout, '.autobuild/runtime')
84
+ )
85
+ return undefined
86
+ const candidate = await cachedRuntime(handoff.root)
87
+ if (candidate?.id !== handoff.cacheId) return undefined
88
+ return handoff
89
+ } finally {
90
+ await opened.store.close()
91
+ }
92
+ }
93
+
94
+ export async function readUpgradeProjection(
95
+ launch: GenerationLaunch,
96
+ argv: string[],
97
+ env: Record<string, string | undefined>,
98
+ ) {
99
+ const opened = await openGenerationStore(launch, argv, env)
100
+ try {
101
+ const record = await opened.store.getRepo(opened.repo)
102
+ const journal =
103
+ launch.journal ??
104
+ (record?.lease?.holder === launch.run
105
+ ? { storeRef: opened.storeRef, repo: opened.repo }
106
+ : undefined)
107
+ if (!journal) return { version: 1, handoff: null, takeover: false }
108
+ const handoff = await readHandoff({ ...launch, journal }, argv, env, true)
109
+ const upgrades = (await readDispatchUpgrade(opened.store, opened.repo)).value
110
+ const state = upgrades.runs[launch.run!]
111
+ const rollbackRecorded =
112
+ !!launch.rollback && upgrades.rollbackIds.includes(launch.rollback.correlation)
113
+ const hold = launch.lineage ? upgrades.holds[launch.lineage] : undefined
114
+ return {
115
+ version: 1,
116
+ journal,
117
+ handoff: handoff ?? null,
118
+ rollbackVersion: 1,
119
+ rollbackRetained:
120
+ rollbackRecorded &&
121
+ (!hold || rollbackRuntimeRetained(hold.payload.failedRoot, launch.lineage!)),
122
+ takeover: !!state?.takeover,
123
+ takeoverAt: state?.takeover?.ts,
124
+ takeoverPayload: state?.takeover?.payload,
125
+ completed: !!state?.completed,
126
+ accepted: !!state?.handoff,
127
+ successor: state?.request?.payload.successor,
128
+ released: !!state?.released,
129
+ }
130
+ } finally {
131
+ await opened.store.close()
132
+ }
133
+ }
134
+ export async function recordPreflightFailure(
135
+ launch: GenerationLaunch,
136
+ argv: string[],
137
+ env: Record<string, string | undefined>,
138
+ correlation: string,
139
+ reason: string,
140
+ ) {
141
+ const opened = await openGenerationStore(launch, argv, env)
142
+ try {
143
+ const state = (await readDispatchUpgrade(opened.store, opened.repo)).value.runs[launch.run!]
144
+ const facts = (await readDispatcherRunFacts(opened.store, opened.repo, launch.run!)).value
145
+ if (facts.stopRequest) return
146
+ const handoff = state?.prepared?.payload
147
+ if (!handoff || handoff.correlation !== correlation || state.handoff || state.failure) return
148
+ const { DISPATCHER } = await import('../events/envelope')
149
+ const { createReadinessRedactor } = await import('./init-readiness-shared')
150
+ await opened.store.appendRepo(opened.repo, {
151
+ actor: DISPATCHER,
152
+ type: 'dispatcher.upgrade-failed',
153
+ payload: {
154
+ correlation,
155
+ run: handoff.run,
156
+ lineage: handoff.lineage,
157
+ from: handoff.from,
158
+ target: handoff.target,
159
+ reason: createReadinessRedactor(env)(reason),
160
+ },
161
+ })
162
+ } finally {
163
+ await opened.store.close()
164
+ }
165
+ }
166
+
167
+ /** The launcher may recover presentation after the exact old process exits.
168
+ * It restores its inherited terminal first; this command records that work. */
169
+ export async function recoverTerminalRelease(
170
+ launch: GenerationLaunch,
171
+ argv: string[],
172
+ env: Record<string, string | undefined>,
173
+ ): Promise<void> {
174
+ if (launch.launcherPid !== process.ppid)
175
+ throw new Error('terminal recovery requires the owning launcher')
176
+ const opened = await openGenerationStore(launch, argv, env)
177
+ try {
178
+ const state = (await readDispatchUpgrade(opened.store, opened.repo)).value.runs[launch.run!]
179
+ const facts = (await readDispatcherRunFacts(opened.store, opened.repo, launch.run!)).value
180
+ if (
181
+ !state?.handoff ||
182
+ !state.request ||
183
+ state.released ||
184
+ state.failure ||
185
+ facts.stopRequest ||
186
+ state.handoff.payload.lineage !== launch.lineage
187
+ )
188
+ return
189
+ const { DISPATCHER } = await import('../events/envelope')
190
+ await opened.store.appendRepo(opened.repo, {
191
+ actor: DISPATCHER,
192
+ type: 'dispatcher.terminal-released',
193
+ payload: state.prepared!.payload,
194
+ })
195
+ } finally {
196
+ await opened.store.close()
197
+ }
198
+ }
199
+
200
+ /** Validate against durable takeover, then publish only under repository authority. */
201
+ export async function recordRuntimeRollback(
202
+ store: import('../store/types').BuildStore,
203
+ repo: string,
204
+ launch: GenerationLaunch,
205
+ run: string,
206
+ ): Promise<void> {
207
+ const context = launch.rollback
208
+ if (launch.recovery) {
209
+ const recovery = launch.recovery
210
+ const state = (await readDispatchUpgrade(store, repo)).value.runs[recovery.predecessor]
211
+ if (
212
+ !state?.takeover ||
213
+ state.takeover.payload.successor !== recovery.successor ||
214
+ state.takeover.payload.correlation !== recovery.handoff ||
215
+ state.takeover.payload.lineage !== launch.lineage ||
216
+ state.takeover.payload.root !== launch.runtimeRoot
217
+ )
218
+ throw new Error('recovery has no matching durable takeover')
219
+ }
220
+ if (!context) return
221
+ const { validRecoveryContext } = await import('./dispatch-launch-contract')
222
+ if (!validRecoveryContext(launch)) throw new Error('invalid rollback launch context')
223
+ const upgrades = (await readDispatchUpgrade(store, repo)).value
224
+ const takeover = upgrades.runs[context.predecessor]?.takeover
225
+ const payload = takeover?.payload
226
+ if (
227
+ !payload ||
228
+ takeover.ts !== context.takeoverAt ||
229
+ payload.correlation !== context.handoff ||
230
+ payload.lineage !== context.lineage ||
231
+ payload.successor !== context.successor ||
232
+ payload.root !== context.failed.root ||
233
+ payload.from.source.location !== context.restored.root ||
234
+ payload.cacheId !== context.failed.cacheId
235
+ )
236
+ throw new Error('rollback has no matching durable takeover and cached runtimes')
237
+ if ((await store.getRepo(repo))?.lease?.holder !== run)
238
+ throw new Error('rollback requires repository authority')
239
+ // A cleared hold may already have released its cache entry. Its correlation
240
+ // remains durable and must never republish/revalidate that consumed launch.
241
+ if (upgrades.rollbackIds.includes(context.correlation)) return
242
+ const [failed, restored] = await Promise.all([
243
+ cachedRuntime(context.failed.root),
244
+ cachedRuntime(context.restored.root),
245
+ ])
246
+ const { captureRuntimeIdentity } = await import('../runtime-identity')
247
+ const sameRuntime = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
248
+ if (
249
+ failed?.id !== context.failed.cacheId ||
250
+ restored?.id !== context.restored.cacheId ||
251
+ !sameRuntime(payload.from, captureRuntimeIdentity(context.restored.root)) ||
252
+ !sameRuntime(payload.to, captureRuntimeIdentity(context.failed.root))
253
+ )
254
+ throw new Error('rollback has no matching durable takeover and cached runtimes')
255
+ const { DISPATCHER } = await import('../events/envelope')
256
+ await store.appendRepo(repo, {
257
+ actor: DISPATCHER,
258
+ type: 'dispatcher.runtime-rolled-back',
259
+ payload: {
260
+ correlation: context.correlation,
261
+ run,
262
+ lineage: context.lineage,
263
+ predecessor: context.predecessor,
264
+ successor: context.successor,
265
+ handoff: context.handoff,
266
+ takeoverAt: context.takeoverAt,
267
+ failures: 3,
268
+ failed: payload.to,
269
+ restored: payload.from,
270
+ failedRoot: context.failed.root,
271
+ restoredRoot: context.restored.root,
272
+ target: payload.target,
273
+ reason: 'three failed generation exits within ten minutes of takeover',
274
+ },
275
+ })
276
+ }
@@ -0,0 +1,170 @@
1
+ import type { SourceLaunch } from './dispatch-upgrade-source'
2
+ import { isAbsolute, join, resolve } from 'node:path'
3
+
4
+ /** Frozen launcher ABI. Changes require a new version and compatibility fixture. */
5
+ export const DISPATCH_OVERLAP_VERSION = 1
6
+ export const DISPATCH_LAUNCH_VERSION = 1
7
+ export const DISPATCH_GENERATION_ENV = 'AB_DISPATCH_GENERATION'
8
+ export const GENERATION_ENTRY = 'bin/ab-dispatch-generation.ts'
9
+ export const GENERATION_EXITS = { stopped: 80, handoff: 81, failed: 82 } as const
10
+ export const GENERATION_SIGNALS = ['SIGINT', 'SIGHUP', 'SIGQUIT', 'SIGTERM'] as const
11
+ /** Negotiated independently of the frozen v1 launch/overlap protocols. */
12
+ export const DISPATCH_ROLLBACK_VERSION = 1
13
+ export interface RollbackContext {
14
+ version: 1
15
+ correlation: string
16
+ lineage: string
17
+ predecessor: string
18
+ successor: string
19
+ handoff: string
20
+ takeoverAt: string
21
+ failures: 3
22
+ failed: { root: string; cacheId: string }
23
+ restored: { root: string; cacheId: string }
24
+ }
25
+ export interface GenerationLaunch {
26
+ version: 1
27
+ rollbackVersion?: 1
28
+ rollback?: RollbackContext
29
+ recovery?: { predecessor: string; successor: string; handoff: string }
30
+ overlapVersion?: 1
31
+ journal?: { storeRef: string; repo: string }
32
+ runtimeRoot: string
33
+ checkout: string
34
+ sourceLaunch?: SourceLaunch
35
+ originalInstall?: string
36
+ run?: string
37
+ lineage?: string
38
+ predecessorRoot?: string
39
+ predecessorCorrelation?: string
40
+ predecessor?: string
41
+ launcherPid?: number
42
+ }
43
+ export function generationArguments(root: string, argv: readonly string[]): string[] {
44
+ return [
45
+ '--no-install',
46
+ '--tsconfig-override',
47
+ join(root, 'tsconfig.json'),
48
+ join(root, GENERATION_ENTRY),
49
+ ...argv,
50
+ ]
51
+ }
52
+ export function consumeGenerationMarker(
53
+ env: Record<string, string | undefined>,
54
+ ownRoot: string,
55
+ ): GenerationLaunch {
56
+ const raw = env[DISPATCH_GENERATION_ENV]
57
+ delete env[DISPATCH_GENERATION_ENV]
58
+ const marker = JSON.parse(raw ?? 'null') as GenerationLaunch | null
59
+ if (
60
+ !marker ||
61
+ !validSourceLaunch(marker.sourceLaunch) ||
62
+ !validRecoveryContext(marker) ||
63
+ marker.version !== DISPATCH_LAUNCH_VERSION ||
64
+ typeof marker.runtimeRoot !== 'string' ||
65
+ !isAbsolute(marker.runtimeRoot) ||
66
+ resolve(marker.runtimeRoot) !== resolve(ownRoot) ||
67
+ typeof marker.checkout !== 'string' ||
68
+ !isAbsolute(marker.checkout)
69
+ ) {
70
+ throw new Error('invalid dispatcher generation launch contract')
71
+ }
72
+ return marker
73
+ }
74
+ export function generationResult(
75
+ code: number,
76
+ signal: string | number | null,
77
+ ): { reason: 'stopped' | 'handoff' | 'failed'; publicCode: number } {
78
+ if (signal !== null) return { reason: 'failed', publicCode: 1 }
79
+ if (code === GENERATION_EXITS.stopped) return { reason: 'stopped', publicCode: 0 }
80
+ // Handoff is reserved; this launcher deliberately implements no target selection.
81
+ if (code === GENERATION_EXITS.handoff) return { reason: 'handoff', publicCode: 1 }
82
+ return { reason: 'failed', publicCode: code === GENERATION_EXITS.failed || code === 0 ? 1 : code }
83
+ }
84
+
85
+ export const DISPATCH_LAUNCH_CONTEXT_ENV = 'AB_DISPATCH_LAUNCH_CONTEXT'
86
+ export function launchContext(
87
+ env: Record<string, string | undefined>,
88
+ ): GenerationLaunch | undefined {
89
+ const raw = env[DISPATCH_LAUNCH_CONTEXT_ENV]
90
+ if (!raw) return undefined
91
+ const value = JSON.parse(raw) as GenerationLaunch
92
+ if (
93
+ !validSourceLaunch(value.sourceLaunch) ||
94
+ !validRecoveryContext(value) ||
95
+ value.version !== 1 ||
96
+ !value.run ||
97
+ !value.lineage ||
98
+ !value.originalInstall ||
99
+ !isAbsolute(value.originalInstall)
100
+ )
101
+ throw new Error('invalid generation context')
102
+ return value
103
+ }
104
+
105
+ function validSourceLaunch(value: unknown): boolean {
106
+ if (value === undefined) return true
107
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
108
+ const v = value as SourceLaunch
109
+ return (
110
+ Object.keys(v).sort().join(',') === 'baseline,commit,repository' &&
111
+ typeof v.repository === 'string' &&
112
+ isAbsolute(v.repository) &&
113
+ typeof v.commit === 'string' &&
114
+ /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(v.commit) &&
115
+ typeof v.baseline === 'string' &&
116
+ /^[a-f0-9]{64}$/.test(v.baseline)
117
+ )
118
+ }
119
+
120
+ export function validRecoveryContext(launch: GenerationLaunch): boolean {
121
+ if (launch.rollbackVersion !== undefined && launch.rollbackVersion !== 1) return false
122
+ if (launch.rollback !== undefined && (!launch.rollback || typeof launch.rollback !== 'object'))
123
+ return false
124
+ if (
125
+ launch.recovery !== undefined &&
126
+ (!launch.recovery || typeof launch.recovery !== 'object' || launch.predecessor)
127
+ )
128
+ return false
129
+ const context = launch.rollback
130
+ if (!context && !launch.recovery) return true
131
+ if (
132
+ launch.rollbackVersion !== DISPATCH_ROLLBACK_VERSION ||
133
+ typeof launch.lineage !== 'string' ||
134
+ !launch.lineage ||
135
+ typeof launch.run !== 'string' ||
136
+ !launch.run ||
137
+ !isAbsolute(launch.checkout) ||
138
+ !isAbsolute(launch.runtimeRoot)
139
+ )
140
+ return false
141
+ if (
142
+ launch.recovery &&
143
+ ![launch.recovery.predecessor, launch.recovery.successor, launch.recovery.handoff].every(
144
+ (v) => typeof v === 'string' && v.length > 0,
145
+ )
146
+ )
147
+ return false
148
+ if (!context) return true
149
+ const validRuntime = (runtime: RollbackContext['failed']) =>
150
+ runtime &&
151
+ typeof runtime.cacheId === 'string' &&
152
+ /^[^/]+-[a-f0-9]{64}$/.test(runtime.cacheId) &&
153
+ runtime.root === join(launch.checkout, '.autobuild/runtime', runtime.cacheId, 'distribution')
154
+ return (
155
+ context.version === 1 &&
156
+ context.lineage === launch.lineage &&
157
+ [context.correlation, context.predecessor, context.successor, context.handoff].every(
158
+ (v) => typeof v === 'string' && v.length > 0,
159
+ ) &&
160
+ typeof context.takeoverAt === 'string' &&
161
+ Number.isFinite(Date.parse(context.takeoverAt)) &&
162
+ context.failures === 3 &&
163
+ validRuntime(context.failed) &&
164
+ validRuntime(context.restored) &&
165
+ context.failed.root !== context.restored.root &&
166
+ context.restored.root === launch.runtimeRoot &&
167
+ !launch.predecessor &&
168
+ !launch.recovery
169
+ )
170
+ }