@defrex/autobuild 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +5 -13
  2. package/SPEC.md +140 -10
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +119 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/architecture.md +107 -8
  7. package/docs/build-store.md +3 -41
  8. package/docs/cli.md +14 -0
  9. package/docs/configuration-overview.md +111 -0
  10. package/docs/configuration.md +260 -141
  11. package/docs/dispatcher-hosting.md +18 -33
  12. package/docs/intake.md +2 -0
  13. package/docs/merge-policy.md +1 -3
  14. package/docs/operating.md +1 -2
  15. package/docs/operator-api.md +100 -47
  16. package/docs/operator-surfaces.md +3 -20
  17. package/docs/overview.md +1 -1
  18. package/docs/plugin-authoring.md +21 -0
  19. package/docs/remote-store-protocol.md +198 -89
  20. package/docs/remote-ticket-protocol.md +29 -49
  21. package/docs/seams.md +8 -8
  22. package/docs/setup.md +34 -129
  23. package/docs/ticket-sources.md +18 -0
  24. package/docs/troubleshooting.md +7 -11
  25. package/docs/upgrading.md +1 -1
  26. package/docs/workspaces.md +4 -4
  27. package/package.json +14 -5
  28. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  29. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  30. package/packages/core/src/accounts/local-credentials.ts +194 -0
  31. package/packages/core/src/accounts/local-inference.ts +106 -0
  32. package/packages/core/src/accounts/local-owner.ts +123 -0
  33. package/packages/core/src/accounts/sensitive.ts +2 -0
  34. package/packages/core/src/cli/accounts.ts +147 -0
  35. package/packages/core/src/cli/binary.ts +3 -1
  36. package/packages/core/src/cli/connect.ts +3 -3
  37. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  38. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  39. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  40. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  41. package/packages/core/src/cli/dispatch.ts +71 -2
  42. package/packages/core/src/cli/help.ts +16 -0
  43. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  44. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  45. package/packages/core/src/cli/init-validation.ts +160 -18
  46. package/packages/core/src/cli/main.ts +44 -0
  47. package/packages/core/src/cli/publication-settlement.ts +4 -1
  48. package/packages/core/src/cli/secrets.ts +173 -0
  49. package/packages/core/src/cli/store-opening.ts +11 -1
  50. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  51. package/packages/core/src/cli/watch.ts +3 -1
  52. package/packages/core/src/config/accounts.ts +101 -0
  53. package/packages/core/src/config/live.ts +14 -1
  54. package/packages/core/src/config/roles.ts +54 -3
  55. package/packages/core/src/config/schema.ts +60 -0
  56. package/packages/core/src/events/compatibility.ts +2 -1
  57. package/packages/core/src/events/payloads.ts +3 -0
  58. package/packages/core/src/events/repository.ts +2 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +3 -0
  60. package/packages/core/src/kernel/reducer.ts +4 -1
  61. package/packages/core/src/operator/index.ts +2 -0
  62. package/packages/core/src/operator/protocol.ts +6 -0
  63. package/packages/core/src/operator/registry.ts +22 -1
  64. package/packages/core/src/operator/tickets.ts +25 -4
  65. package/packages/core/src/plugins/manifest.ts +2 -1
  66. package/packages/core/src/ports/runner/account-env.ts +88 -0
  67. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  68. package/packages/core/src/ports/runner/claude.ts +26 -2
  69. package/packages/core/src/ports/runner/codex.ts +63 -31
  70. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  71. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  72. package/packages/core/src/ports/runner/routing.ts +35 -4
  73. package/packages/core/src/ports/tickets/contract.ts +58 -0
  74. package/packages/core/src/ports/tickets/tree.ts +1 -1
  75. package/packages/core/src/ports/types.ts +28 -7
  76. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  77. package/packages/core/src/ports/workspace/build-execution.ts +6 -1
  78. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  79. package/packages/core/src/ports/workspace/create.ts +2 -0
  80. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  81. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  82. package/packages/core/src/ports/workspace/vercel-sandbox.ts +125 -35
  83. package/packages/core/src/processes/build-runner.ts +32 -1
  84. package/packages/core/src/processes/dispatcher.ts +23 -0
  85. package/packages/core/src/processes/execution-settlement.ts +21 -3
  86. package/packages/core/src/processes/harvest-runner.ts +68 -8
  87. package/packages/core/src/project-secrets.ts +105 -0
  88. package/packages/core/src/secret-name.ts +41 -0
  89. package/packages/core/src/store/account-redaction.ts +156 -0
  90. package/packages/core/src/store/contract.ts +3 -1
  91. package/packages/core/src/store/reducer-value-shapes.json +2889 -2781
  92. package/packages/core/src/store/remote/client.ts +42 -47
  93. package/packages/core/src/store/remote/compatibility.ts +18 -0
  94. package/packages/core/src/testing/dispatch-read-budget.ts +122 -0
  95. package/packages/core/src/testing/index.ts +1 -0
  96. package/packages/core/src/testing/reduced-read-budget.ts +47 -0
  97. package/skills/guide/SKILL.md +120 -30
  98. package/skills/guide/references/accounts.md +119 -0
  99. package/skills/guide/references/merge-policy.md +1 -3
  100. package/skills/guide/references/operator-api.md +100 -47
  101. package/skills/guide/references/plugin-authoring.md +21 -0
  102. package/skills/guide/references/remote-store-protocol.md +198 -89
  103. package/skills/guide/references/remote-ticket-protocol.md +29 -49
  104. package/skills/guide/references/setup.md +34 -129
  105. package/skills/harvest/SKILL.md +3 -1
  106. package/skills/harvest-review/SKILL.md +3 -1
  107. package/skills/operate/SKILL.md +5 -6
  108. package/skills/spec/SKILL.md +1 -1
  109. package/skills/tickets/SKILL.md +3 -2
  110. package/templates/hosted-service/package.json +2 -2
  111. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  112. package/docs/hosted-dispatcher.md +0 -278
  113. package/docs/hosted-service.md +0 -304
  114. package/docs/mcp.md +0 -150
@@ -6,7 +6,16 @@ import { spawnExec } from '../ports/workspace/git-worktree'
6
6
  import { parseDispatchArgs } from './dispatch-args'
7
7
  import { readDispatchUpgrade, readDispatcherRunFacts } from '../store/reduced-reads'
8
8
  import { cachedRuntime } from './dispatch-runtime-cache'
9
- import type { GenerationLaunch } from './dispatch-launch-contract'
9
+ import type {
10
+ GenerationLaunch,
11
+ UpgradeCondition,
12
+ UpgradeGuards,
13
+ UpgradeProjection,
14
+ ConditionalUpgradeResult,
15
+ } from './dispatch-launch-contract'
16
+ import { validChangePosition } from './dispatch-launch-contract'
17
+ import type { UpgradeRun } from '../kernel/dispatch-upgrade'
18
+ type DispatcherRunFacts = Awaited<ReturnType<typeof readDispatcherRunFacts>>['value']
10
19
  import type { Handoff } from '../kernel/dispatch-upgrade'
11
20
 
12
21
  /** Once a held run identifies its journal, readers retain that transport
@@ -67,66 +76,138 @@ export async function readHandoff(
67
76
  const selected = live ? state?.prepared : state?.handoff
68
77
  if (!selected || (!live && state?.completed) || state?.failure) return undefined
69
78
  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
79
+ return validateHandoff(launch, selectHandoff(launch, state, facts, live))
89
80
  } finally {
90
81
  await opened.store.close()
91
82
  }
92
83
  }
93
84
 
85
+ /** Durable selection is separate from local cache validation. */
86
+ function selectHandoff(
87
+ launch: GenerationLaunch,
88
+ state: UpgradeRun | undefined,
89
+ facts: DispatcherRunFacts,
90
+ live: boolean,
91
+ ): Handoff | null {
92
+ const selected = live ? state?.prepared : state?.handoff
93
+ if (!selected || (!live && state?.completed) || state?.failure) return null
94
+ const handoff = selected.payload
95
+ if (
96
+ (!live &&
97
+ (facts.stop?.type !== 'dispatcher.run-stopped' ||
98
+ facts.stop.payload.outcome !== 'normal' ||
99
+ facts.stop.payload.signal !== undefined)) ||
100
+ facts.stopRequest ||
101
+ handoff.lineage !== launch.lineage
102
+ )
103
+ return null
104
+ return handoff
105
+ }
106
+ async function validateHandoff(
107
+ launch: GenerationLaunch,
108
+ handoff: Handoff | null,
109
+ ): Promise<Handoff | undefined> {
110
+ if (!handoff || handoff.lineage !== launch.lineage || handoff.run !== launch.run) return undefined
111
+ const expected = join(launch.checkout, '.autobuild/runtime', handoff.cacheId, 'distribution')
112
+ if (
113
+ resolve(handoff.root) !== expected ||
114
+ dirname(dirname(handoff.root)) !== join(launch.checkout, '.autobuild/runtime')
115
+ )
116
+ return undefined
117
+ return (await cachedRuntime(handoff.root))?.id === handoff.cacheId ? handoff : undefined
118
+ }
119
+ async function localGuards(launch: GenerationLaunch, guards: UpgradeGuards) {
120
+ return {
121
+ handoff: (await validateHandoff(launch, guards.handoff)) ?? null,
122
+ rollbackRetained:
123
+ guards.rollbackRecorded &&
124
+ (!guards.failedRoot || rollbackRuntimeRetained(guards.failedRoot, launch.lineage!)),
125
+ }
126
+ }
127
+ export function readUpgradeProjection(
128
+ launch: GenerationLaunch,
129
+ argv: string[],
130
+ env: Record<string, string | undefined>,
131
+ ): Promise<UpgradeProjection>
132
+ export function readUpgradeProjection(
133
+ launch: GenerationLaunch,
134
+ argv: string[],
135
+ env: Record<string, string | undefined>,
136
+ options: { openStore?: StoreOpener; condition?: UpgradeCondition },
137
+ ): Promise<UpgradeProjection | ConditionalUpgradeResult>
94
138
  export async function readUpgradeProjection(
95
139
  launch: GenerationLaunch,
96
140
  argv: string[],
97
141
  env: Record<string, string | undefined>,
98
- ) {
99
- const opened = await openGenerationStore(launch, argv, env)
142
+ options: { openStore?: StoreOpener; condition?: UpgradeCondition } = {},
143
+ ): Promise<UpgradeProjection | ConditionalUpgradeResult> {
144
+ const opened = await openGenerationStore(launch, argv, env, options.openStore)
100
145
  try {
146
+ const condition = options.condition
147
+ // Sample before projection reads: concurrent appends invalidate the next poll.
148
+ const position =
149
+ condition && launch.journal
150
+ ? await opened.store.getRepoChangePosition(opened.repo)
151
+ : undefined
152
+ if (position !== undefined && !validChangePosition(position))
153
+ throw new Error('invalid upgrade change position')
154
+ if (position !== undefined && condition?.position === position && condition.guards) {
155
+ return {
156
+ conditionalVersion: 1,
157
+ kind: 'unchanged',
158
+ identity: condition.identity,
159
+ position,
160
+ ...(await localGuards(launch, condition.guards)),
161
+ }
162
+ }
101
163
  const record = await opened.store.getRepo(opened.repo)
102
164
  const journal =
103
165
  launch.journal ??
104
166
  (record?.lease?.holder === launch.run
105
167
  ? { storeRef: opened.storeRef, repo: opened.repo }
106
168
  : 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,
169
+ let projection: UpgradeProjection = { version: 1, handoff: null, takeover: false }
170
+ let guards: UpgradeGuards | undefined
171
+ if (journal) {
172
+ const upgrades = (await readDispatchUpgrade(opened.store, opened.repo)).value
173
+ const state = upgrades.runs[launch.run!]
174
+ const facts =
175
+ launch.run && launch.lineage && record && state?.prepared && !state.failure
176
+ ? (await readDispatcherRunFacts(opened.store, opened.repo, launch.run)).value
177
+ : undefined
178
+ const rollbackRecorded =
179
+ !!launch.rollback && upgrades.rollbackIds.includes(launch.rollback.correlation)
180
+ guards = {
181
+ handoff: facts ? selectHandoff(launch, state, facts, true) : null,
182
+ rollbackRecorded,
183
+ failedRoot:
184
+ rollbackRecorded && launch.lineage
185
+ ? (upgrades.holds[launch.lineage]?.payload.failedRoot ?? null)
186
+ : null,
187
+ }
188
+ projection = {
189
+ version: 1,
190
+ journal,
191
+ rollbackVersion: 1,
192
+ ...(await localGuards(launch, guards)),
193
+ takeover: !!state?.takeover,
194
+ takeoverAt: state?.takeover?.ts,
195
+ takeoverPayload: state?.takeover?.payload,
196
+ completed: !!state?.completed,
197
+ accepted: !!state?.handoff,
198
+ successor: state?.request?.payload.successor,
199
+ released: !!state?.released,
200
+ }
129
201
  }
202
+ return condition
203
+ ? {
204
+ conditionalVersion: 1,
205
+ kind: 'full',
206
+ identity: condition.identity,
207
+ projection,
208
+ ...(position !== undefined && guards ? { position, guards } : {}),
209
+ }
210
+ : projection
130
211
  } finally {
131
212
  await opened.store.close()
132
213
  }
@@ -168,3 +168,190 @@ export function validRecoveryContext(launch: GenerationLaunch): boolean {
168
168
  !launch.recovery
169
169
  )
170
170
  }
171
+
172
+ /** Optional runtime-reader extension; independent of launch/overlap v1. */
173
+ export const DISPATCH_CONDITIONAL_VERSION = 1
174
+ export const DISPATCH_CONDITIONAL_ENV = 'AB_DISPATCH_CONDITIONAL_UPGRADE'
175
+ export interface UpgradeGuards {
176
+ handoff: import('../kernel/dispatch-upgrade').Handoff | null
177
+ rollbackRecorded: boolean
178
+ failedRoot: string | null
179
+ }
180
+ export interface UpgradeProjection {
181
+ version: 1
182
+ handoff: import('../kernel/dispatch-upgrade').Handoff | null
183
+ takeover: boolean
184
+ journal?: GenerationLaunch['journal']
185
+ rollbackVersion?: 1
186
+ rollbackRetained?: boolean
187
+ takeoverAt?: string
188
+ takeoverPayload?: unknown
189
+ completed?: boolean
190
+ accepted?: boolean
191
+ successor?: string
192
+ released?: boolean
193
+ }
194
+ export interface UpgradeCondition {
195
+ version: 1
196
+ identity: string
197
+ position?: string
198
+ guards?: UpgradeGuards
199
+ }
200
+ export type ConditionalUpgradeResult =
201
+ | {
202
+ conditionalVersion: 1
203
+ kind: 'full'
204
+ identity: string
205
+ position?: string
206
+ guards?: UpgradeGuards
207
+ projection: UpgradeProjection
208
+ }
209
+ | {
210
+ conditionalVersion: 1
211
+ kind: 'unchanged'
212
+ identity: string
213
+ position: string
214
+ handoff: UpgradeProjection['handoff']
215
+ rollbackRetained: boolean
216
+ }
217
+
218
+ export function validChangePosition(value: unknown): value is string {
219
+ return typeof value === 'string' && /^(0|[1-9][0-9]*)$/.test(value)
220
+ }
221
+ // The public launcher outlives its runtimes. Only these fields belong to its
222
+ // contract; target/source descriptors and future runtime fields remain opaque.
223
+ const launcherHandoffFields = ['root', 'cacheId', 'run', 'lineage', 'correlation'] as const
224
+ function validHandoff(value: unknown): boolean {
225
+ if (value === null) return true
226
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
227
+ const h = value as Record<string, unknown>
228
+ return (
229
+ launcherHandoffFields.every((key) => typeof h[key] === 'string') && isAbsolute(h.root as string)
230
+ )
231
+ }
232
+ function sameLauncherHandoff(
233
+ left: UpgradeProjection['handoff'],
234
+ right: UpgradeGuards['handoff'],
235
+ ): boolean {
236
+ return (
237
+ left === null ||
238
+ (right !== null && launcherHandoffFields.every((key) => left[key] === right[key]))
239
+ )
240
+ }
241
+ function validUpgradeProjection(value: unknown): value is UpgradeProjection {
242
+ if (!value || typeof value !== 'object') return false
243
+ const p = value as UpgradeProjection
244
+ return (
245
+ p.version === 1 &&
246
+ validHandoff(p.handoff) &&
247
+ typeof p.takeover === 'boolean' &&
248
+ ['rollbackRetained', 'completed', 'accepted', 'released'].every((key) => {
249
+ const flag = (p as unknown as Record<string, unknown>)[key]
250
+ return flag === undefined || typeof flag === 'boolean'
251
+ }) &&
252
+ (p.rollbackVersion === undefined || p.rollbackVersion === 1) &&
253
+ (p.takeoverAt === undefined || typeof p.takeoverAt === 'string') &&
254
+ (p.successor === undefined || typeof p.successor === 'string') &&
255
+ (p.journal === undefined ||
256
+ (!!p.journal && typeof p.journal.storeRef === 'string' && typeof p.journal.repo === 'string'))
257
+ )
258
+ }
259
+ export function validUpgradeGuards(value: unknown): value is UpgradeGuards {
260
+ if (!value || typeof value !== 'object') return false
261
+ const v = value as UpgradeGuards
262
+ return (
263
+ validHandoff(v.handoff) &&
264
+ typeof v.rollbackRecorded === 'boolean' &&
265
+ (v.failedRoot === null || (typeof v.failedRoot === 'string' && isAbsolute(v.failedRoot))) &&
266
+ (v.rollbackRecorded || v.failedRoot === null)
267
+ )
268
+ }
269
+ export function consumeUpgradeCondition(
270
+ env: Record<string, string | undefined>,
271
+ ): UpgradeCondition | undefined {
272
+ const raw = env[DISPATCH_CONDITIONAL_ENV]
273
+ delete env[DISPATCH_CONDITIONAL_ENV]
274
+ if (raw === undefined) return undefined
275
+ const v = JSON.parse(raw) as UpgradeCondition
276
+ if (
277
+ v?.version !== 1 ||
278
+ typeof v.identity !== 'string' ||
279
+ !v.identity ||
280
+ (v.position === undefined
281
+ ? v.guards !== undefined
282
+ : !validChangePosition(v.position) || !validUpgradeGuards(v.guards))
283
+ )
284
+ throw new Error('invalid conditional upgrade request')
285
+ return v
286
+ }
287
+
288
+ /** One cache per reader/query. A helper still runs on every call, so a broken
289
+ * successor can never be hidden by its last successful projection. */
290
+ export function conditionalUpgradeClient() {
291
+ let cache:
292
+ | { identity: string; position: string; guards: UpgradeGuards; projection: UpgradeProjection }
293
+ | undefined
294
+ return async (
295
+ identity: string,
296
+ read: (request: UpgradeCondition) => Promise<unknown>,
297
+ ): Promise<UpgradeProjection> => {
298
+ if (cache?.identity !== identity) cache = undefined
299
+ try {
300
+ const request: UpgradeCondition = {
301
+ version: 1,
302
+ identity,
303
+ ...(cache ? { position: cache.position, guards: cache.guards } : {}),
304
+ }
305
+ const raw = await read(request)
306
+ if (!raw || typeof raw !== 'object') throw new Error('invalid upgrade reader response')
307
+ const result = raw as ConditionalUpgradeResult
308
+ if (!('conditionalVersion' in raw)) {
309
+ cache = undefined
310
+ const legacy = raw as UpgradeProjection
311
+ if (!validUpgradeProjection(legacy))
312
+ throw new Error('invalid legacy upgrade reader response')
313
+ return legacy
314
+ }
315
+ if (result.conditionalVersion !== 1 || result.identity !== identity)
316
+ throw new Error('incompatible conditional upgrade reader')
317
+ if (result.kind === 'unchanged') {
318
+ if (
319
+ !cache ||
320
+ result.position !== cache.position ||
321
+ !validHandoff(result.handoff) ||
322
+ typeof result.rollbackRetained !== 'boolean' ||
323
+ !sameLauncherHandoff(result.handoff, cache.guards.handoff) ||
324
+ (result.rollbackRetained && !cache.guards.rollbackRecorded)
325
+ )
326
+ throw new Error('invalid unchanged upgrade response')
327
+ cache.projection = {
328
+ ...cache.projection,
329
+ handoff: result.handoff,
330
+ rollbackRetained: result.rollbackRetained,
331
+ }
332
+ return cache.projection
333
+ }
334
+ if (
335
+ result.kind !== 'full' ||
336
+ !validUpgradeProjection(result.projection) ||
337
+ (result.position === undefined
338
+ ? result.guards !== undefined
339
+ : !validChangePosition(result.position) || !validUpgradeGuards(result.guards))
340
+ )
341
+ throw new Error('invalid full upgrade response')
342
+ cache =
343
+ result.position !== undefined && result.guards
344
+ ? {
345
+ identity,
346
+ position: result.position,
347
+ guards: result.guards,
348
+ projection: result.projection,
349
+ }
350
+ : undefined
351
+ return result.projection
352
+ } catch (error) {
353
+ cache = undefined
354
+ throw error
355
+ }
356
+ }
357
+ }
@@ -28,6 +28,8 @@ import {
28
28
  } from './dispatch-runtime-use'
29
29
  import {
30
30
  DISPATCH_GENERATION_ENV,
31
+ DISPATCH_CONDITIONAL_ENV,
32
+ conditionalUpgradeClient,
31
33
  DISPATCH_LAUNCH_VERSION,
32
34
  DISPATCH_OVERLAP_VERSION,
33
35
  GENERATION_SIGNALS,
@@ -35,6 +37,27 @@ import {
35
37
  generationResult,
36
38
  } from './dispatch-launch-contract'
37
39
 
40
+ /** Preserve subprocess diagnostics; stdout belongs exclusively to projection JSON. */
41
+ export function generationReaderResult(code: number, output: string, error: string) {
42
+ if (code !== 0) throw new Error(`generation journal reader failed: ${error}`)
43
+ return output ? JSON.parse(output) : null
44
+ }
45
+
46
+ /** At most two messages are retained: active and predecessor for this episode. */
47
+ export function generationReaderFailures(stderr: (message: string) => void) {
48
+ const failures = new Map<string, string>()
49
+ return {
50
+ report(role: 'active' | 'predecessor', error: unknown) {
51
+ const message = error instanceof Error ? error.message : String(error)
52
+ if (failures.get(role) !== message) stderr(`${role} generation reader: ${message}`)
53
+ failures.set(role, message)
54
+ },
55
+ clear() {
56
+ failures.clear()
57
+ },
58
+ }
59
+ }
60
+
38
61
  // Filesystem/process-only dependencies above are evaluated before installation.
39
62
  async function gitExec(cmd: string[], options: { cwd?: string }) {
40
63
  const child = Bun.spawn(cmd, { cwd: options.cwd, stdout: 'pipe', stderr: 'pipe' })
@@ -201,8 +224,25 @@ export async function launchDispatcher(argv: string[]): Promise<number> {
201
224
  new Response(helper.stdout).text(),
202
225
  new Response(helper.stderr).text(),
203
226
  ])
204
- if (code !== 0) throw new Error(`generation journal reader failed: ${error}`)
205
- return output ? JSON.parse(output) : null
227
+ return generationReaderResult(code, output, error)
228
+ }
229
+ const readConditional = conditionalUpgradeClient()
230
+ const fallbackConditional = conditionalUpgradeClient()
231
+ const upgradeReader = (record: Pick<Child, 'runtime' | 'env'>, fallback = false) => {
232
+ const identity = JSON.stringify([
233
+ record.runtime.root,
234
+ record.env[DISPATCH_GENERATION_ENV],
235
+ argv,
236
+ ])
237
+ return (fallback ? fallbackConditional : readConditional)(identity, (condition) =>
238
+ reader(
239
+ {
240
+ ...record,
241
+ env: { ...record.env, [DISPATCH_CONDITIONAL_ENV]: JSON.stringify(condition) },
242
+ },
243
+ '--read-upgrade',
244
+ ),
245
+ )
206
246
  }
207
247
  let active: Child | undefined
208
248
  let pending: { record: Child; correlation: string } | undefined
@@ -278,6 +318,7 @@ export async function launchDispatcher(argv: string[]): Promise<number> {
278
318
  undefined,
279
319
  bootstrap.rollbackVersion === 1,
280
320
  )
321
+ const readerFailures = generationReaderFailures((message) => console.error(message))
281
322
  for (;;) {
282
323
  if (signal) break
283
324
  // Once recovery has expired, a failed child must retain its ordinary
@@ -307,22 +348,10 @@ export async function launchDispatcher(argv: string[]): Promise<number> {
307
348
  released?: boolean
308
349
  }
309
350
  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 {
351
+ projection = await upgradeReader(active)
352
+ } catch (error) {
353
+ if (signal) break
354
+ readerFailures.report('active', error)
326
355
  // A broken target may not even load its reader. Use the known cached
327
356
  // predecessor's reader with the same journal/run query identity.
328
357
  const healthy = pending?.record ?? recovery?.previous
@@ -332,18 +361,21 @@ export async function launchDispatcher(argv: string[]): Promise<number> {
332
361
  ...healthy.launch,
333
362
  runtimeRoot: healthy.runtime.root,
334
363
  run: active.launch.run,
364
+ journal: active.launch.journal,
335
365
  predecessor: undefined,
336
366
  rollback: undefined,
337
367
  recovery: undefined,
338
368
  }
339
- projection = await reader(
369
+ projection = await upgradeReader(
340
370
  {
341
371
  runtime: healthy.runtime,
342
372
  env: { ...healthy.env, [DISPATCH_GENERATION_ENV]: JSON.stringify(query) },
343
373
  },
344
- '--read-upgrade',
374
+ true,
345
375
  )
346
- } catch {
376
+ } catch (error) {
377
+ if (signal) break
378
+ readerFailures.report('predecessor', error)
347
379
  await new Promise<void>((resolve) => setTimeout(resolve, 100))
348
380
  continue
349
381
  }
@@ -356,6 +388,7 @@ export async function launchDispatcher(argv: string[]): Promise<number> {
356
388
  continue
357
389
  }
358
390
  }
391
+ readerFailures.clear()
359
392
  if (active.launch.rollback && projection.rollbackRetained) {
360
393
  for (const root of [
361
394
  active.launch.rollback.failed.root,
@@ -169,7 +169,12 @@ async function runGenerationPreflight(
169
169
  plugins,
170
170
  { repoRoot: launch.checkout, env },
171
171
  )
172
- createRuntimeResolver(runtimes, config.roles, config.policy.sessionBudgetSeconds)
172
+ createRuntimeResolver(
173
+ runtimes,
174
+ config.roles,
175
+ config.policy.sessionBudgetSeconds,
176
+ config.accounts,
177
+ )
173
178
  const facts = (await readDispatcherRunFacts(opened.store, opened.repo, handoff.run)).value
174
179
  if (facts.stopRequest || facts.stop)
175
180
  throw new Error('predecessor stopped during preflight')