@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,272 @@
1
+ import type { BuildStore } from '../store/types'
2
+ import { DISPATCHER } from '../events/envelope'
3
+ import type { Handoff } from '../kernel/dispatch-upgrade'
4
+
5
+ export interface StoreOverlapEvidence {
6
+ compatible: boolean
7
+ evidence: string
8
+ }
9
+ export interface PreflightInput {
10
+ store: BuildStore
11
+ repo: string
12
+ handoff: Handoff
13
+ successor: string
14
+ signal: AbortSignal
15
+ validate(): Promise<void>
16
+ /** The admitted predecessor owns failure publication, including when this
17
+ * target cannot authenticate or its new catalog writes are rejected. */
18
+ failure(reason: string): Promise<void>
19
+ }
20
+ async function preflightRead<T>(signal: AbortSignal, read: () => Promise<T>): Promise<T> {
21
+ signal.throwIfAborted()
22
+ return new Promise<T>((resolve, reject) => {
23
+ const abort = () => reject(signal.reason)
24
+ signal.addEventListener('abort', abort, { once: true })
25
+ Promise.resolve()
26
+ .then(() => {
27
+ signal.throwIfAborted()
28
+ return read()
29
+ })
30
+ .then(
31
+ (value) => {
32
+ signal.removeEventListener('abort', abort)
33
+ resolve(value)
34
+ },
35
+ (error) => {
36
+ signal.removeEventListener('abort', abort)
37
+ reject(error)
38
+ },
39
+ )
40
+ })
41
+ }
42
+
43
+ /** A successful metadata probe never authorizes yield. Only a successfully
44
+ * persisted request does. Callers keep terminal and repository work inactive. */
45
+ export async function prepareDispatcherYield(input: PreflightInput): Promise<boolean> {
46
+ try {
47
+ input.signal.throwIfAborted()
48
+ await preflightRead(input.signal, input.validate)
49
+ const evidence = (await preflightRead(input.signal, async () =>
50
+ input.store.inspectDispatcherOverlap?.(input.signal),
51
+ )) ?? {
52
+ compatible: false,
53
+ evidence: 'selected store does not provide overlap compatibility evidence',
54
+ }
55
+ input.signal.throwIfAborted()
56
+ const holder = (await preflightRead(input.signal, () => input.store.getRepo(input.repo)))?.lease
57
+ if (holder?.holder !== input.handoff.run || Date.parse(holder.expiresAt) <= Date.now())
58
+ throw new Error('preflight predecessor no longer holds the repository lease')
59
+ // This write is also the actual store/catalog admission test. A rejection
60
+ // must never be translated into cutover or successful preflight.
61
+ await input.store.appendRepo(input.repo, {
62
+ actor: DISPATCHER,
63
+ type: 'dispatcher.yield-requested',
64
+ payload: {
65
+ ...input.handoff,
66
+ successor: input.successor,
67
+ mode: evidence.compatible ? 'drain' : 'cutover',
68
+ evidence: evidence.evidence,
69
+ },
70
+ })
71
+ return true
72
+ } catch (error) {
73
+ if (
74
+ !input.signal.aborted ||
75
+ (input.signal.reason instanceof Error && input.signal.reason.name === 'TimeoutError')
76
+ )
77
+ await input.failure(
78
+ input.signal.aborted
79
+ ? 'dispatcher preflight deadline exceeded'
80
+ : error instanceof Error
81
+ ? error.message
82
+ : 'dispatcher preflight failed',
83
+ )
84
+ return false
85
+ }
86
+ }
87
+
88
+ /** Runtime-owned entry. The launcher never opens the store or interprets config. */
89
+ async function runGenerationPreflight(
90
+ launch: import('./dispatch-launch-contract').GenerationLaunch,
91
+ argv: string[],
92
+ env: Record<string, string | undefined>,
93
+ signal: AbortSignal,
94
+ ): Promise<boolean> {
95
+ const { RemoteBuildStore } = await import('../store/remote/client')
96
+ const { openGenerationStore } = await import('./dispatch-handoff')
97
+ const { openLocalStore } = await import('../store/local/store')
98
+ const { spawnExec } = await import('../ports/workspace/git-worktree')
99
+ const { loadConfig } = await import('../config/load')
100
+ const { readDispatchUpgrade, readDispatcherRunFacts } = await import('../store/reduced-reads')
101
+ const { join } = await import('node:path')
102
+ let prepared = false
103
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(120_000)])
104
+ const opened = await openGenerationStore(launch, argv, env, (ref, token) =>
105
+ /^https?:/i.test(ref)
106
+ ? new RemoteBuildStore({
107
+ url: ref,
108
+ token,
109
+ fetchFn: ((input, init) =>
110
+ fetch(input, {
111
+ ...init,
112
+ signal: AbortSignal.any([
113
+ signal,
114
+ prepared ? AbortSignal.timeout(30_000) : deadline,
115
+ ...(init?.signal ? [init.signal] : []),
116
+ ]),
117
+ })) as typeof fetch,
118
+ })
119
+ : openLocalStore(ref, { bootstrap: false }),
120
+ )
121
+ try {
122
+ const state = (await readDispatchUpgrade(opened.store, opened.repo)).value.runs[
123
+ launch.predecessor!
124
+ ]
125
+ const handoff = state?.prepared?.payload
126
+ if (
127
+ !handoff ||
128
+ handoff.correlation !== launch.predecessorCorrelation ||
129
+ handoff.root !== launch.runtimeRoot ||
130
+ handoff.lineage !== launch.lineage ||
131
+ !launch.run
132
+ )
133
+ return false
134
+ if (state?.request && state.request.payload.successor !== launch.run) return false
135
+ const failure = async (reason: string) => publishPreflightFailure(launch, argv, env, reason)
136
+
137
+ if (state?.request?.payload.successor === launch.run) prepared = true
138
+ if (
139
+ !prepared &&
140
+ !(await prepareDispatcherYield({
141
+ store: opened.store,
142
+ repo: opened.repo,
143
+ handoff,
144
+ successor: launch.run,
145
+ signal: deadline,
146
+ failure,
147
+ validate: async () => {
148
+ const config = await loadConfig(join(launch.checkout, 'autobuild.toml'))
149
+ if (!config.upgrade.automatic)
150
+ throw new Error('automatic upgrades disabled during preflight')
151
+ const { loadPlugins } = await import('../plugins/load')
152
+ const { materializePluginRuntimes } = await import('../plugins/runtimes')
153
+ const { createProductionRuntimes } = await import('../ports/runner/production')
154
+ const { createRuntimeResolver } = await import('../ports/runner/routing')
155
+ const { resolveForgeRegistration } = await import('../ports/forge/create')
156
+ const { validateWorkspaceDispatchConfiguration } = await import('./dispatch-readiness')
157
+ const plugins = await loadPlugins(config.plugins, launch.checkout, {
158
+ packageRoot: launch.checkout,
159
+ onNotice: () => {},
160
+ })
161
+ resolveForgeRegistration(config.forge, plugins)
162
+ await validateWorkspaceDispatchConfiguration(
163
+ config,
164
+ { targetRepo: launch.checkout, env, exec: spawnExec },
165
+ plugins,
166
+ )
167
+ const runtimes = await materializePluginRuntimes(
168
+ createProductionRuntimes().runtimes,
169
+ plugins,
170
+ { repoRoot: launch.checkout, env },
171
+ )
172
+ createRuntimeResolver(runtimes, config.roles, config.policy.sessionBudgetSeconds)
173
+ const facts = (await readDispatcherRunFacts(opened.store, opened.repo, handoff.run)).value
174
+ if (facts.stopRequest || facts.stop)
175
+ throw new Error('predecessor stopped during preflight')
176
+ },
177
+ }))
178
+ )
179
+ return false
180
+ prepared = true
181
+ for (;;) {
182
+ signal.throwIfAborted()
183
+ const current = (await readDispatchUpgrade(opened.store, opened.repo)).value.runs[handoff.run]
184
+ const facts = (await readDispatcherRunFacts(opened.store, opened.repo, handoff.run)).value
185
+ if (facts.stopRequest || current?.failure) return false
186
+ if (facts.stop && !current?.handoff) return false
187
+ if (
188
+ current?.request?.payload.correlation !== handoff.correlation ||
189
+ current.request.payload.successor !== launch.run
190
+ )
191
+ return false
192
+ const ready =
193
+ current?.handoff?.payload.successor === launch.run &&
194
+ current.handoff.payload.correlation === handoff.correlation &&
195
+ current?.released?.payload.correlation === handoff.correlation &&
196
+ (current.request?.payload.mode === 'drain' ||
197
+ (current.completed &&
198
+ facts.stop?.type === 'dispatcher.run-stopped' &&
199
+ facts.stop.payload.outcome === 'normal'))
200
+ if (ready && (await opened.store.claimRepoLease(opened.repo, launch.run, 60_000))) {
201
+ await opened.store.appendRepo(opened.repo, {
202
+ actor: DISPATCHER,
203
+ type: 'dispatcher.takeover',
204
+ payload: { ...handoff, successor: launch.run },
205
+ })
206
+ return true
207
+ }
208
+ await new Promise<void>((resolve) => setTimeout(resolve, 500))
209
+ }
210
+ } finally {
211
+ await opened.store.close()
212
+ }
213
+ }
214
+
215
+ export async function preflightGeneration(
216
+ launch: import('./dispatch-launch-contract').GenerationLaunch,
217
+ argv: string[],
218
+ env: Record<string, string | undefined>,
219
+ signal: AbortSignal,
220
+ ): Promise<boolean> {
221
+ try {
222
+ return await runGenerationPreflight(launch, argv, env, signal)
223
+ } catch (error) {
224
+ if (!signal.aborted)
225
+ await publishPreflightFailure(
226
+ launch,
227
+ argv,
228
+ env,
229
+ error instanceof Error ? error.message : 'target preflight failed',
230
+ )
231
+ return false
232
+ }
233
+ }
234
+
235
+ async function publishPreflightFailure(
236
+ launch: import('./dispatch-launch-contract').GenerationLaunch,
237
+ argv: string[],
238
+ env: Record<string, string | undefined>,
239
+ reason: string,
240
+ ): Promise<void> {
241
+ if (!launch.predecessorRoot || !launch.predecessor || !launch.predecessorCorrelation)
242
+ throw new Error('missing predecessor failure writer')
243
+ const { generationArguments, DISPATCH_GENERATION_ENV } = await import(
244
+ './dispatch-launch-contract'
245
+ )
246
+ const predecessor = {
247
+ ...launch,
248
+ run: launch.predecessor,
249
+ runtimeRoot: launch.predecessorRoot,
250
+ predecessor: undefined,
251
+ }
252
+ const writer = Bun.spawn(
253
+ [
254
+ process.execPath,
255
+ ...generationArguments(launch.predecessorRoot, [
256
+ '--record-preflight-failure',
257
+ launch.predecessorCorrelation,
258
+ reason,
259
+ ...argv,
260
+ ]),
261
+ ],
262
+ {
263
+ env: { ...env, [DISPATCH_GENERATION_ENV]: JSON.stringify(predecessor) },
264
+ cwd: launch.checkout,
265
+ stdin: 'ignore',
266
+ stdout: 'ignore',
267
+ stderr: 'ignore',
268
+ signal: AbortSignal.timeout(30_000),
269
+ },
270
+ )
271
+ if ((await writer.exited) !== 0) throw new Error('predecessor could not record preflight failure')
272
+ }
@@ -0,0 +1,46 @@
1
+ import { readFileSync } from 'node:fs'
2
+
3
+ /** Observe presentation liveness, never kernel work. Raw-mode Ctrl-Z stops only
4
+ * the generation; the shell also needs its direct child stopped to regain the
5
+ * terminal. SIGCONT from `fg` resumes that presentation, leaving the kernel alone. */
6
+ export function watchPresentationJob(pid: number): { close(): void } {
7
+ let closed = false
8
+ let checking = false
9
+ const continued = () => {
10
+ try {
11
+ process.kill(pid, 'SIGCONT')
12
+ } catch {}
13
+ }
14
+ process.on('SIGCONT', continued)
15
+ const timer = setInterval(async () => {
16
+ if (closed || checking) return
17
+ checking = true
18
+ try {
19
+ let state: string
20
+ if (process.platform === 'linux') {
21
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
22
+ state = stat.slice(stat.lastIndexOf(')') + 2)
23
+ } else {
24
+ const child = Bun.spawn(['ps', '-o', 'stat=', '-p', String(pid)], {
25
+ stdout: 'pipe',
26
+ stderr: 'ignore',
27
+ })
28
+ state = await new Response(child.stdout).text()
29
+ await child.exited
30
+ }
31
+ if (!closed && state.trimStart().startsWith('T')) process.kill(process.pid, 'SIGSTOP')
32
+ } catch {
33
+ // An exited or inaccessible child does not establish a stopped job.
34
+ } finally {
35
+ checking = false
36
+ }
37
+ }, 100)
38
+ timer.unref()
39
+ return {
40
+ close() {
41
+ closed = true
42
+ clearInterval(timer)
43
+ process.removeListener('SIGCONT', continued)
44
+ },
45
+ }
46
+ }
@@ -0,0 +1,9 @@
1
+ /** Process-local output guard, never lifecycle authority. Durable terminal
2
+ * release and lease acquisition decide when another generation may present. */
3
+ let released = false
4
+ export function releaseDispatchPresentation(): void {
5
+ released = true
6
+ }
7
+ export function ownsDispatchPresentation(): boolean {
8
+ return !released
9
+ }
@@ -1,10 +1,12 @@
1
- import { readDispatcherRunFacts, readOpenTick } from '../store/reduced-reads'
1
+ import { bunRuntimeArguments } from './runtime-spawn'
2
+ import { spawnUsingRuntime } from './dispatch-runtime-use'
3
+ import { distributionRoot } from '../distribution'
4
+ import { readDispatcherRunFacts } from '../store/reduced-reads'
2
5
  import { distributionPath } from '../distribution'
3
6
  import { DISPATCHER } from '../events/envelope'
4
7
  import type { BuildStore } from '../store/types'
5
8
 
6
9
  export const DISPATCH_CHILD_OPTIONS_ENV = 'AB_DISPATCH_CHILD_OPTIONS'
7
- const DEFAULT_STOP_TIMEOUT_MS = 5_000
8
10
 
9
11
  export interface DispatchChildOptions {
10
12
  targetRepo: string
@@ -75,48 +77,7 @@ export function installDispatchKernelSignalHandlers(
75
77
  }
76
78
  }
77
79
 
78
- export interface DispatchParentWatchDeps {
79
- intervalMs?: number
80
- currentParentPid?: () => number
81
- isAlive?: (pid: number) => boolean
82
- }
83
-
84
- /** A private kernel must never become a detached daemon if its terminal-owning
85
- * parent is killed directly rather than through the foreground process group.
86
- * Polling is deliberately local process liveness, not an operational IPC
87
- * channel; shutdown still converges through the normal AbortSignal boundary. */
88
- export function watchDispatchParent(
89
- parentPid: number,
90
- onParentExit: () => void,
91
- deps: DispatchParentWatchDeps = {},
92
- ): DispatchProcessHook {
93
- const currentParentPid = deps.currentParentPid ?? (() => process.ppid)
94
- const isAlive =
95
- deps.isAlive ??
96
- ((pid: number): boolean => {
97
- try {
98
- process.kill(pid, 0)
99
- return true
100
- } catch {
101
- return false
102
- }
103
- })
104
- let closed = false
105
- let timer: ReturnType<typeof setInterval>
106
- const close = (): void => {
107
- if (closed) return
108
- closed = true
109
- clearInterval(timer)
110
- }
111
- timer = setInterval(() => {
112
- if (currentParentPid() === parentPid && isAlive(parentPid)) return
113
- close()
114
- onParentExit()
115
- }, deps.intervalMs ?? 100)
116
- timer.unref?.()
117
- return { close }
118
- }
119
-
80
+ export { watchDispatchParent, type DispatchParentWatchDeps } from './dispatch-parent-watch'
120
81
  export interface DispatchChildSupervisorDeps {
121
82
  store: BuildStore
122
83
  /** Repository identity (§12) — the Store journal key. */
@@ -141,13 +102,17 @@ function defaultSpawn(input: {
141
102
  cwd: string
142
103
  env: Record<string, string>
143
104
  }): DispatchSubprocess {
144
- return Bun.spawn([process.execPath, input.entrypoint], {
145
- cwd: input.cwd,
146
- env: input.env,
147
- stdin: 'ignore',
148
- stdout: 'ignore',
149
- stderr: 'ignore',
150
- })
105
+ const { child, release } = spawnUsingRuntime(distributionRoot(), () =>
106
+ Bun.spawn(bunRuntimeArguments(input.entrypoint), {
107
+ cwd: input.cwd,
108
+ env: input.env,
109
+ stdin: 'ignore',
110
+ stdout: 'ignore',
111
+ stderr: 'ignore',
112
+ }),
113
+ )
114
+ void child.exited.finally(release)
115
+ return child
151
116
  }
152
117
 
153
118
  /** Spawn and reap the private kernel. Changing operational state never crosses
@@ -157,12 +122,12 @@ export function superviseDispatchChild(deps: DispatchChildSupervisorDeps): Dispa
157
122
  const entrypoint = deps.entrypoint ?? distributionPath('bin', 'ab-dispatch-kernel.ts')
158
123
  const env: Record<string, string> = {}
159
124
  for (const [key, value] of Object.entries(deps.env)) if (value !== undefined) env[key] = value
125
+ delete env.AB_DISPATCH_GENERATION
160
126
  env[DISPATCH_CHILD_OPTIONS_ENV] = JSON.stringify(deps.options)
161
127
  const child = (deps.spawn ?? defaultSpawn)({ entrypoint, cwd: deps.cwd ?? deps.repo, env })
162
128
 
163
129
  let requestedSignal: string | undefined
164
130
  let stopping = false
165
- let forced = false
166
131
  let stopPromise: Promise<void> | undefined
167
132
  // This is the sole supervisor writer of a missing stop fact. `stop()` only
168
133
  // chooses/awaits process termination, avoiding check-then-append races.
@@ -180,11 +145,8 @@ export function superviseDispatchChild(deps: DispatchChildSupervisorDeps): Dispa
180
145
  }
181
146
  }
182
147
 
183
- const outcome: DispatchChildOutcome = forced
184
- ? 'forced'
185
- : stopping && exitCode === 0 && child.signalCode === null
186
- ? 'normal'
187
- : 'abnormal'
148
+ const outcome: DispatchChildOutcome =
149
+ stopping && exitCode === 0 && child.signalCode === null ? 'normal' : 'abnormal'
188
150
  const error =
189
151
  outcome === 'abnormal'
190
152
  ? `kernel process exited with status ${exitCode}${
@@ -231,39 +193,9 @@ export function superviseDispatchChild(deps: DispatchChildSupervisorDeps): Dispa
231
193
  }
232
194
  }
233
195
  child.kill('SIGINT')
234
- const timeout = deps.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS
235
- const stopped = await Promise.race([
236
- child.exited.then(() => true),
237
- new Promise<false>((resolve) => setTimeout(() => resolve(false), timeout)),
238
- ])
239
- if (stopped || child.exitCode !== null) return
240
-
241
- // A dispatcher tick may hold an external ticket claim before its build
242
- // record exists. Killing that turn can make the ticket disappear from
243
- // Ready with no durable build to recover. Let an open tick reach its
244
- // normal boundary; all non-tick work is lease-backed/recoverable and a
245
- // child stuck there is safe to terminate.
246
- let open = true
247
- try {
248
- const record = await deps.store.getRepo(deps.repo)
249
- open =
250
- record?.tick?.run === deps.run
251
- ? record.tick.open !== undefined
252
- : await readOpenTick(deps.store, deps.repo, deps.run, false)
253
- } catch {
254
- // Unreadable telemetry cannot authorize an unsafe kill.
255
- }
256
- // The child may have exited while the asynchronous journal read was in
257
- // flight. Re-check at the force boundary so evidence never claims a
258
- // SIGKILL that was not actually sent.
259
- if (child.exitCode !== null) return
260
- if (open) {
261
- await child.exited
262
- return
263
- }
264
-
265
- forced = true
266
- child.kill('SIGKILL')
196
+ // The kernel owns local runner suspension and its durable writes.
197
+ // Neither an elapsed deadline nor a closed claim tick proves those
198
+ // writes finished. Keep graceful signal handlers installed while waiting.
267
199
  await child.exited
268
200
  })()
269
201
  return stopPromise
@@ -0,0 +1,47 @@
1
+ import type { Config } from '../config/schema'
2
+ import type { PluginRegistry } from '../plugins/registry'
3
+ import type { Exec } from '../ports/workspace/git-worktree'
4
+
5
+ /** Shared validation without opening workspaces, claims, runners or polling. */
6
+ export async function validateWorkspaceDispatchConfiguration(
7
+ config: Config,
8
+ opts: {
9
+ repository?: string
10
+ targetRepo: string
11
+ env: Record<string, string | undefined>
12
+ exec: Exec
13
+ },
14
+ plugins: PluginRegistry,
15
+ ): Promise<void> {
16
+ // Dispatch preflight is capability-driven (AUT-516): forge support, origin
17
+ // validation, and required environment all read the selected provider's
18
+ // registration declarations — builtin and plugin alike — instead of naming
19
+ // a provider.
20
+ const workspaceCaps = plugins.workspaceProviders.get(config.workspace.provider)?.capabilities
21
+ if (workspaceCaps?.supportedForges !== undefined) {
22
+ if (!workspaceCaps.supportedForges.includes(config.forge)) {
23
+ throw new Error(
24
+ workspaceCaps.forgeDispatchMessage ??
25
+ `workspace provider "${config.workspace.provider}" does not support forge "${config.forge}"`,
26
+ )
27
+ }
28
+ }
29
+ if (workspaceCaps?.validateOrigin !== undefined && !opts.repository) {
30
+ const origin = await opts.exec(['git', 'remote', 'get-url', 'origin'], {
31
+ cwd: opts.targetRepo,
32
+ })
33
+ if (origin.exitCode !== 0)
34
+ throw new Error(
35
+ workspaceCaps.originReadFailureMessage ??
36
+ `workspace provider "${config.workspace.provider}" requires a readable Git origin`,
37
+ )
38
+ workspaceCaps.validateOrigin(origin.stdout.trim())
39
+ }
40
+ for (const group of workspaceCaps?.requiredEnv ?? []) {
41
+ if (group.dispatchMessage === undefined) continue
42
+ const satisfied = group.alternatives.some((names) =>
43
+ names.every((name) => opts.env[name] !== undefined && opts.env[name] !== ''),
44
+ )
45
+ if (!satisfied) throw new Error(group.dispatchMessage)
46
+ }
47
+ }
@@ -1,11 +1,16 @@
1
+ import { DISPATCH_HANDOFF_EVENT_TYPES } from '../store/repo-state-events'
1
2
  import { type RepositoryEvent, validateRepositoryEventWrite } from '../events/repository'
2
3
  import { defineReducer } from '../kernel/incremental'
3
4
  import { loadReducerSnapshot, persistReducerSnapshot } from '../store/snapshots'
4
5
  import type { BuildStore, Clock } from '../store/types'
5
6
 
7
+ const handoffTypes = new Set<string>(DISPATCH_HANDOFF_EVENT_TYPES)
8
+
6
9
  export function isDashboardRepositoryEvent(event: RepositoryEvent): boolean {
7
10
  return (
11
+ handoffTypes.has(event.type) ||
8
12
  event.type.startsWith('harvest.') ||
13
+ event.type === 'tickets.migration-recorded' ||
9
14
  event.type === 'dispatcher.intake-set' ||
10
15
  event.type === 'dispatcher.pause-set' ||
11
16
  event.type === 'dispatcher.auto-merge-default-set'
@@ -13,7 +18,7 @@ export function isDashboardRepositoryEvent(event: RepositoryEvent): boolean {
13
18
  }
14
19
 
15
20
  export const dispatchFrontendReducer = defineReducer({
16
- version: 2,
21
+ version: 4,
17
22
  initial: (): { retained: RepositoryEvent[]; incompleteIdentities: boolean } => ({
18
23
  retained: [],
19
24
  incompleteIdentities: true,