@defrex/autobuild 1.0.0-beta.3 → 1.0.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 (168) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +362 -56
  3. package/bin/ab-dispatch-generation.ts +93 -0
  4. package/docs/agent-runtimes.md +157 -0
  5. package/docs/answering-blocked-builds.md +21 -3
  6. package/docs/architecture.md +166 -7
  7. package/docs/build-store.md +123 -0
  8. package/docs/builds.md +82 -0
  9. package/docs/cli.md +48 -0
  10. package/docs/configuration-overview.md +93 -0
  11. package/docs/configuration.md +1778 -188
  12. package/docs/dispatcher-hosting.md +115 -0
  13. package/docs/dispatcher.md +59 -0
  14. package/docs/forges.md +121 -0
  15. package/docs/getting-started.md +60 -0
  16. package/docs/glossary.md +60 -0
  17. package/docs/hosted-service.md +2 -2
  18. package/docs/intake.md +48 -0
  19. package/docs/integration-overview.md +81 -0
  20. package/docs/integration-tree.md +87 -2
  21. package/docs/integration.md +54 -0
  22. package/docs/operating.md +114 -0
  23. package/docs/operator-api.md +64 -11
  24. package/docs/operator-surfaces.md +90 -0
  25. package/docs/overview.md +49 -0
  26. package/docs/plugin-authoring.md +426 -0
  27. package/docs/remote-store-protocol.md +12 -9
  28. package/docs/restacking.md +4 -1
  29. package/docs/seams.md +66 -0
  30. package/docs/setup.md +28 -6
  31. package/docs/skills.md +119 -0
  32. package/docs/spec-standard.md +23 -5
  33. package/docs/ticket-sources.md +132 -0
  34. package/docs/tickets.md +69 -0
  35. package/docs/troubleshooting.md +111 -0
  36. package/docs/upgrading.md +50 -0
  37. package/docs/verification.md +146 -0
  38. package/docs/website.md +47 -5
  39. package/docs/workspaces.md +152 -0
  40. package/package.json +5 -4
  41. package/packages/core/src/cli/artifact.ts +5 -4
  42. package/packages/core/src/cli/attention.ts +2 -0
  43. package/packages/core/src/cli/binary-direct.ts +190 -0
  44. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  45. package/packages/core/src/cli/binary.ts +24 -210
  46. package/packages/core/src/cli/build-control.ts +105 -2
  47. package/packages/core/src/cli/context.ts +41 -1
  48. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  49. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  50. package/packages/core/src/cli/dashboard/integration-detail.ts +3 -0
  51. package/packages/core/src/cli/dashboard/model.ts +34 -10
  52. package/packages/core/src/cli/dashboard/render.ts +24 -2
  53. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  54. package/packages/core/src/cli/dispatch-args.ts +53 -0
  55. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  56. package/packages/core/src/cli/dispatch-frontend.ts +52 -5
  57. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  58. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  59. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  60. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  61. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  62. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  63. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  64. package/packages/core/src/cli/dispatch-process.ts +22 -90
  65. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  66. package/packages/core/src/cli/dispatch-repository-feed.ts +5 -1
  67. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  68. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  69. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  70. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  71. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  72. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  73. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  74. package/packages/core/src/cli/dispatch.ts +604 -60
  75. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  76. package/packages/core/src/cli/env.ts +1 -1
  77. package/packages/core/src/cli/harvest.ts +28 -11
  78. package/packages/core/src/cli/help.ts +10 -5
  79. package/packages/core/src/cli/installation.ts +5 -3
  80. package/packages/core/src/cli/main-checkout.ts +59 -0
  81. package/packages/core/src/cli/main.ts +15 -45
  82. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  83. package/packages/core/src/cli/repo-state.ts +3 -58
  84. package/packages/core/src/cli/repository-status.ts +67 -3
  85. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  86. package/packages/core/src/cli/status.ts +57 -3
  87. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  88. package/packages/core/src/cli/wait.ts +3 -0
  89. package/packages/core/src/cli/watch.ts +7 -0
  90. package/packages/core/src/config/landing.ts +8 -0
  91. package/packages/core/src/config/live.ts +1 -0
  92. package/packages/core/src/config/reference-metadata.ts +31 -0
  93. package/packages/core/src/config/reference.ts +342 -0
  94. package/packages/core/src/config/roles.ts +1 -1
  95. package/packages/core/src/config/schema.ts +352 -10
  96. package/packages/core/src/distribution-packaging.ts +116 -0
  97. package/packages/core/src/events/catalog.ts +6 -0
  98. package/packages/core/src/events/payloads.ts +53 -9
  99. package/packages/core/src/events/policy.ts +25 -0
  100. package/packages/core/src/events/repository.ts +184 -4
  101. package/packages/core/src/events/runtime.ts +16 -0
  102. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +2515 -78
  103. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  104. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  105. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  106. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  107. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  108. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  109. package/packages/core/src/kernel/harvest.ts +98 -4
  110. package/packages/core/src/kernel/integration-attention.ts +20 -0
  111. package/packages/core/src/kernel/integration-state.ts +80 -11
  112. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  113. package/packages/core/src/kernel/mixed-version.ts +34 -0
  114. package/packages/core/src/kernel/node-polling.ts +160 -0
  115. package/packages/core/src/kernel/read-facts.ts +40 -5
  116. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  117. package/packages/core/src/kernel/reducer.ts +75 -14
  118. package/packages/core/src/kernel/service-facts.ts +11 -4
  119. package/packages/core/src/ontology.ts +2 -2
  120. package/packages/core/src/open-map.ts +3 -1
  121. package/packages/core/src/operator/presentation.ts +7 -0
  122. package/packages/core/src/operator/query.ts +6 -2
  123. package/packages/core/src/operator/registry.ts +1 -1
  124. package/packages/core/src/plugins/load.ts +4 -1
  125. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  126. package/packages/core/src/ports/forge/contract.ts +29 -0
  127. package/packages/core/src/ports/forge/github.ts +189 -61
  128. package/packages/core/src/ports/forge-failure.ts +1 -0
  129. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  130. package/packages/core/src/ports/runner/session-env.ts +1 -0
  131. package/packages/core/src/ports/types.ts +10 -0
  132. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  133. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  134. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  135. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  136. package/packages/core/src/processes/build-child-exit.ts +5 -26
  137. package/packages/core/src/processes/build-runner.ts +81 -11
  138. package/packages/core/src/processes/dispatcher.ts +254 -23
  139. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  140. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  141. package/packages/core/src/processes/execution-settlement.ts +16 -7
  142. package/packages/core/src/processes/harvest-runner.ts +328 -292
  143. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  144. package/packages/core/src/runtime-identity.ts +22 -3
  145. package/packages/core/src/store/contract.ts +153 -0
  146. package/packages/core/src/store/local/store.ts +197 -72
  147. package/packages/core/src/store/reduced-reads.ts +8 -0
  148. package/packages/core/src/store/reducer-value-shapes.json +5783 -3305
  149. package/packages/core/src/store/remote/client.ts +43 -0
  150. package/packages/core/src/store/repo-state-events.ts +20 -3
  151. package/packages/core/src/store/types.ts +7 -0
  152. package/skills/finalize/SKILL.md +3 -1
  153. package/skills/guide/SKILL.md +273 -48
  154. package/skills/guide/references/integration-tree.md +87 -2
  155. package/skills/guide/references/operator-api.md +71 -14
  156. package/skills/guide/references/plugin-authoring.md +231 -266
  157. package/skills/guide/references/remote-store-protocol.md +12 -9
  158. package/skills/guide/references/restacking.md +4 -1
  159. package/skills/guide/references/setup.md +28 -6
  160. package/skills/guide/references/spec-standard.md +23 -5
  161. package/skills/harvest/SKILL.md +4 -0
  162. package/skills/harvest-review/SKILL.md +4 -0
  163. package/skills/implement/SKILL.md +4 -2
  164. package/skills/operate/SKILL.md +104 -35
  165. package/skills/plan/SKILL.md +12 -4
  166. package/skills/spec/SKILL.md +20 -2
  167. package/skills/tickets/SKILL.md +20 -1
  168. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,7 @@
1
+ import { nodeActivityKey, nodePollingSchedule } from '../kernel/node-polling'
2
+ import { buildReadFactsReducer } from '../kernel/read-facts'
3
+ import { formatRuntimeIdentity } from '../events/runtime'
4
+ import { projectHandPushed, handPushedText, type HandPushedChange } from './dashboard/hand-pushed'
1
5
  import { compatibilityDiagnostic } from '../kernel/mixed-version'
2
6
  import { indexLog } from '../kernel/log-index'
3
7
  import { projectTree, type TreeProjection } from './dashboard/tree'
@@ -104,6 +108,7 @@ export interface BuildSummary {
104
108
  target?: string
105
109
  integration?: ReturnType<typeof buildVocabulary>['integration']
106
110
  integrationState?: BuildState['integration']
111
+ handPushedCommits?: HandPushedChange[]
107
112
  nodeRestack?: BuildState['nodeRestack']
108
113
  slug: string
109
114
  ticket?: TicketRef
@@ -150,6 +155,8 @@ export type BuildDecisionProjection =
150
155
  | { kind: 'unavailable'; diagnostic: string }
151
156
 
152
157
  export interface BuildDetail extends BuildSummary {
158
+ nodePolling?: { mode: 'active' | 'idle'; intervalSeconds: number; lastChecked?: string }
159
+ runnerAttaches: import('../kernel/read-facts').RunnerAttach[]
153
160
  tree?: TreeProjection
154
161
  /** Immutable policy provenance and durable command/native application state. */
155
162
  landing?: BuildState['landing']
@@ -246,7 +253,9 @@ export function summarizeFrom(record: BuildRecord, state: BuildState, now: Date)
246
253
  slug: record.slug,
247
254
  ...buildVocabulary(state),
248
255
  ...(state.kind === 'node' ? { integrationState: state.integration } : {}),
249
- ...(state.kind === 'node' ? { nodeRestack: state.nodeRestack } : {}),
256
+ ...(state.kind === 'node'
257
+ ? { nodeRestack: state.nodeRestack, handPushedCommits: projectHandPushed(state.nodeRestack) }
258
+ : {}),
250
259
  // record.ticket is a TicketRef already carrying id/title/url — no artifact
251
260
  // read and no ticket-provider call (live ticket state is out of scope).
252
261
  ...(record.ticket !== undefined ? { ticket: record.ticket } : {}),
@@ -303,6 +312,7 @@ export function detail(
303
312
  record,
304
313
  {
305
314
  state: reduceBuild(events),
315
+ runnerAttaches: buildReadFactsReducer.reduce(events).runnerAttaches,
306
316
  log: indexLog(events),
307
317
  observations: events
308
318
  .filter((event) => event.type === 'observation.recorded')
@@ -319,7 +329,9 @@ export function detail(
319
329
  export function detailFromFacts(
320
330
  record: BuildRecord,
321
331
  facts: Pick<BuildFacts, 'state' | 'open'> &
322
- Partial<Pick<BuildFacts, 'log'>> & { observations: BuildState['observations'] },
332
+ Partial<Pick<BuildFacts, 'log' | 'runnerAttaches'>> & {
333
+ observations: BuildState['observations']
334
+ },
323
335
  now: Date,
324
336
  events?: AbEvent[],
325
337
  decision?: BuildDecisionProjection,
@@ -354,6 +366,7 @@ export function detailFromFacts(
354
366
  }))
355
367
  return {
356
368
  ...summary,
369
+ runnerAttaches: facts.runnerAttaches ?? [],
357
370
  ...(facts.log ? { tree: projectTree(record, state, facts.log.restack) } : {}),
358
371
  autoMerge: autoMergeDisplay(state),
359
372
  ...(state.landing && Object.keys(state.landing).length ? { landing: state.landing } : {}),
@@ -550,6 +563,14 @@ export function renderSummaries(summaries: BuildSummary[], now: Date, emptyNote:
550
563
  /** Labeled sections, each omitted when absent ("when each is available"). */
551
564
  export function renderDetail(d: BuildDetail, now: Date): string[] {
552
565
  const lines: string[] = [`build ${d.slug}`]
566
+ if (d.nodePolling)
567
+ lines.push(
568
+ ` node polling: ${d.nodePolling.mode === 'idle' ? `idle; polled every ${d.nodePolling.intervalSeconds} seconds` : 'active; polled every tick'}; last checked: ${d.nodePolling.lastChecked ?? 'unrecorded'}`,
569
+ )
570
+ for (const attach of d.runnerAttaches)
571
+ lines.push(
572
+ ` runner attach #${attach.seq}: ${attach.instance}; host ${attach.host}; ${attach.ts}; ${formatRuntimeIdentity(attach.runtime)}`,
573
+ )
553
574
  if (d.compatibility)
554
575
  lines.push(
555
576
  ` newer facts: ${d.compatibility.unknownFacts} (${d.compatibility.decisiveFacts} decisive)`,
@@ -576,6 +597,8 @@ export function renderDetail(d: BuildDetail, now: Date): string[] {
576
597
  if (d.integration === 'verification failed')
577
598
  lines.push(' repair: file a child ticket targeting this node')
578
599
  }
600
+ if (d.kind === 'integration')
601
+ lines.push(` hand-pushed changes (node-owned): ${handPushedText(d.handPushedCommits)}`)
579
602
  if (d.nodeRestack) {
580
603
  const node = d.nodeRestack
581
604
  const move = node.parentRequest ?? node.parentChange
@@ -587,7 +610,6 @@ export function renderDetail(d: BuildDetail, now: Date): string[] {
587
610
  if (node.inventory) {
588
611
  lines.push(` node head: ${node.inventory.head}`)
589
612
  lines.push(` build changes: ${node.inventory.builds.join(', ') || 'none'}`)
590
- lines.push(` foreign changes (node-owned): ${node.inventory.foreign.join(', ') || 'none'}`)
591
613
  }
592
614
  if (!node.active && node.observedParent && node.observedParent.sha !== node.contributionBase)
593
615
  lines.push(` node restack pending: parent ${node.observedParent.sha}`)
@@ -1086,8 +1108,40 @@ export async function abBuildStatus(opts: AbBuildStatusOpts): Promise<void> {
1086
1108
  )
1087
1109
  const configMeta =
1088
1110
  configArtifact !== null ? parseBuildConfigMetadata(configArtifact) : undefined
1111
+ let nodePolling: BuildDetail['nodePolling']
1112
+ if (
1113
+ facts.state.kind === 'node' &&
1114
+ facts.state.status !== 'done' &&
1115
+ facts.state.status !== 'aborted' &&
1116
+ facts.state.prState !== 'closed' &&
1117
+ facts.state.prState !== 'merged'
1118
+ ) {
1119
+ const children: { slug: string; state: BuildState }[] = []
1120
+ for (const child of await context.store.listBuilds()) {
1121
+ if (child.repo !== record.repo) continue
1122
+ const state = (await readBuildFacts(context.store, child.slug)).value.state
1123
+ if (state.target?.build === record.slug) children.push({ slug: child.slug, state })
1124
+ }
1125
+ // The checkpoint records the dispatcher's hot policy. A held node's
1126
+ // launch artifact can predate later policy changes.
1127
+ const policy = {
1128
+ nodeIdleAfterSeconds: facts.state.nodePolling?.nodeIdleAfterSeconds ?? 600,
1129
+ nodeIdlePollSeconds: facts.state.nodePolling?.nodeIdlePollSeconds ?? 120,
1130
+ }
1131
+ nodePolling = nodePollingSchedule(
1132
+ facts.state,
1133
+ nodeActivityKey(facts.state, children),
1134
+ policy,
1135
+ now,
1136
+ facts.open !== null ||
1137
+ facts.publication.pending() ||
1138
+ facts.publication.abandonedPending() ||
1139
+ undefined,
1140
+ )
1141
+ }
1089
1142
  const d: BuildDetail = {
1090
1143
  ...projected,
1144
+ ...(nodePolling ? { nodePolling } : {}),
1091
1145
  ...(configMeta?.revision !== undefined ? { effectiveConfigRev: configMeta.revision } : {}),
1092
1146
  ...(configMeta?.pipelineSource !== undefined
1093
1147
  ? { pipelineSource: configMeta.pipelineSource }
@@ -0,0 +1,25 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+ import { loadConfig } from '../config/load'
4
+
5
+ /** Describes future adoption, never claims that a skill merge upgraded a process. */
6
+ export async function upgradeFollowup(checkout: string): Promise<string> {
7
+ const config = await loadConfig(join(checkout, 'autobuild.toml'))
8
+ if (!config.upgrade.automatic)
9
+ return 'Automatic dispatcher upgrades are off; restart dispatchers after updating their installation.'
10
+ let manifest: {
11
+ dependencies?: Record<string, unknown>
12
+ devDependencies?: Record<string, unknown>
13
+ } = {}
14
+ try {
15
+ manifest = JSON.parse(await readFile(join(checkout, 'package.json'), 'utf8'))
16
+ } catch (error) {
17
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
18
+ }
19
+ const pinned =
20
+ manifest.dependencies?.['@defrex/autobuild'] !== undefined ||
21
+ manifest.devDependencies?.['@defrex/autobuild'] !== undefined
22
+ return pinned
23
+ ? `Dispatchers check every 60 seconds and adopt the pinned version once this commit reaches ${config.baseBranch}. This command never pushes.`
24
+ : 'The dispatcher on this machine checks its original installation every 60 seconds and adopts a changed version automatically. Skill merges alone do not change that version. This command never pushes.'
25
+ }
@@ -1,3 +1,4 @@
1
+ import { integrationFailed } from '../kernel/integration-state'
1
2
  import { awaitsConsent } from '../kernel/landing-readiness'
2
3
  import { leafRestackReducer, type LeafRestackState } from '../kernel/leaf-restack-state'
3
4
  import { consentReady, consentIdentity } from './attention'
@@ -215,6 +216,7 @@ function stateSatisfies(
215
216
  return !!state.nodeRestack?.conflict || !!(restack.active && restack.replay?.conflicted)
216
217
  case 'attention':
217
218
  return (
219
+ (state.kind === 'node' && integrationFailed(state)) ||
218
220
  state.janitor?.attention === true ||
219
221
  awaitsConsent(state, restack) ||
220
222
  !!state.nodeRestack?.conflict ||
@@ -501,6 +503,7 @@ export async function abWait(opts: AbWaitOpts): Promise<number> {
501
503
  event.type === 'escalation.raised' ||
502
504
  event.type === 'phase.deferral-escalated' ||
503
505
  event.type === 'integration.landed' ||
506
+ event.type === 'integration.verification-failed' ||
504
507
  event.type === 'node.item-conflicted' ||
505
508
  (event.type === 'restack.replayed' && event.payload.conflicted)
506
509
  )
@@ -109,6 +109,7 @@ export const BUILD_ATTENTION_EVENTS = [
109
109
  'escalation.raised',
110
110
  'phase.deferral-escalated',
111
111
  'integration.landed',
112
+ 'integration.verification-failed',
112
113
  'node.item-conflicted',
113
114
  ] as const satisfies readonly EventType[]
114
115
 
@@ -409,6 +410,8 @@ const SUMMARY_MAX = 200
409
410
  */
410
411
  export function summarizeEvent(event: AbEvent | RepositoryEvent, state: BuildState | null): string {
411
412
  switch (event.type) {
413
+ case 'integration.verification-failed':
414
+ return `verification failed: ${event.payload.steps.join(', ')}; head ${event.payload.head}; parent ${event.payload.parent}; ${event.payload.guidance}`
412
415
  case 'build.janitor-failing':
413
416
  return `Janitor failing: ${singleLine(event.payload.message)}`
414
417
  case 'dispatcher.forge-degraded':
@@ -466,6 +469,10 @@ export function summarizeEvent(event: AbEvent | RepositoryEvent, state: BuildSta
466
469
  return `dispatcher tick failed: ${singleLine(event.payload.error)}`
467
470
  case 'dispatcher.forge-readiness-failed':
468
471
  return singleLine(formatReadinessFailure(event.payload))
472
+ case 'dispatcher.runtime-rolled-back':
473
+ return `dispatcher runtime rolled back ${event.payload.failed.version} → ${event.payload.restored.version}: ${singleLine(event.payload.reason)}`
474
+ case 'dispatcher.upgrade-failed':
475
+ return `dispatcher upgrade failed (${event.payload.target.mode} ${event.payload.target.version ?? event.payload.target.source}): ${singleLine(event.payload.reason)}`
469
476
  case 'dispatcher.config-rejected':
470
477
  return `dispatcher config rejected: ${singleLine(event.payload.error)}`
471
478
  case 'dispatcher.harvest-runner-failed':
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod'
2
+ import { documentFields } from './reference-metadata'
2
3
 
3
4
  /** Ordered dispatcher-owned policy; omitted predicates are wildcards. */
4
5
  export const landingRuleSchema = z.strictObject({
@@ -20,3 +21,10 @@ export const landingRuleSchema = z.strictObject({
20
21
  mode: z.enum(['auto', 'consent']),
21
22
  })
22
23
  export type LandingRule = z.infer<typeof landingRuleSchema>
24
+
25
+ documentFields(landingRuleSchema, {
26
+ into: 'Optional destination: `root`, any `node`, or an exact frozen destination node ticket id.',
27
+ from: 'Restrict this rule to one source build kind; omission matches all kinds.',
28
+ label: 'Optional exact, case-sensitive label on the source ticket. Blank labels are invalid.',
29
+ mode: 'Choose automatic landing or require recorded consent.',
30
+ })
@@ -13,6 +13,7 @@ export const DISPATCHER_CONFIG_ARTIFACT = 'dispatcher-config'
13
13
  */
14
14
  export const CONFIG_RELOAD_CLASSIFICATION = {
15
15
  store: 'restart',
16
+ upgrade: 'hot',
16
17
  baseBranch: 'hot',
17
18
  capacity: 'hot',
18
19
  ticketScanIntervalSeconds: 'hot',
@@ -0,0 +1,31 @@
1
+ import type { z } from 'zod'
2
+
3
+ /** Documentation describes input semantics; it never participates in validation. */
4
+ export interface ReferenceMetadata {
5
+ description?: string
6
+ constraints?: string
7
+ required?: string
8
+ examples?: string[]
9
+ structure?:
10
+ | { kind: 'map'; value: z.ZodType; keys: string }
11
+ | { kind: 'steps'; steps: z.ZodType; table: z.ZodType; afterReconcile?: z.ZodType }
12
+ }
13
+ const registry = new WeakMap<z.ZodType, ReferenceMetadata>()
14
+ export function referenceMetadata(schema: z.ZodType): ReferenceMetadata | undefined {
15
+ return registry.get(schema)
16
+ }
17
+ export function documentSchema<T extends z.ZodType>(schema: T, metadata: ReferenceMetadata): T {
18
+ registry.set(schema, { ...registry.get(schema), ...metadata })
19
+ return schema
20
+ }
21
+ /** A description map is deliberately not an inventory: traversal reads the schema. */
22
+ export function documentFields(schema: z.ZodObject, descriptions: Record<string, string>): void {
23
+ for (const [key, description] of Object.entries(descriptions)) {
24
+ const field = schema.shape[key]
25
+ if (!field)
26
+ throw new Error(
27
+ `Configuration reference metadata names an unknown field: ${key}. Remove its obsolete description, then regenerate with bun run docs:configuration.`,
28
+ )
29
+ documentSchema(field, { description })
30
+ }
31
+ }
@@ -0,0 +1,342 @@
1
+ import type { z } from 'zod'
2
+ import { referenceMetadata, type ReferenceMetadata } from './reference-metadata'
3
+ import { BUILTIN_WORKSPACE_PROVIDER_CONFIG, configRootSchema } from './schema'
4
+ import { BUILD_OWNED_CONFIG_PATHS, CONFIG_RELOAD_CLASSIFICATION } from './live'
5
+
6
+ /** Zod 4 input adapter. Unsupported nodes/checks fail closed at their TOML path. */
7
+ interface Definition {
8
+ type: string
9
+ innerType?: z.ZodType
10
+ in?: z.ZodType
11
+ element?: z.ZodType
12
+ shape?: Record<string, z.ZodType>
13
+ catchall?: z.ZodType
14
+ options?: z.ZodType[]
15
+ entries?: Record<string, string>
16
+ values?: unknown[]
17
+ defaultValue?: unknown
18
+ checks?: { _zod: { def: Check } }[]
19
+ }
20
+ interface Check {
21
+ check: string
22
+ format?: string
23
+ value?: number
24
+ minimum?: number
25
+ maximum?: number
26
+ length?: number
27
+ inclusive?: boolean
28
+ pattern?: RegExp
29
+ error?: () => string
30
+ }
31
+ function definition(schema: z.ZodType): Definition {
32
+ return schema._zod.def as unknown as Definition
33
+ }
34
+ function fail(path: string, message: string): never {
35
+ throw new Error(`Configuration reference ${path}: ${message}`)
36
+ }
37
+ function metadata(schema: z.ZodType, path: string): ReferenceMetadata {
38
+ const result = referenceMetadata(schema) ?? {}
39
+ for (const [key, value] of Object.entries(result)) {
40
+ if (!['description', 'constraints', 'required', 'examples', 'structure'].includes(key))
41
+ fail(path, `unknown metadata ${key}`)
42
+ if (
43
+ ['description', 'constraints', 'required'].includes(key) &&
44
+ (typeof value !== 'string' || !value.trim())
45
+ )
46
+ fail(path, `blank or malformed ${key}`)
47
+ }
48
+ if (
49
+ result.examples !== undefined &&
50
+ (!Array.isArray(result.examples) ||
51
+ result.examples.some((v) => typeof v !== 'string' || !v.trim()))
52
+ )
53
+ fail(path, 'malformed examples')
54
+ if (result.structure !== undefined) {
55
+ const structure = result.structure
56
+ if (!structure || typeof structure !== 'object') fail(path, 'malformed structure metadata')
57
+ const allowed =
58
+ structure.kind === 'map'
59
+ ? ['kind', 'value', 'keys']
60
+ : structure.kind === 'steps'
61
+ ? ['kind', 'steps', 'table', 'afterReconcile']
62
+ : []
63
+ if (!allowed.length) fail(path, 'unsupported structure descriptor')
64
+ for (const key of Object.keys(structure))
65
+ if (!allowed.includes(key)) fail(path, `unknown structure metadata ${key}`)
66
+ const isSchema = (value: unknown): value is z.ZodType =>
67
+ typeof value === 'object' && value !== null && '_zod' in value
68
+ if (structure.kind === 'map') {
69
+ if (!isSchema(structure.value) || !['any', 'nonempty', 'nonblank'].includes(structure.keys))
70
+ fail(path, 'malformed map descriptor')
71
+ } else if (
72
+ !isSchema(structure.steps) ||
73
+ !isSchema(structure.table) ||
74
+ (structure.afterReconcile !== undefined && !isSchema(structure.afterReconcile))
75
+ )
76
+ fail(path, 'malformed steps descriptor')
77
+ }
78
+ return result
79
+ }
80
+ interface Input {
81
+ schema: z.ZodType
82
+ metadata: ReferenceMetadata
83
+ optional: boolean
84
+ default: string
85
+ constraints: string[]
86
+ }
87
+ function checks(schema: z.ZodType, path: string, meta: ReferenceMetadata): string[] {
88
+ return (definition(schema).checks ?? []).map(({ _zod: { def } }) => {
89
+ switch (def.check) {
90
+ case 'number_format':
91
+ if (def.format !== 'safeint') fail(path, `unsupported number format ${def.format}`)
92
+ return 'safe integer'
93
+ case 'greater_than':
94
+ return `${def.inclusive ? '≥' : '>'} ${def.value}`
95
+ case 'less_than':
96
+ return `${def.inclusive ? '≤' : '<'} ${def.value}`
97
+ case 'min_length':
98
+ return `minimum length ${def.minimum}`
99
+ case 'max_length':
100
+ return `maximum length ${def.maximum}`
101
+ case 'length_equals':
102
+ return `length ${def.length}`
103
+ case 'multiple_of':
104
+ return `multiple of ${def.value}`
105
+ case 'string_format':
106
+ if (def.format !== 'regex' || !def.pattern)
107
+ fail(path, `unsupported string format ${def.format}`)
108
+ return `matches ${def.pattern}`
109
+ case 'custom': {
110
+ const message = def.error?.()
111
+ if (message) return message
112
+ if (meta.constraints) return meta.constraints
113
+ return fail(path, 'custom refinement needs constraint metadata')
114
+ }
115
+ default:
116
+ return fail(path, `unsupported check ${def.check}`)
117
+ }
118
+ })
119
+ }
120
+ /** Preserve outer defaults: optional(default(x)) still applies x in Zod 4. */
121
+ function input(schema: z.ZodType, path: string): Input {
122
+ let current = schema
123
+ let meta: ReferenceMetadata = {}
124
+ let optional = false
125
+ let fallback = 'omitted'
126
+ let hasDefault = false
127
+ const constraints: string[] = []
128
+ for (;;) {
129
+ const own = metadata(current, path)
130
+ meta = { ...own, ...meta }
131
+ constraints.push(...checks(current, path, meta))
132
+ const def = definition(current)
133
+ if (meta.structure) break
134
+ if (['optional', 'default', 'prefault'].includes(def.type)) {
135
+ optional = true
136
+ if (!hasDefault && def.type !== 'optional') {
137
+ fallback = JSON.stringify(def.defaultValue)
138
+ if (def.type === 'prefault')
139
+ fallback += ' (input supplied on omission; nested defaults apply)'
140
+ hasDefault = true
141
+ }
142
+ if (!def.innerType) fail(path, 'wrapper has no inner schema')
143
+ current = def.innerType
144
+ } else if (def.type === 'pipe') {
145
+ if (!def.in) fail(path, 'pipe has no input schema')
146
+ // A transformation must explain input-to-output semantics, not hide them.
147
+ if (!meta.constraints) fail(path, 'transform needs input constraint metadata')
148
+ if (definition(def.in).type === 'unknown')
149
+ fail(path, 'opaque transform needs a structural input descriptor')
150
+ current = def.in
151
+ } else break
152
+ }
153
+ // openMap and stepSection carry their descriptor on an outer prefault.
154
+ if (meta.structure && definition(current).type === 'prefault' && !hasDefault) {
155
+ optional = true
156
+ fallback = `${JSON.stringify(definition(current).defaultValue)} (input supplied on omission)`
157
+ }
158
+ return { schema: current, metadata: meta, optional, default: fallback, constraints }
159
+ }
160
+ function typeOf(value: Input, path: string): string {
161
+ if (value.metadata.structure) return 'table'
162
+ const def = definition(value.schema)
163
+ switch (def.type) {
164
+ case 'object':
165
+ if (!def.catchall || definition(def.catchall).type !== 'never')
166
+ fail(path, 'unsupported non-strict object; use an explicit open-map descriptor')
167
+ return 'strict table'
168
+ case 'unknown':
169
+ return 'plugin-owned TOML value'
170
+ case 'string':
171
+ case 'boolean':
172
+ case 'number':
173
+ return def.type
174
+ case 'literal':
175
+ return def.values!.map((v) => JSON.stringify(v)).join(' | ')
176
+ case 'enum':
177
+ return Object.values(def.entries!)
178
+ .map((v) => JSON.stringify(v))
179
+ .join(' | ')
180
+ case 'array':
181
+ return `array of ${typeOf(input(def.element!, `${path}[]`), `${path}[]`)}`
182
+ case 'union':
183
+ return def.options!.map((v) => typeOf(input(v, path), path)).join(' | ')
184
+ default:
185
+ return fail(path, `unsupported schema node ${def.type}`)
186
+ }
187
+ }
188
+ export interface ReferenceField {
189
+ path: string
190
+ type: string
191
+ default: string
192
+ required: string
193
+ reload: string
194
+ description: string
195
+ constraints: string[]
196
+ examples: string[]
197
+ variant?: string
198
+ }
199
+ /** Optional ticket fields overlay the candidate in composeReloadedConfig. */
200
+ export const DOCUMENTATION_RELOAD_FALLBACK = {
201
+ 'tickets.url': 'hot',
202
+ 'tickets.doneState': 'hot',
203
+ } as const
204
+ export function reloadBehavior(path: string): string {
205
+ const parts = path.replaceAll('[]', '').split('.')
206
+ let classification: unknown = CONFIG_RELOAD_CLASSIFICATION
207
+ for (const part of parts) {
208
+ if (typeof classification === 'string') break
209
+ classification = (classification as Record<string, unknown> | undefined)?.[part]
210
+ }
211
+ if (typeof classification === 'object' && classification !== null) {
212
+ const values = Object.values(classification)
213
+ classification = values.every((value) => value === values[0]) ? values[0] : 'mixed'
214
+ }
215
+ classification ??=
216
+ DOCUMENTATION_RELOAD_FALLBACK[path as keyof typeof DOCUMENTATION_RELOAD_FALLBACK]
217
+ if (!['hot', 'restart', 'mixed'].includes(String(classification)))
218
+ fail(path, 'missing reload classification')
219
+ const dispatcher =
220
+ classification === 'hot'
221
+ ? 'Hot: next dispatcher action captures the accepted value.'
222
+ : classification === 'restart'
223
+ ? 'Dispatcher restart required; startup adapters retain their configuration.'
224
+ : 'Mixed: see individual fields for dispatcher reload behavior.'
225
+ const owned = BUILD_OWNED_CONFIG_PATHS.some((prefix) => parts[0] === prefix)
226
+ return `${dispatcher}${owned ? ' Build-owned pipeline: captured from the build branch; later base-branch edits do not replace it. Workspace provisioning applies at the next build launch.' : ''} A running invocation keeps its captured values.`
227
+ }
228
+ export function schemaFields(
229
+ schema: z.ZodType,
230
+ path: string,
231
+ reload: (path: string) => string = reloadBehavior,
232
+ ): ReferenceField[] {
233
+ const fields: ReferenceField[] = []
234
+ function visit(schema: z.ZodType, path: string, variant?: string): void {
235
+ const value = input(schema, path)
236
+ const def = definition(value.schema)
237
+ const description = value.metadata.description ?? schema.description
238
+ if (!description?.trim()) fail(path, 'missing nonempty description')
239
+ const constraints = [...value.constraints]
240
+ if (value.metadata.constraints) constraints.push(value.metadata.constraints)
241
+ if (def.type === 'array') {
242
+ const element = input(def.element!, `${path}[]`)
243
+ constraints.push(...element.constraints.map((c) => `Each item: ${c}`))
244
+ if (element.metadata.constraints)
245
+ constraints.push(`Each item: ${element.metadata.constraints}`)
246
+ }
247
+ fields.push({
248
+ path,
249
+ type: typeOf(value, path),
250
+ default: value.default,
251
+ required:
252
+ value.metadata.required ??
253
+ (value.optional ? 'Optional' : 'Required') + (variant ? ` when ${variant}` : ''),
254
+ reload: reload(path),
255
+ description,
256
+ constraints: [...new Set(constraints)],
257
+ examples: value.metadata.examples ?? [],
258
+ ...(variant ? { variant } : {}),
259
+ })
260
+ const structure = value.metadata.structure
261
+ if (structure) {
262
+ if (structure.kind === 'map') {
263
+ if (!structure.value || !['any', 'nonempty', 'nonblank'].includes(structure.keys))
264
+ fail(path, 'malformed map descriptor')
265
+ fields[fields.length - 1]!.constraints.push(`Entry names: ${structure.keys}`)
266
+ visit(structure.value, `${path}.<name>`, variant)
267
+ } else if (structure.kind === 'steps') {
268
+ if (!structure.steps || !structure.table) fail(path, 'malformed steps descriptor')
269
+ visit(structure.steps, `${path}.steps`, variant)
270
+ if (structure.afterReconcile)
271
+ visit(structure.afterReconcile, `${path}.afterReconcile`, variant)
272
+ visit(structure.table, `${path}.<step>`, variant)
273
+ } else fail(path, 'unsupported structure descriptor')
274
+ } else if (def.type === 'object') {
275
+ for (const [key, child] of Object.entries(def.shape!)) visit(child, `${path}.${key}`, variant)
276
+ } else if (def.type === 'array') {
277
+ const element = input(def.element!, `${path}[]`)
278
+ if (definition(element.schema).type === 'object') {
279
+ for (const [key, child] of Object.entries(definition(element.schema).shape!))
280
+ visit(child, `${path}[].${key}`, variant)
281
+ } else if (element.metadata.structure) visit(def.element!, `${path}[]`, variant)
282
+ } else if (def.type === 'union') {
283
+ for (const option of def.options!) {
284
+ const branch = input(option, path)
285
+ const shape = definition(branch.schema).shape
286
+ if (!shape) fail(path, 'union branch must be a strict table')
287
+ const discriminator = shape.kind && definition(input(shape.kind, path).schema).values?.[0]
288
+ if (typeof discriminator !== 'string')
289
+ fail(path, 'union needs a literal kind discriminator')
290
+ for (const [key, child] of Object.entries(shape))
291
+ visit(child, `${path}.${key}`, `kind = ${JSON.stringify(discriminator)}`)
292
+ }
293
+ }
294
+ }
295
+ visit(schema, path)
296
+ return fields
297
+ }
298
+ export function configurationReference(): Record<string, ReferenceField[]> {
299
+ const regions: Record<string, ReferenceField[]> = { root: [] }
300
+ for (const [key, schema] of Object.entries(configRootSchema.shape)) {
301
+ const fields = schemaFields(schema, key)
302
+ const type = fields[0]!.type
303
+ if (!type.includes('table')) regions.root!.push(...fields)
304
+ else regions[key] = fields
305
+ }
306
+ regions['pr-imageHost'] = regions.pr!.filter((field) => field.path.startsWith('pr.imageHost.'))
307
+ regions.pr = regions.pr!.filter((field) => !field.path.startsWith('pr.imageHost.'))
308
+ for (const [provider, declaration] of BUILTIN_WORKSPACE_PROVIDER_CONFIG) {
309
+ if (declaration.configSchema)
310
+ regions[`workspace-${provider}`] = schemaFields(declaration.configSchema, 'workspace.config')
311
+ else if (declaration.configRefusalMessage)
312
+ regions
313
+ .workspace!.find((field) => field.path === 'workspace.config')!
314
+ .constraints.push(
315
+ `provider = ${JSON.stringify(provider)}: ${declaration.configRefusalMessage}`,
316
+ )
317
+ else fail('workspace.config', `builtin ${provider} has no declaration`)
318
+ }
319
+ return regions
320
+ }
321
+ export function renderFields(fields: readonly ReferenceField[]): string {
322
+ return fields
323
+ .map((field) =>
324
+ [
325
+ `#### \`${field.path}\`${field.variant ? ` (${field.variant})` : ''}`,
326
+ '',
327
+ `**TOML key:** \`${field.path}\``,
328
+ '',
329
+ `- **Type:** \`${field.type}\``,
330
+ `- **Default:** \`${field.default}\``,
331
+ `- **Required:** ${field.required}`,
332
+ `- **Reload:** ${field.reload}`,
333
+ '',
334
+ `**Description:** ${field.description}`,
335
+ '',
336
+ `**Constraints:** ${field.constraints.length ? field.constraints.join('; ') : 'None beyond the input type.'}`,
337
+ ...field.examples.flatMap((example) => ['', `**Example:** \`${example}\``]),
338
+ '',
339
+ ].join('\n'),
340
+ )
341
+ .join('\n')
342
+ }
@@ -361,7 +361,7 @@ function deprecationNotice(entry: RoleKeyConsumers): string {
361
361
  // declares its own step-named role, which wins — so it can never be a reason
362
362
  // to keep this key, and it never blocks the rename. Counting it as one made
363
363
  // the advice non-converging: "keep it, it is also the superseded key for
364
- // e2e", followed on the next dispatch by "it can be deleted".
364
+ // acceptance", followed on the next dispatch by "it can be deleted".
365
365
 
366
366
  // Inert: the key routes nothing at all.
367
367
  if (activeAlias.length === 0) {