@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
@@ -0,0 +1,580 @@
1
+ import { DispatchCrashBudget } from './dispatch-crash-budget'
2
+ import { readFile } from 'node:fs/promises'
3
+ import {
4
+ sourceRepository,
5
+ sourceCommand,
6
+ sourceContent,
7
+ type SourceLaunch,
8
+ } from './dispatch-upgrade-source'
9
+ import {
10
+ FOCUS_REPORTING_MODE,
11
+ KITTY_KEYBOARD_MODE,
12
+ BRACKETED_PASTE_MODE,
13
+ ALTERNATE_SCREEN_MODE,
14
+ HIDDEN_CURSOR_MODE,
15
+ } from './terminal-restore'
16
+ import { watchPresentationJob } from './dispatch-presentation-job'
17
+ import { dirname, basename, resolve, join } from 'node:path'
18
+ import { randomUUID } from 'node:crypto'
19
+ import { distributionRoot } from '../distribution'
20
+ import { resolveMainRepo } from './main-checkout'
21
+ import { prepareRuntime, guestArchiveProvenance } from './dispatch-runtime-cache'
22
+ import {
23
+ activateRuntime,
24
+ pruneRuntimes,
25
+ spawnUsingRuntime,
26
+ releasePreparedRuntime,
27
+ reserveExistingRuntime,
28
+ } from './dispatch-runtime-use'
29
+ import {
30
+ DISPATCH_GENERATION_ENV,
31
+ DISPATCH_LAUNCH_VERSION,
32
+ DISPATCH_OVERLAP_VERSION,
33
+ GENERATION_SIGNALS,
34
+ generationArguments,
35
+ generationResult,
36
+ } from './dispatch-launch-contract'
37
+
38
+ // Filesystem/process-only dependencies above are evaluated before installation.
39
+ async function gitExec(cmd: string[], options: { cwd?: string }) {
40
+ const child = Bun.spawn(cmd, { cwd: options.cwd, stdout: 'pipe', stderr: 'pipe' })
41
+ const [exitCode, stdout, stderr] = await Promise.all([
42
+ child.exited,
43
+ new Response(child.stdout).text(),
44
+ new Response(child.stderr).text(),
45
+ ])
46
+ return { exitCode, stdout, stderr }
47
+ }
48
+ /** Launcher seam: preserve installation evidence before freezing the runtime. */
49
+ export async function prepareLaunchRuntime(
50
+ source: string,
51
+ originalInstall: string,
52
+ checkout: string,
53
+ ) {
54
+ return prepareRuntime(source, checkout, undefined, {
55
+ provenance: await guestArchiveProvenance(originalInstall),
56
+ })
57
+ }
58
+ export async function launchDispatcher(argv: string[]): Promise<number> {
59
+ const checkout = await resolveMainRepo(process.cwd(), gitExec)
60
+ // Keep the public installation pathname rather than its realpath into Bun's version store.
61
+ const entry = resolve(process.argv[1] ?? '')
62
+ const originalInstall =
63
+ basename(dirname(entry)) === '.bin'
64
+ ? join(dirname(dirname(entry)), '@defrex/autobuild')
65
+ : entry.endsWith('/bin/ab.ts')
66
+ ? dirname(dirname(entry))
67
+ : distributionRoot()
68
+ const repository = await sourceRepository(distributionRoot(), checkout)
69
+ let sourceLaunch: SourceLaunch | undefined
70
+ if (repository) {
71
+ const commit = (await sourceCommand(['git', 'rev-parse', 'HEAD'], distributionRoot())).trim()
72
+ const baseline = await sourceContent(distributionRoot(), repository)
73
+ sourceLaunch = { repository, commit, baseline: baseline.key }
74
+ }
75
+ let runtime = await prepareLaunchRuntime(distributionRoot(), originalInstall, checkout)
76
+ if (sourceLaunch) {
77
+ const frozen = JSON.parse(await readFile(join(runtime.root, 'package.json'), 'utf8'))
78
+ if (
79
+ typeof frozen.gitHead !== 'string' ||
80
+ !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(frozen.gitHead)
81
+ ) {
82
+ releasePreparedRuntime(runtime.root)
83
+ throw new Error('frozen source runtime has no commit provenance')
84
+ }
85
+ sourceLaunch.commit = frozen.gitHead
86
+ }
87
+ if (
88
+ sourceLaunch &&
89
+ (await sourceContent(distributionRoot(), sourceLaunch.repository)).key !== sourceLaunch.baseline
90
+ ) {
91
+ releasePreparedRuntime(runtime.root)
92
+ throw new Error('source changed while freezing launch provenance; retry dispatch')
93
+ }
94
+ type Child = {
95
+ runtime: typeof runtime
96
+ rollbackCapable: boolean
97
+ launch: import('./dispatch-launch-contract').GenerationLaunch
98
+ env: Record<string, string | undefined>
99
+ child: ReturnType<typeof Bun.spawn>
100
+ release(): void
101
+ job?: ReturnType<typeof watchPresentationJob>
102
+ result?: ReturnType<typeof generationResult>
103
+ exited: Promise<void>
104
+ }
105
+ const lineage = randomUUID()
106
+ const children = new Set<Child>()
107
+ let signal: NodeJS.Signals | undefined
108
+ const stopping = new AbortController()
109
+ const listeners = GENERATION_SIGNALS.map((name) => ({
110
+ name,
111
+ listener: () => {
112
+ signal ??= name
113
+ stopping.abort()
114
+ for (const record of children)
115
+ try {
116
+ record.child.kill(name)
117
+ } catch {}
118
+ },
119
+ }))
120
+ for (const { name, listener } of listeners) process.on(name, listener)
121
+ const start = (
122
+ selected: typeof runtime,
123
+ predecessor?: string,
124
+ predecessorRoot?: string,
125
+ predecessorCorrelation?: string,
126
+ journal?: import('./dispatch-launch-contract').GenerationLaunch['journal'],
127
+ successorRun?: string,
128
+ recovery?: Pick<import('./dispatch-launch-contract').GenerationLaunch, 'rollback' | 'recovery'>,
129
+ rollbackCapable = false,
130
+ ): Child => {
131
+ if (signal) throw new Error('dispatcher launch interrupted')
132
+ const launch: import('./dispatch-launch-contract').GenerationLaunch = {
133
+ version: DISPATCH_LAUNCH_VERSION,
134
+ ...(rollbackCapable ? { rollbackVersion: 1 as const } : {}),
135
+ ...recovery,
136
+ overlapVersion: DISPATCH_OVERLAP_VERSION,
137
+ ...(journal ? { journal } : {}),
138
+ runtimeRoot: selected.root,
139
+ checkout,
140
+ originalInstall,
141
+ ...(sourceLaunch ? { sourceLaunch } : {}),
142
+ launcherPid: process.pid,
143
+ run: successorRun ?? randomUUID(),
144
+ lineage,
145
+ ...(predecessor ? { predecessor, predecessorRoot, predecessorCorrelation } : {}),
146
+ }
147
+ const env = {
148
+ ...process.env,
149
+ ...(journal ? { AB_STORE: journal.storeRef } : {}),
150
+ [DISPATCH_GENERATION_ENV]: JSON.stringify(launch),
151
+ }
152
+ const spawned = spawnUsingRuntime(selected.root, () =>
153
+ Bun.spawn(
154
+ [
155
+ process.execPath,
156
+ ...generationArguments(selected.root, [...(predecessor ? ['--preflight'] : []), ...argv]),
157
+ ],
158
+ { cwd: process.cwd(), env, stdin: 'inherit', stdout: 'inherit', stderr: 'inherit' },
159
+ ),
160
+ )
161
+ const record: Child = {
162
+ runtime: selected,
163
+ rollbackCapable,
164
+ launch,
165
+ env,
166
+ child: spawned.child,
167
+ release: spawned.release,
168
+ exited: Promise.resolve(),
169
+ }
170
+ children.add(record)
171
+ if (!predecessor) releasePreparedRuntime(selected.root)
172
+ if (!predecessor) record.job = watchPresentationJob(record.child.pid)
173
+ record.exited = record.child.exited
174
+ .then((code) => {
175
+ record.result = generationResult(code, record.child.signalCode)
176
+ })
177
+ .finally(() => {
178
+ record.job?.close()
179
+ record.release()
180
+ })
181
+ return record
182
+ }
183
+ const reader = async (
184
+ record: Pick<Child, 'runtime' | 'env'>,
185
+ mode: string,
186
+ extra: string[] = [],
187
+ ) => {
188
+ const helper = Bun.spawn(
189
+ [process.execPath, ...generationArguments(record.runtime.root, [mode, ...extra, ...argv])],
190
+ {
191
+ cwd: process.cwd(),
192
+ env: record.env,
193
+ stdin: 'ignore',
194
+ stdout: 'pipe',
195
+ stderr: 'pipe',
196
+ signal: AbortSignal.any([stopping.signal, AbortSignal.timeout(30_000)]),
197
+ },
198
+ )
199
+ const [code, output, error] = await Promise.all([
200
+ helper.exited,
201
+ new Response(helper.stdout).text(),
202
+ new Response(helper.stderr).text(),
203
+ ])
204
+ if (code !== 0) throw new Error(`generation journal reader failed: ${error}`)
205
+ return output ? JSON.parse(output) : null
206
+ }
207
+ let active: Child | undefined
208
+ let pending: { record: Child; correlation: string } | undefined
209
+ let recovery:
210
+ | { previous: Child; successor: string; correlation: string; budget: DispatchCrashBudget }
211
+ | undefined
212
+ const protectedRoots = new Set<string>()
213
+ const protect = (root: string) => {
214
+ if (!reserveExistingRuntime(root)) throw new Error(`rollback runtime unavailable: ${root}`)
215
+ protectedRoots.add(root)
216
+ }
217
+ const supportsRollback = async (selected: typeof runtime) => {
218
+ const result = await reader(
219
+ {
220
+ runtime: selected,
221
+ env: {
222
+ ...process.env,
223
+ [DISPATCH_GENERATION_ENV]: JSON.stringify({
224
+ version: 1,
225
+ runtimeRoot: selected.root,
226
+ checkout,
227
+ originalInstall,
228
+ lineage,
229
+ journal: active?.launch.journal,
230
+ }),
231
+ },
232
+ },
233
+ '--read-journal',
234
+ ).catch(() => null)
235
+ return result?.rollbackVersion === 1
236
+ }
237
+ let clean = false
238
+ let publicCode = 1
239
+ try {
240
+ activateRuntime(runtime.root)
241
+ const bootstrap = (await reader(
242
+ {
243
+ runtime,
244
+ env: {
245
+ ...process.env,
246
+ [DISPATCH_GENERATION_ENV]: JSON.stringify({
247
+ version: DISPATCH_LAUNCH_VERSION,
248
+ overlapVersion: DISPATCH_OVERLAP_VERSION,
249
+ runtimeRoot: runtime.root,
250
+ checkout,
251
+ originalInstall,
252
+ ...(sourceLaunch ? { sourceLaunch } : {}),
253
+ launcherPid: process.pid,
254
+ lineage,
255
+ }),
256
+ },
257
+ },
258
+ '--read-journal',
259
+ )) as {
260
+ version: number
261
+ rollbackVersion?: number
262
+ journal?: { storeRef: string; repo: string }
263
+ }
264
+ if (
265
+ bootstrap.version !== 1 ||
266
+ typeof bootstrap.journal?.storeRef !== 'string' ||
267
+ typeof bootstrap.journal.repo !== 'string'
268
+ )
269
+ throw new Error('invalid generation journal identity')
270
+ if (signal) throw new Error('dispatcher launch interrupted')
271
+ active = start(
272
+ runtime,
273
+ undefined,
274
+ undefined,
275
+ undefined,
276
+ bootstrap.journal,
277
+ undefined,
278
+ undefined,
279
+ bootstrap.rollbackVersion === 1,
280
+ )
281
+ for (;;) {
282
+ if (signal) break
283
+ // Once recovery has expired, a failed child must retain its ordinary
284
+ // exit behavior even when neither cached reader can reach the store.
285
+ if (active.result && !pending && recovery && !recovery.budget.withinWindow(Date.now())) {
286
+ clean = active.result.reason === 'stopped'
287
+ publicCode = active.result.publicCode
288
+ break
289
+ }
290
+ // Projection is produced by the running immutable runtime. This module
291
+ // has no store, config, compatibility or target-resolution dependencies.
292
+ let projection: {
293
+ version: number
294
+ handoff: {
295
+ root: string
296
+ cacheId: string
297
+ run: string
298
+ lineage: string
299
+ correlation: string
300
+ } | null
301
+ takeover: boolean
302
+ rollbackRetained?: boolean
303
+ takeoverAt?: string
304
+ journal?: { storeRef: string; repo: string }
305
+ successor?: string
306
+ accepted?: boolean
307
+ released?: boolean
308
+ }
309
+ try {
310
+ projection = (await reader(active, '--read-upgrade')) as {
311
+ version: number
312
+ handoff: {
313
+ root: string
314
+ cacheId: string
315
+ run: string
316
+ lineage: string
317
+ correlation: string
318
+ } | null
319
+ takeover: boolean
320
+ journal?: { storeRef: string; repo: string }
321
+ successor?: string
322
+ accepted?: boolean
323
+ released?: boolean
324
+ }
325
+ } catch {
326
+ // A broken target may not even load its reader. Use the known cached
327
+ // predecessor's reader with the same journal/run query identity.
328
+ const healthy = pending?.record ?? recovery?.previous
329
+ if (healthy) {
330
+ try {
331
+ const query = {
332
+ ...healthy.launch,
333
+ runtimeRoot: healthy.runtime.root,
334
+ run: active.launch.run,
335
+ predecessor: undefined,
336
+ rollback: undefined,
337
+ recovery: undefined,
338
+ }
339
+ projection = await reader(
340
+ {
341
+ runtime: healthy.runtime,
342
+ env: { ...healthy.env, [DISPATCH_GENERATION_ENV]: JSON.stringify(query) },
343
+ },
344
+ '--read-upgrade',
345
+ )
346
+ } catch {
347
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
348
+ continue
349
+ }
350
+ } else if (active.result && !pending) {
351
+ clean = active.result.reason === 'stopped'
352
+ publicCode = active.result.publicCode
353
+ break
354
+ } else {
355
+ await new Promise<void>((resolve) => setTimeout(resolve, 100))
356
+ continue
357
+ }
358
+ }
359
+ if (active.launch.rollback && projection.rollbackRetained) {
360
+ for (const root of [
361
+ active.launch.rollback.failed.root,
362
+ active.launch.rollback.restored.root,
363
+ ]) {
364
+ if (protectedRoots.has(root)) releasePreparedRuntime(root)
365
+ protectedRoots.delete(root)
366
+ }
367
+ }
368
+ if (projection.version !== 1) throw new Error('incompatible generation upgrade reader')
369
+ if (projection.journal && !active.launch.journal) {
370
+ active.launch = { ...active.launch, journal: projection.journal }
371
+ active.env = { ...active.env, [DISPATCH_GENERATION_ENV]: JSON.stringify(active.launch) }
372
+ }
373
+
374
+ if (pending && active.result && projection.accepted && !projection.released) {
375
+ active.job?.close()
376
+ active.job = undefined
377
+ if (process.stdin.isTTY) process.stdin.setRawMode(false)
378
+ if (process.stdout.isTTY)
379
+ for (const mode of [
380
+ FOCUS_REPORTING_MODE,
381
+ KITTY_KEYBOARD_MODE,
382
+ BRACKETED_PASTE_MODE,
383
+ ALTERNATE_SCREEN_MODE,
384
+ HIDDEN_CURSOR_MODE,
385
+ ])
386
+ process.stdout.write(mode.restore)
387
+ await reader(active, '--recover-terminal-release')
388
+ }
389
+
390
+ if (pending && projection.takeover) {
391
+ const previous = active
392
+ if (previous.rollbackCapable && pending.record.rollbackCapable && projection.takeoverAt) {
393
+ protect(previous.runtime.root)
394
+ protect(pending.record.runtime.root)
395
+ for (const root of protectedRoots) {
396
+ if (root === previous.runtime.root || root === pending.record.runtime.root) continue
397
+ releasePreparedRuntime(root)
398
+ protectedRoots.delete(root)
399
+ }
400
+ recovery = {
401
+ previous,
402
+ successor: pending.record.launch.run!,
403
+ correlation: pending.correlation,
404
+ budget: new DispatchCrashBudget(projection.takeoverAt),
405
+ }
406
+ } else {
407
+ recovery = undefined
408
+ console.error(
409
+ 'automatic runtime rollback requires rollback-capable predecessor and successor runtimes',
410
+ )
411
+ }
412
+ active.job?.close()
413
+ active.job = undefined
414
+ active = pending.record
415
+ releasePreparedRuntime(active.runtime.root)
416
+ active.job = watchPresentationJob(active.child.pid)
417
+ runtime = active.runtime
418
+ activateRuntime(runtime.root)
419
+ pending = undefined
420
+ } else if (pending?.record.result) {
421
+ children.delete(pending.record)
422
+ if (projection.accepted && projection.handoff && projection.successor) {
423
+ pending = {
424
+ record: start(
425
+ pending.record.runtime,
426
+ active.launch.run,
427
+ active.runtime.root,
428
+ pending.correlation,
429
+ active.launch.journal,
430
+ projection.successor,
431
+ undefined,
432
+ pending.record.rollbackCapable,
433
+ ),
434
+ correlation: pending.correlation,
435
+ }
436
+ } else {
437
+ try {
438
+ await reader(active, '--record-preflight-failure', [
439
+ pending.correlation,
440
+ 'target preflight exited without takeover; repository authority was retained',
441
+ ])
442
+ } catch {
443
+ // Failure publication is retryable durable work, not permission to
444
+ // stop a healthy predecessor or retry target preparation.
445
+ await new Promise<void>((resolve) => setTimeout(resolve, 1_000))
446
+ continue
447
+ }
448
+ releasePreparedRuntime(pending.record.runtime.root)
449
+ pending = undefined
450
+ }
451
+ } else if (!pending && projection.handoff) {
452
+ const handoff = projection.handoff
453
+ if (handoff.run !== active.launch.run || handoff.lineage !== lineage)
454
+ throw new Error('invalid durable generation target')
455
+ pending = {
456
+ record: start(
457
+ { ...runtime, root: handoff.root, id: handoff.cacheId },
458
+ active.launch.run,
459
+ active.runtime.root,
460
+ handoff.correlation,
461
+ active.launch.journal,
462
+ projection.successor,
463
+ undefined,
464
+ await supportsRollback({ ...runtime, root: handoff.root, id: handoff.cacheId }),
465
+ ),
466
+ correlation: handoff.correlation,
467
+ }
468
+ }
469
+ if (active.result?.reason === 'failed' && !pending && recovery) {
470
+ const action = recovery.budget.failed(active.launch.run!, Date.now())
471
+ if (action) {
472
+ if (process.stdin.isTTY) process.stdin.setRawMode(false)
473
+ if (process.stdout.isTTY)
474
+ for (const mode of [
475
+ FOCUS_REPORTING_MODE,
476
+ KITTY_KEYBOARD_MODE,
477
+ BRACKETED_PASTE_MODE,
478
+ ALTERNATE_SCREEN_MODE,
479
+ HIDDEN_CURSOR_MODE,
480
+ ])
481
+ process.stdout.write(mode.restore)
482
+ active.job?.close()
483
+ const context = {
484
+ predecessor: recovery.previous.launch.run!,
485
+ successor: recovery.successor,
486
+ handoff: recovery.correlation,
487
+ }
488
+ if (action === 'restart') {
489
+ active = start(
490
+ active.runtime,
491
+ undefined,
492
+ undefined,
493
+ undefined,
494
+ active.launch.journal,
495
+ undefined,
496
+ { recovery: context },
497
+ true,
498
+ )
499
+ } else {
500
+ const previous = recovery.previous
501
+ // Both entries were reserved before activation/releasing child claims.
502
+ // The restored generation transfers the failed entry to its durable hold.
503
+ const rollback: import('./dispatch-launch-contract').RollbackContext = {
504
+ version: 1,
505
+ correlation: randomUUID(),
506
+ lineage,
507
+ ...context,
508
+ takeoverAt: recovery.budget.takeoverAt,
509
+ failures: 3,
510
+ failed: { root: active.runtime.root, cacheId: active.runtime.id },
511
+ restored: { root: previous.runtime.root, cacheId: previous.runtime.id },
512
+ }
513
+ active = start(
514
+ previous.runtime,
515
+ undefined,
516
+ undefined,
517
+ undefined,
518
+ active.launch.journal,
519
+ undefined,
520
+ { rollback },
521
+ true,
522
+ )
523
+ runtime = active.runtime
524
+ activateRuntime(runtime.root)
525
+ recovery = undefined
526
+ }
527
+ continue
528
+ }
529
+ }
530
+ if (active.result && !pending) {
531
+ clean = active.result.reason === 'stopped' || active.result.reason === 'handoff'
532
+ publicCode = active.result.publicCode
533
+ break
534
+ }
535
+ for (const record of children)
536
+ if (record !== active && record !== pending?.record && record.result)
537
+ children.delete(record)
538
+ pruneRuntimes(dirname(dirname(runtime.root)))
539
+ let timer: ReturnType<typeof setTimeout> | undefined
540
+ try {
541
+ await Promise.race([
542
+ new Promise<void>((resolve) => {
543
+ timer = setTimeout(resolve, pending ? 250 : 1_000)
544
+ }),
545
+ ...(!active.result ? [active.exited] : []),
546
+ ...(pending && !pending.record.result ? [pending.record.exited] : []),
547
+ ])
548
+ } finally {
549
+ clearTimeout(timer)
550
+ }
551
+ }
552
+ } catch (error) {
553
+ if (!signal) throw error
554
+ } finally {
555
+ for (const record of children)
556
+ if (!record.result)
557
+ try {
558
+ record.child.kill(signal ?? 'SIGTERM')
559
+ } catch {}
560
+ await Promise.all([...children].map((record) => record.exited))
561
+ if (active?.result?.reason === 'stopped' || active?.result?.reason === 'handoff') clean = true
562
+ for (const { name, listener } of listeners) process.removeListener(name, listener)
563
+ // A preflight process never owns restoration. Only failure of the active
564
+ // presentation owner requires the launcher's last-resort cleanup.
565
+ if (!clean && active && process.stdin.isTTY) process.stdin.setRawMode(false)
566
+ if (!clean && active && process.stdout.isTTY)
567
+ for (const mode of [
568
+ FOCUS_REPORTING_MODE,
569
+ KITTY_KEYBOARD_MODE,
570
+ BRACKETED_PASTE_MODE,
571
+ ALTERNATE_SCREEN_MODE,
572
+ HIDDEN_CURSOR_MODE,
573
+ ])
574
+ process.stdout.write(mode.restore)
575
+ for (const root of protectedRoots) releasePreparedRuntime(root)
576
+ pruneRuntimes(dirname(dirname(runtime.root)))
577
+ }
578
+ if (signal && signal !== 'SIGINT') process.kill(process.pid, signal)
579
+ return signal === 'SIGINT' ? 0 : publicCode
580
+ }
@@ -0,0 +1,44 @@
1
+ export interface DispatchProcessHook {
2
+ close(): void
3
+ }
4
+ export interface DispatchParentWatchDeps {
5
+ intervalMs?: number
6
+ currentParentPid?: () => number
7
+ isAlive?: (pid: number) => boolean
8
+ }
9
+
10
+ /** A private kernel must never become a detached daemon if its terminal-owning
11
+ * parent is killed directly rather than through the foreground process group.
12
+ * Polling is deliberately local process liveness, not an operational IPC
13
+ * channel; shutdown still converges through the normal AbortSignal boundary. */
14
+ export function watchDispatchParent(
15
+ parentPid: number,
16
+ onParentExit: () => void,
17
+ deps: DispatchParentWatchDeps = {},
18
+ ): DispatchProcessHook {
19
+ const currentParentPid = deps.currentParentPid ?? (() => process.ppid)
20
+ const isAlive =
21
+ deps.isAlive ??
22
+ ((pid: number): boolean => {
23
+ try {
24
+ process.kill(pid, 0)
25
+ return true
26
+ } catch {
27
+ return false
28
+ }
29
+ })
30
+ let closed = false
31
+ let timer: ReturnType<typeof setInterval>
32
+ const close = (): void => {
33
+ if (closed) return
34
+ closed = true
35
+ clearInterval(timer)
36
+ }
37
+ timer = setInterval(() => {
38
+ if (currentParentPid() === parentPid && isAlive(parentPid)) return
39
+ close()
40
+ onParentExit()
41
+ }, deps.intervalMs ?? 100)
42
+ timer.unref?.()
43
+ return { close }
44
+ }