@defrex/autobuild 1.0.0 → 1.1.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 (186) hide show
  1. package/README.md +6 -6
  2. package/SPEC.md +360 -229
  3. package/docs/answering-blocked-builds.md +2 -2
  4. package/docs/architecture.md +155 -45
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/builds.md +4 -4
  7. package/docs/cli.md +4 -4
  8. package/docs/configuration-overview.md +4 -4
  9. package/docs/configuration.md +245 -210
  10. package/docs/dispatcher-hosting.md +2 -2
  11. package/docs/dispatcher.md +1 -1
  12. package/docs/forges.md +5 -5
  13. package/docs/getting-started.md +2 -2
  14. package/docs/glossary.md +6 -6
  15. package/docs/hosted-dispatcher.md +6 -3
  16. package/docs/hosted-service.md +16 -5
  17. package/docs/integration-overview.md +15 -15
  18. package/docs/integration-tree.md +45 -38
  19. package/docs/integration.md +6 -6
  20. package/docs/mcp.md +16 -15
  21. package/docs/{landing-policy.md → merge-policy.md} +42 -24
  22. package/docs/migration-1.0.md +17 -13
  23. package/docs/operating.md +41 -18
  24. package/docs/operator-api.md +91 -15
  25. package/docs/operator-surfaces.md +8 -4
  26. package/docs/overview.md +3 -3
  27. package/docs/remote-store-protocol.md +76 -11
  28. package/docs/remote-ticket-protocol.md +1 -1
  29. package/docs/restacking.md +54 -15
  30. package/docs/setup.md +41 -6
  31. package/docs/skills.md +1 -1
  32. package/docs/spec-standard.md +6 -6
  33. package/docs/ticket-dependencies.md +7 -7
  34. package/docs/tickets.md +8 -2
  35. package/docs/troubleshooting.md +2 -2
  36. package/docs/upgrading.md +8 -3
  37. package/docs/verification.md +60 -14
  38. package/package.json +7 -5
  39. package/packages/core/src/cli/binary-direct.ts +13 -1
  40. package/packages/core/src/cli/binary-lifecycle.ts +65 -2
  41. package/packages/core/src/cli/build-control.ts +83 -28
  42. package/packages/core/src/cli/context.ts +81 -38
  43. package/packages/core/src/cli/dashboard/facts.ts +2 -1
  44. package/packages/core/src/cli/dashboard/integration-detail.ts +8 -8
  45. package/packages/core/src/cli/dashboard/integration-row.ts +40 -13
  46. package/packages/core/src/cli/dashboard/landing-display.ts +25 -0
  47. package/packages/core/src/cli/dashboard/model.ts +56 -33
  48. package/packages/core/src/cli/dashboard/poll.ts +9 -3
  49. package/packages/core/src/cli/dashboard/render.ts +59 -37
  50. package/packages/core/src/cli/dashboard/target-distance.ts +14 -0
  51. package/packages/core/src/cli/dashboard/tree.ts +3 -2
  52. package/packages/core/src/cli/dispatch-args.ts +1 -1
  53. package/packages/core/src/cli/dispatch-frontend.ts +6 -3
  54. package/packages/core/src/cli/dispatch.ts +35 -9
  55. package/packages/core/src/cli/env.ts +4 -0
  56. package/packages/core/src/cli/help.ts +30 -23
  57. package/packages/core/src/cli/main.ts +24 -8
  58. package/packages/core/src/cli/node-verification-provenance.ts +1 -97
  59. package/packages/core/src/cli/publication-settlement.ts +43 -20
  60. package/packages/core/src/cli/repository-status.ts +20 -9
  61. package/packages/core/src/cli/status.ts +42 -5
  62. package/packages/core/src/cli/store-opening.ts +6 -1
  63. package/packages/core/src/cli/terminal.ts +22 -1
  64. package/packages/core/src/cli/terminals.ts +14 -10
  65. package/packages/core/src/cli/upgrade-landing.ts +70 -30
  66. package/packages/core/src/cli/upgrade.ts +3 -1
  67. package/packages/core/src/cli/wait.ts +15 -7
  68. package/packages/core/src/cli/watch-lifetime.ts +111 -0
  69. package/packages/core/src/cli/watch.ts +634 -511
  70. package/packages/core/src/config/effective-artifact.fixture.ts +27 -0
  71. package/packages/core/src/config/effective-artifact.ts +13 -0
  72. package/packages/core/src/config/landing.ts +1 -1
  73. package/packages/core/src/config/load.ts +21 -1
  74. package/packages/core/src/config/pipeline-source.ts +28 -0
  75. package/packages/core/src/config/reference-metadata.ts +2 -0
  76. package/packages/core/src/config/reference.ts +22 -7
  77. package/packages/core/src/config/schema.ts +86 -162
  78. package/packages/core/src/context-directory.ts +26 -0
  79. package/packages/core/src/distribution-packaging.ts +26 -5
  80. package/packages/core/src/events/catalog.ts +10 -2
  81. package/packages/core/src/events/globs.ts +1 -1
  82. package/packages/core/src/events/payloads.ts +70 -1
  83. package/packages/core/src/events/policy.ts +7 -0
  84. package/packages/core/src/events/repository.ts +2 -4
  85. package/packages/core/src/events/sessions.ts +6 -6
  86. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +571 -0
  87. package/packages/core/src/kernel/auto-merge.ts +2 -2
  88. package/packages/core/src/kernel/engine.ts +255 -26
  89. package/packages/core/src/kernel/generators/leaf-restack-log.ts +10 -0
  90. package/packages/core/src/kernel/integration-landing.ts +3 -3
  91. package/packages/core/src/kernel/integration-state.ts +27 -4
  92. package/packages/core/src/kernel/leaf-restack-state.ts +28 -3
  93. package/packages/core/src/kernel/log-index.ts +13 -1
  94. package/packages/core/src/kernel/node-landing.ts +8 -8
  95. package/packages/core/src/kernel/node-parent.ts +2 -2
  96. package/packages/core/src/kernel/node-restack-transaction.ts +1 -1
  97. package/packages/core/src/kernel/node-verification-context.ts +216 -0
  98. package/packages/core/src/kernel/phases.ts +1 -1
  99. package/packages/core/src/kernel/plan-verify-selection.ts +16 -0
  100. package/packages/core/src/kernel/publication-retry.ts +168 -0
  101. package/packages/core/src/kernel/reconcile-restack.ts +29 -1
  102. package/packages/core/src/kernel/reducer.ts +82 -5
  103. package/packages/core/src/kernel/target-distance.ts +45 -0
  104. package/packages/core/src/kernel/terminal-guard.ts +10 -1
  105. package/packages/core/src/kernel/verify-stage-state.ts +123 -0
  106. package/packages/core/src/kernel/verify-stages.ts +39 -0
  107. package/packages/core/src/ontology.ts +1 -0
  108. package/packages/core/src/operator/annotations.ts +6 -0
  109. package/packages/core/src/operator/control.ts +1 -1
  110. package/packages/core/src/operator/index.ts +1 -7
  111. package/packages/core/src/operator/landings.ts +5 -1
  112. package/packages/core/src/operator/presentation.ts +6 -1
  113. package/packages/core/src/operator/query.ts +14 -18
  114. package/packages/core/src/operator/registry.ts +17 -6
  115. package/packages/core/src/operator/sandbox-host.ts +64 -40
  116. package/packages/core/src/operator/sandbox.ts +3 -0
  117. package/packages/core/src/operator/ticket-source-backend.ts +3 -12
  118. package/packages/core/src/ports/forge/contract.ts +2 -2
  119. package/packages/core/src/ports/forge/git-rewrite.ts +25 -2
  120. package/packages/core/src/ports/forge/github-readiness.ts +2 -2
  121. package/packages/core/src/ports/forge/github.ts +26 -7
  122. package/packages/core/src/ports/forge/local-git.ts +4 -4
  123. package/packages/core/src/ports/forge/readiness.ts +1 -1
  124. package/packages/core/src/ports/forge-failure.ts +24 -0
  125. package/packages/core/src/ports/workspace/build-execution.ts +3 -1
  126. package/packages/core/src/ports/workspace/phase-scratch.ts +4 -3
  127. package/packages/core/src/ports/workspace/vercel-sandbox.ts +59 -39
  128. package/packages/core/src/processes/build-child.ts +6 -8
  129. package/packages/core/src/processes/build-execution-state.ts +8 -5
  130. package/packages/core/src/processes/build-runner.ts +522 -98
  131. package/packages/core/src/processes/dispatcher.ts +186 -101
  132. package/packages/core/src/processes/execution-no-progress.ts +8 -1
  133. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  134. package/packages/core/src/processes/publication-loss.ts +8 -2
  135. package/packages/core/src/processes/publication-state.ts +42 -4
  136. package/packages/core/src/processes/repo-view.ts +14 -0
  137. package/packages/core/src/processes/verify-cycle-config.ts +96 -0
  138. package/packages/core/src/{integration → scenarios}/harness.ts +330 -317
  139. package/packages/core/src/store/adapter.ts +1 -0
  140. package/packages/core/src/store/build-scope.ts +9 -0
  141. package/packages/core/src/store/contract.ts +113 -1
  142. package/packages/core/src/store/local/schema.ts +13 -0
  143. package/packages/core/src/store/local/store.ts +42 -0
  144. package/packages/core/src/store/memory.ts +47 -0
  145. package/packages/core/src/store/operator-presence.ts +21 -0
  146. package/packages/core/src/store/phase-session.ts +10 -0
  147. package/packages/core/src/store/reducer-value-shapes.json +5081 -4160
  148. package/packages/core/src/store/remote/client.ts +47 -1
  149. package/packages/core/src/store/remote/compatibility.ts +2 -0
  150. package/packages/core/src/store/remote/protocol.ts +4 -0
  151. package/packages/core/src/store/remote/version.ts +3 -1
  152. package/packages/core/src/store/retention.ts +2 -3
  153. package/packages/core/src/store/session-handle.ts +9 -0
  154. package/packages/core/src/store/streams/session-writer.ts +1 -1
  155. package/packages/core/src/store/types.ts +12 -2
  156. package/packages/core/src/testing/index.ts +11 -1
  157. package/packages/core/src/testing/temp-directories.ts +58 -0
  158. package/skills/code-review/SKILL.md +23 -9
  159. package/skills/finalize/SKILL.md +15 -7
  160. package/skills/guide/SKILL.md +253 -118
  161. package/skills/guide/references/integration-tree.md +45 -38
  162. package/skills/guide/references/{landing-policy.md → merge-policy.md} +42 -24
  163. package/skills/guide/references/migration-1.0.md +17 -13
  164. package/skills/guide/references/operator-api.md +91 -15
  165. package/skills/guide/references/remote-store-protocol.md +76 -11
  166. package/skills/guide/references/remote-ticket-protocol.md +1 -1
  167. package/skills/guide/references/restacking.md +54 -15
  168. package/skills/guide/references/setup.md +41 -6
  169. package/skills/guide/references/spec-standard.md +6 -6
  170. package/skills/guide/references/ticket-dependencies.md +7 -7
  171. package/skills/implement/SKILL.md +43 -17
  172. package/skills/operate/SKILL.md +117 -116
  173. package/skills/plan/SKILL.md +39 -13
  174. package/skills/plan-review/SKILL.md +15 -10
  175. package/skills/reconcile/SKILL.md +22 -3
  176. package/skills/spec/SKILL.md +19 -19
  177. package/skills/tickets/SKILL.md +9 -7
  178. package/templates/autobuild.toml +1 -1
  179. package/templates/hosted-service/package.json +2 -2
  180. package/packages/core/src/orchestrator/approvals.ts +0 -115
  181. package/packages/core/src/orchestrator/conversation.ts +0 -167
  182. package/packages/core/src/orchestrator/model.ts +0 -86
  183. package/packages/core/src/orchestrator/prompt.ts +0 -63
  184. package/packages/core/src/orchestrator/tools.ts +0 -117
  185. package/packages/core/src/orchestrator/turn-runner.ts +0 -457
  186. package/packages/core/src/processes/orchestrator-tick.ts +0 -360
@@ -0,0 +1,27 @@
1
+ import { parseConfig } from './load'
2
+ import { effectiveBuildConfigContent } from '../processes/build-execution-state'
3
+
4
+ /** Pre-removal normalized snapshot, including defaults written while disabled. */
5
+ export function historicalEffectiveConfig(enabled = false): Record<string, unknown> {
6
+ const config = JSON.parse(
7
+ effectiveBuildConfigContent(
8
+ parseConfig(`
9
+ [tickets]
10
+ source = "file"
11
+ readyState = "ready"
12
+ [orchestrator]
13
+ enabled = ${enabled}
14
+ [orchestrator.sandbox]
15
+ idleMinutes = 7
16
+ environmentVariables = ["CUSTOM_TOOL"]
17
+ `),
18
+ ),
19
+ )
20
+ config.orchestrator = {
21
+ ...config.orchestrator,
22
+ invocationBudgetSeconds: 240,
23
+ approvals: ['sandbox.publish'],
24
+ ...(enabled ? { model: 'test/historical', wake: ['escalation.*'] } : {}),
25
+ }
26
+ return config
27
+ }
@@ -0,0 +1,13 @@
1
+ /** Read compatibility for immutable pre-removal effective-config artifacts only.
2
+ * New TOML must pass the current strict schema without this conversion. */
3
+ export function normalizeEffectiveConfigArtifact(value: unknown): unknown {
4
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return value
5
+ const config = value as Record<string, unknown>
6
+ const previous = config.orchestrator
7
+ if (previous === null || typeof previous !== 'object' || Array.isArray(previous)) return value
8
+ const orchestrator = { ...previous } as Record<string, unknown>
9
+ for (const key of ['model', 'invocationBudgetSeconds', 'approvals', 'wake']) {
10
+ delete orchestrator[key]
11
+ }
12
+ return { ...config, orchestrator }
13
+ }
@@ -26,5 +26,5 @@ documentFields(landingRuleSchema, {
26
26
  into: 'Optional destination: `root`, any `node`, or an exact frozen destination node ticket id.',
27
27
  from: 'Restrict this rule to one source build kind; omission matches all kinds.',
28
28
  label: 'Optional exact, case-sensitive label on the source ticket. Blank labels are invalid.',
29
- mode: 'Choose automatic landing or require recorded consent.',
29
+ mode: 'Choose automatic merge or require recorded consent.',
30
30
  })
@@ -70,7 +70,11 @@ function describeIssue(issue: z.core.$ZodIssue): string {
70
70
  return ` ${formatPath(path)}: ${message}`
71
71
  }
72
72
 
73
- export function parseConfig(tomlText: string, source = 'autobuild.toml'): Config {
73
+ export function parseConfig(
74
+ tomlText: string,
75
+ source = 'autobuild.toml',
76
+ warn: (message: string) => void = console.error,
77
+ ): Config {
74
78
  let table: unknown
75
79
  try {
76
80
  table = parseToml(tomlText)
@@ -81,6 +85,19 @@ export function parseConfig(tomlText: string, source = 'autobuild.toml'): Config
81
85
  throw error
82
86
  }
83
87
 
88
+ if (table && typeof table === 'object' && 'orchestrator' in table) {
89
+ const orchestrator = table.orchestrator
90
+ if (orchestrator && typeof orchestrator === 'object') {
91
+ const removed = ['model', 'invocationBudgetSeconds', 'approvals', 'wake'].filter((key) =>
92
+ Object.hasOwn(orchestrator, key),
93
+ )
94
+ if (removed.length > 0) {
95
+ throw new ConfigError(
96
+ `${source}: [orchestrator].${removed.join(', [orchestrator].')} removed: the embedded runner was removed; operators run externally. Keep only enabled and sandbox settings.`,
97
+ )
98
+ }
99
+ }
100
+ }
84
101
  const result = configSchema.safeParse(table)
85
102
  if (!result.success) {
86
103
  // Expanded for the operator, raw for the payload: the expanded copies carry
@@ -89,6 +106,9 @@ export function parseConfig(tomlText: string, source = 'autobuild.toml'): Config
89
106
  const details = expandIssues(result.error.issues).map(describeIssue).join('\n')
90
107
  throw new ConfigError(`${source}: invalid config\n${details}`, result.error.issues)
91
108
  }
109
+ if (table && typeof table === 'object' && Object.hasOwn(table, 'landing')) {
110
+ warn(`${source}: [[landing]] is deprecated; use [[merge]] instead`)
111
+ }
92
112
  return result.data
93
113
  }
94
114
 
@@ -387,3 +387,31 @@ export async function resolvePipelineSource(
387
387
  }
388
388
  return parsePipeline(baseSha, 'base', baseContent, onFailure)
389
389
  }
390
+
391
+ /** Strict execution-side read. Failures block verification rather than falling back. */
392
+ export async function readVerifyPipeline(
393
+ workspacePath: string,
394
+ exec: Exec,
395
+ ): Promise<PipelineSource & { head: string }> {
396
+ const run = async (args: string[]) => {
397
+ const result = await git(args, workspacePath, exec)
398
+ if (result.exitCode !== 0)
399
+ throw new Error(`verify config: git ${args.join(' ')}: ${result.stderr}`)
400
+ return result.stdout.trim()
401
+ }
402
+ const head = await run(['rev-parse', '--verify', 'HEAD'])
403
+ if (!/^[a-f0-9]{40,64}$/.test(head)) throw new Error('verify config: invalid checkout HEAD')
404
+ const content = await readFile(join(workspacePath, 'autobuild.toml'), 'utf8')
405
+ const [committed, working] = await Promise.all([
406
+ run(['ls-tree', head, '--', 'autobuild.toml']),
407
+ run(['hash-object', '--', 'autobuild.toml']),
408
+ ])
409
+ return {
410
+ head,
411
+ meta:
412
+ committed.split(/\s+/)[2] === working
413
+ ? { ref: 'branch-head', commit: head }
414
+ : { ref: 'worktree-dirty' },
415
+ config: parseConfig(content, `autobuild.toml@${head}`),
416
+ }
417
+ }
@@ -2,6 +2,8 @@ import type { z } from 'zod'
2
2
 
3
3
  /** Documentation describes input semantics; it never participates in validation. */
4
4
  export interface ReferenceMetadata {
5
+ /** Semantic default when omission is intentionally preserved in serialized config. */
6
+ default?: string
5
7
  description?: string
6
8
  constraints?: string
7
9
  required?: string
@@ -37,10 +37,12 @@ function fail(path: string, message: string): never {
37
37
  function metadata(schema: z.ZodType, path: string): ReferenceMetadata {
38
38
  const result = referenceMetadata(schema) ?? {}
39
39
  for (const [key, value] of Object.entries(result)) {
40
- if (!['description', 'constraints', 'required', 'examples', 'structure'].includes(key))
40
+ if (
41
+ !['description', 'constraints', 'required', 'examples', 'structure', 'default'].includes(key)
42
+ )
41
43
  fail(path, `unknown metadata ${key}`)
42
44
  if (
43
- ['description', 'constraints', 'required'].includes(key) &&
45
+ ['description', 'constraints', 'required', 'default'].includes(key) &&
44
46
  (typeof value !== 'string' || !value.trim())
45
47
  )
46
48
  fail(path, `blank or malformed ${key}`)
@@ -155,7 +157,13 @@ function input(schema: z.ZodType, path: string): Input {
155
157
  optional = true
156
158
  fallback = `${JSON.stringify(definition(current).defaultValue)} (input supplied on omission)`
157
159
  }
158
- return { schema: current, metadata: meta, optional, default: fallback, constraints }
160
+ return {
161
+ schema: current,
162
+ metadata: meta,
163
+ optional,
164
+ default: meta.default ?? fallback,
165
+ constraints,
166
+ }
159
167
  }
160
168
  function typeOf(value: Input, path: string): string {
161
169
  if (value.metadata.structure) return 'table'
@@ -177,8 +185,11 @@ function typeOf(value: Input, path: string): string {
177
185
  return Object.values(def.entries!)
178
186
  .map((v) => JSON.stringify(v))
179
187
  .join(' | ')
180
- case 'array':
181
- return `array of ${typeOf(input(def.element!, `${path}[]`), `${path}[]`)}`
188
+ case 'array': {
189
+ const elementInput = input(def.element!, `${path}[]`)
190
+ const element = typeOf(elementInput, `${path}[]`)
191
+ return `array of ${definition(elementInput.schema).type === 'union' ? `(${element})` : element}`
192
+ }
182
193
  case 'union':
183
194
  return def.options!.map((v) => typeOf(input(v, path), path)).join(' | ')
184
195
  default:
@@ -202,7 +213,10 @@ export const DOCUMENTATION_RELOAD_FALLBACK = {
202
213
  'tickets.doneState': 'hot',
203
214
  } as const
204
215
  export function reloadBehavior(path: string): string {
205
- const parts = path.replaceAll('[]', '').split('.')
216
+ const parts = path
217
+ .replace(/^merge(?=\[|\.|$)/, 'landing')
218
+ .replaceAll('[]', '')
219
+ .split('.')
206
220
  let classification: unknown = CONFIG_RELOAD_CLASSIFICATION
207
221
  for (const part of parts) {
208
222
  if (typeof classification === 'string') break
@@ -223,7 +237,7 @@ export function reloadBehavior(path: string): string {
223
237
  ? 'Dispatcher restart required; startup adapters retain their configuration.'
224
238
  : 'Mixed: see individual fields for dispatcher reload behavior.'
225
239
  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.`
240
+ return `${dispatcher}${owned ? ' Build-owned pipeline: captured from the execution checkout each verify cycle; later base-branch edits do not replace it. Workspace provisioning applies at the next build launch.' : ''} A running invocation keeps its captured values.`
227
241
  }
228
242
  export function schemaFields(
229
243
  schema: z.ZodType,
@@ -298,6 +312,7 @@ export function schemaFields(
298
312
  export function configurationReference(): Record<string, ReferenceField[]> {
299
313
  const regions: Record<string, ReferenceField[]> = { root: [] }
300
314
  for (const [key, schema] of Object.entries(configRootSchema.shape)) {
315
+ if (key === 'landing') continue // Deprecated spelling is documented with the canonical merge rules.
301
316
  const fields = schemaFields(schema, key)
302
317
  const type = fields[0]!.type
303
318
  if (!type.includes('table')) regions.root!.push(...fields)
@@ -1,3 +1,4 @@
1
+ import { isSafeStepName } from '../context-directory'
1
2
  /**
2
3
  * autobuild.toml schema (SPEC §16.1, D9): the one declarative per-repo config
3
4
  * file. Declarative, not executable — the kernel, dispatcher, CLI, and any
@@ -25,8 +26,6 @@ import {
25
26
  } from '../ports/workspace/provider-capabilities'
26
27
  import { defineEntry, openMap, ownEntries, parseEntry } from '../open-map'
27
28
  import { forwardIssues } from '../zod-issues'
28
- import { compileEventGlobs } from '../events/globs'
29
- import { REPOSITORY_ATTENTION_EVENTS } from '../events/repository'
30
29
  import { effectiveRuntimeReferences } from './roles'
31
30
 
32
31
  // ── Open maps ────────────────────────────────────────────────────────────────
@@ -60,11 +59,11 @@ import { effectiveRuntimeReferences } from './roles'
60
59
  * rather than silent, but a diagnostic that contradicts the source is its own
61
60
  * defect: §16.1 errors are feedback to whoever edits the file.
62
61
  */
63
- function stepSection<T, C>(
62
+ function stepSection<T, C, S = string[]>(
64
63
  label: string,
65
- stepsSchema: z.ZodType<string[]>,
64
+ stepsSchema: z.ZodType<S>,
66
65
  tableSchema: z.ZodType<T>,
67
- compose: (steps: string[], stepConfigs: Record<string, T>, afterReconcile: boolean) => C,
66
+ compose: (steps: S, stepConfigs: Record<string, T>, afterReconcile: boolean) => C,
68
67
  allowAfterReconcile = false,
69
68
  ) {
70
69
  const afterReconcileSchema = z.boolean().default(true)
@@ -72,7 +71,7 @@ function stepSection<T, C>(
72
71
  .unknown()
73
72
  .transform((input, ctx): C => {
74
73
  const stepConfigs: Record<string, T> = Object.create(null)
75
- let steps: string[] = []
74
+ let steps = stepsSchema.parse(undefined)
76
75
  let afterReconcile = afterReconcileSchema.parse(undefined)
77
76
  for (const [key, raw] of ownEntries(input, label, ctx)) {
78
77
  if (key === 'afterReconcile' && allowAfterReconcile) {
@@ -94,8 +93,17 @@ function stepSection<T, C>(
94
93
  })
95
94
  .prefault({})
96
95
  documentSchema(stepsSchema, {
96
+ ...(allowAfterReconcile
97
+ ? {
98
+ constraints:
99
+ 'Each name is nonempty; each grouped stage contains at least one nonempty name. Names must be unique within and across stages.',
100
+ }
101
+ : {}),
97
102
  description:
98
- 'Ordered names of the configured step tables. Every listed step must have a table and every table must be listed.',
103
+ (allowAfterReconcile
104
+ ? 'Ordered verify stages: a name is a singleton stage; a nonempty array runs its members concurrently. Names must be unique within and across stages. '
105
+ : 'Ordered names of the configured step tables. ') +
106
+ 'Names contain only ASCII letters, digits, ., _ and -, excluding "." and "..". Every listed step must have a table and every table must be listed.',
99
107
  })
100
108
  documentSchema(tableSchema, {
101
109
  description:
@@ -478,6 +486,8 @@ documentSchema(verifyPathGlobSchema, {
478
486
  })
479
487
 
480
488
  const verifyApplicabilityShape = {
489
+ /** Absence preserves historical serialized configuration identity. */
490
+ failFast: documentSchema(z.boolean().optional(), { default: 'false (omission is preserved)' }),
481
491
  afterReconcile: z.boolean().optional(),
482
492
  /** Any-match positive path selectors; absent means unconditional. */
483
493
  paths: z
@@ -503,6 +513,7 @@ documentFields(verifyCheckStepSchema, {
503
513
  'Name of an existing command in [commands]; required for check steps and forbidden for agent steps.',
504
514
  afterReconcile:
505
515
  'Step override wins over `[verify].afterReconcile`; false skips this step after reconciliation only.',
516
+ failFast: 'Cancel unfinished members of this stage when this step fails. Defaults to false.',
506
517
  paths: 'Apply only when at least one changed path matches. Available to both variants.',
507
518
  always:
508
519
  '`true` makes the step mandatory in plan selection and bypasses path gating. Available to both variants.',
@@ -520,6 +531,7 @@ documentFields(verifyAgentStepSchema, {
520
531
  skill: 'Exact installed skill name; required for agent steps and forbidden for check steps.',
521
532
  afterReconcile:
522
533
  'Step override wins over `[verify].afterReconcile`; false skips this step after reconciliation only.',
534
+ failFast: 'Cancel unfinished members of this stage when this step fails. Defaults to false.',
523
535
  paths: 'Apply only when at least one changed path matches. Available to both variants.',
524
536
  always:
525
537
  '`true` makes the step mandatory in plan selection and bypasses path gating. Available to both variants.',
@@ -535,6 +547,8 @@ export interface VerifyConfig {
535
547
  afterReconcile: boolean
536
548
  /** Step order — each entry names a `verify:<step>` phase (§15.2.1). */
537
549
  steps: string[]
550
+ /** Present only when the source contains grouped entries. */
551
+ stages?: string[][]
538
552
  /** The [verify.<step>] tables, keyed by step name. */
539
553
  stepConfigs: Record<string, VerifyStepConfig>
540
554
  }
@@ -547,12 +561,31 @@ export interface VerifyConfig {
547
561
  */
548
562
  export const verifySectionSchema = stepSection(
549
563
  '[verify]',
550
- z.array(z.string().min(1)).default([]),
564
+ z
565
+ .array(
566
+ z.union([
567
+ z.string().min(1),
568
+ z.array(z.string().min(1)).min(1, 'verify stage must not be empty'),
569
+ ]),
570
+ )
571
+ .default([]),
551
572
  verifyStepConfigSchema,
552
- (steps, stepConfigs, afterReconcile): VerifyConfig => ({ steps, stepConfigs, afterReconcile }),
573
+ (entries, stepConfigs, afterReconcile): VerifyConfig => ({
574
+ steps: entries.flat(),
575
+ stepConfigs,
576
+ afterReconcile,
577
+ ...(entries.some(Array.isArray)
578
+ ? { stages: entries.map((entry) => (typeof entry === 'string' ? [entry] : entry)) }
579
+ : {}),
580
+ }),
553
581
  true,
554
582
  )
555
583
 
584
+ /** Historical configurations have singleton stages without additional metadata. */
585
+ export function verifyStages(config: VerifyConfig): readonly (readonly string[])[] {
586
+ return config.stages ?? config.steps.map((step) => [step])
587
+ }
588
+
556
589
  // ── [finalize.<step>] ────────────────────────────────────────────────────────
557
590
 
558
591
  /** Finalize steps deliberately omit verify-only applicability fields. */
@@ -969,131 +1002,15 @@ documentSchema(orchestratorSandboxSchema.shape.environmentVariables, {
969
1002
  })
970
1003
  export type OrchestratorSandboxConfig = z.infer<typeof orchestratorSandboxSchema>
971
1004
 
972
- /** The turn runner lives inside the hosted operator route and the dispatcher
973
- * tick, both of which run under a Vercel function duration limit the config's
974
- * invocation budget can never exceed: a value above this is clamped (not
975
- * rejected) at parse time so a mis-set budget degrades to the limit instead of
976
- * failing every deploy. The operator route pins `maxDuration` to this same
977
- * constant, so one number is cited by the config, the route, and the docs. */
978
- export const ORCHESTRATOR_ROUTE_LIMIT_SECONDS = 300
979
-
980
- /** Turn budget floor for the dispatcher tick's orchestrator step: when less
981
- * than this many seconds of tick budget remain, the step skips the pass
982
- * entirely (suspension state is durable, so skipping is always safe). */
983
- export const ORCHESTRATOR_MIN_TURN_SECONDS = 30
984
-
985
- /** The turn approval entries' shape: a registry tool name, optionally
986
- * qualified by the discriminator field's accepted value (`tool:qualifier`).
987
- * Validation is syntactic only — an entry naming an absent or unknown tool is
988
- * inert by design (documented in docs/configuration.md), because the list
989
- * is meant to stay stable while the registry grows — e.g. `sandbox.publish`
990
- * was named here before its ticket landed, and stays inert in bindings
991
- * where no sandbox backend is bound (the hosted default). */
992
- const ORCHESTRATOR_APPROVAL_ENTRY = /^[a-z][a-z0-9_.]*(:[a-z0-9_-]+)?$/
993
-
994
- /** The attention set a new session's wake settings inherit when the
995
- * repository does not override `wake`: the build events an operator or agent
996
- * must wake up for, spelled as literal globs. These legacy hosted defaults
997
- * remain independent of CLI watch defaults; failed node verification belongs
998
- * to both. Repository-journal attention can also wake a session. */
999
- export const defaultOrchestratorWakeGlobs: readonly string[] = [
1000
- 'escalation.raised',
1001
- 'integration.verification-failed',
1002
- 'phase.deferral-escalated',
1003
- 'phase.failed',
1004
- 'infrastructure.failed',
1005
- 'runner.setup-failed',
1006
- 'dispatch.failed',
1007
- 'publication.lost',
1008
- 'finalize.completed',
1009
- 'pr.conflicted',
1010
- 'pr.merged',
1011
- 'pr.closed',
1012
- 'build.completed',
1013
- 'build.aborted',
1014
- ...REPOSITORY_ATTENTION_EVENTS,
1015
- ]
1016
-
1017
- /** The registry tools a turn asks its operator about before executing.
1018
- * The maintainer sets this to `[]` for autonomous operation. */
1019
- export const defaultOrchestratorApprovals: readonly string[] = [
1020
- 'builds.control:abort',
1021
- 'builds.control:discard',
1022
- 'builds.answer:revise-spec',
1023
- 'sandbox.publish',
1024
- 'tickets.move:ready',
1025
- ]
1026
-
1027
- /** A session's effective wake globs: the configured `wake` when declared
1028
- * (an explicit `[]` means never wake), else the default attention set. Kept
1029
- * as a resolver rather than a schema default so `wake`'s absence (inherit)
1030
- * and emptiness (never wake) stay distinct. */
1031
- export function orchestratorWakeGlobs(config: OrchestratorConfig): string[] {
1032
- return [...(config.wake ?? defaultOrchestratorWakeGlobs)]
1033
- }
1034
-
1035
1005
  export const orchestratorSchema = z.strictObject({
1036
1006
  enabled: z.boolean().default(false),
1037
1007
  sandbox: orchestratorSandboxSchema.prefault({}),
1038
- /** Provider-qualified model string for the turn runner, in the same
1039
- * vocabulary as `[roles]` model strings (nonblank; a leading
1040
- * `vercel-ai-gateway/` prefix is stripped before the gateway provider).
1041
- * Resolved through the deployment's gateway credential. Required when
1042
- * `enabled = true` (cross-validated below); the runner never starts a turn
1043
- * on a repository whose config omits it. */
1044
- model: z.string().min(1).optional(),
1045
- /** Wall-clock budget for one turn invocation, in seconds. Clamped — not
1046
- * rejected — to ORCHESTRATOR_ROUTE_LIMIT_SECONDS, the hosted function
1047
- * duration the runner runs under. */
1048
- invocationBudgetSeconds: z
1049
- .number()
1050
- .int()
1051
- .positive()
1052
- .default(240)
1053
- .transform((value) => Math.min(value, ORCHESTRATOR_ROUTE_LIMIT_SECONDS)),
1054
- /** Registry tool names (optionally `tool:qualifier`) whose calls suspend a
1055
- * turn until the operator answers. Empty means none. Entries naming an
1056
- * absent or unknown tool are inert by design, which is what keeps the
1057
- * default list stable while the registry grows. */
1058
- approvals: z
1059
- .array(
1060
- z
1061
- .string()
1062
- .regex(
1063
- ORCHESTRATOR_APPROVAL_ENTRY,
1064
- 'approval entries look like "tool" or "tool:qualifier"',
1065
- ),
1066
- )
1067
- .default([...defaultOrchestratorApprovals]),
1068
- /** Wake-filter globs a NEW session inherits. Kept schema-optional (not
1069
- * `.default()`) so absent ("inherit the default attention set") and `[]`
1070
- * ("never wake") stay distinct. Each glob must match at least one build
1071
- * or repository-journal event type — validated below with the shared
1072
- * `ab watch` compiler. */
1073
- wake: z.array(z.string().min(1)).optional(),
1074
1008
  })
1075
1009
 
1076
1010
  documentFields(orchestratorSchema, {
1077
1011
  enabled:
1078
- 'Master gate. With the table absent or `enabled = false`, the sandbox tools are absent from every binding, no environment is ever provisioned, and no dispatcher tick or message post ever runs orchestrator code \u2014 a local dispatcher is inert even when enabled, because the turn runner exists only in the hosted deployment.',
1012
+ 'Enables externally driven sandbox tools, archive cleanup and dispatcher idle settlement. Operators run in external agent harnesses.',
1079
1013
  sandbox: 'Sandbox behavior knobs.',
1080
- model:
1081
- "Provider-qualified model string for the turn runner, in the same vocabulary as `[roles]` model strings (a leading `vercel-ai-gateway/` prefix is accepted and stripped). Resolved through the deployment's gateway credential.",
1082
- invocationBudgetSeconds:
1083
- 'Wall-clock budget in seconds for one turn invocation. Values above the route limit are clamped after parsing.',
1084
- approvals:
1085
- "Registry tool names whose calls suspend a turn until you answer. Empty (`[]`) means none \u2014 autonomous operation. An entry naming an absent or unknown tool is **inert by design**, never a config error: the list stays stable while the registry grows, and a tool's removal cannot break parsing. A `tool:qualifier` entry applies to the named discriminator value only (for example `tickets.move:ready` approves moving a ticket to `ready`); for a tool without a discriminator, only the bare form matches.",
1086
- wake: 'The attention events a **new** session wakes for. Kept schema-optional so absent (inherit the legacy hosted wake set including `integration.verification-failed`, independently of CLI watch defaults) and `[]` (never wake; message-only) stay distinct. Each glob must match at least one build or repository-journal event type, validated with the same compiler `ab watch` uses. Existing sessions never retroactively inherit; an explicit `PUT .../wake` always wins.',
1087
- })
1088
- documentSchema(orchestratorSchema.shape.model, {
1089
- required: 'Required when orchestrator.enabled = true.',
1090
- })
1091
- documentSchema(orchestratorSchema.shape.invocationBudgetSeconds, {
1092
- constraints: `Values above ${ORCHESTRATOR_ROUTE_LIMIT_SECONDS} are clamped to that limit after parsing.`,
1093
- })
1094
- documentSchema(orchestratorSchema.shape.wake, {
1095
- constraints:
1096
- 'Every glob must match a known build or repository-journal event. Omission inherits the legacy hosted wake set independently of CLI watch defaults; [] disables waking.',
1097
1014
  })
1098
1015
  export type OrchestratorConfig = z.infer<typeof orchestratorSchema>
1099
1016
 
@@ -1140,7 +1057,8 @@ export const configRootSchema = z.strictObject({
1140
1057
  .refine((value) => value.trim().length > 0, 'plugin module specifiers must be nonblank'),
1141
1058
  )
1142
1059
  .default([]),
1143
- landing: z.array(landingRuleSchema).default([]),
1060
+ merge: z.array(landingRuleSchema).optional(),
1061
+ landing: z.array(landingRuleSchema).optional(),
1144
1062
  pr: prSchema.optional(),
1145
1063
  workspace: workspaceSchema.prefault({}),
1146
1064
  commands: commandsSchema,
@@ -1176,12 +1094,15 @@ documentFields(configRootSchema, {
1176
1094
  'Forge adapter name. Shipped values are `github` and `local-git`; configured plugins may register other names.',
1177
1095
  plugins:
1178
1096
  'Trusted Bun plugin modules loaded by dispatch, `ab ticket`, and scoped phase CLI processes.',
1179
- landing: 'Ordered landing rules; the first matching rule controls consent.',
1097
+ merge: 'Ordered merge rules; the first matching rule controls consent.',
1098
+ landing: 'Deprecated alias for merge. Do not declare both keys.',
1180
1099
  pr: 'Pull request review image hosting configuration.',
1181
1100
  workspace: 'Workspace provider selector and provider-specific configuration.',
1182
1101
  commands: 'Named shell commands used by setup and deterministic checks.',
1183
- verify: 'Ordered verification steps and applicability rules.',
1184
- finalize: 'Ordered post-PR steps. Failures are recorded without blocking the PR.',
1102
+ verify:
1103
+ 'Ordered verification steps and applicability rules. Step names use ASCII letters, digits, ., _ and -; exactly . and .. are forbidden.',
1104
+ finalize:
1105
+ 'Ordered post-PR steps. Failures are recorded without blocking the PR. Step names use ASCII letters, digits, ., _ and -; exactly . and .. are forbidden.',
1185
1106
  roles: 'Named agent roles. The reserved default role provides inherited runtime axes.',
1186
1107
  policy: 'Lifecycle budgets, retries, convergence and harvest limits.',
1187
1108
  orchestrator:
@@ -1214,7 +1135,33 @@ export const TOP_LEVEL_KEYS = Object.keys(configRootSchema.shape)
1214
1135
  * because validation failures are feedback to whoever edits the file (D6
1215
1136
  * discipline applied to config).
1216
1137
  */
1217
- export const configSchema = configRootSchema.superRefine((config, ctx) => {
1138
+ const normalizedConfigSchema = configRootSchema.transform((input, ctx) => {
1139
+ if (input.merge !== undefined && input.landing !== undefined) {
1140
+ ctx.addIssue({
1141
+ code: 'custom',
1142
+ path: ['merge'],
1143
+ message: 'merge and deprecated landing cannot both be declared',
1144
+ })
1145
+ return z.NEVER
1146
+ }
1147
+ const { merge, landing, ...rest } = input
1148
+ return { ...rest, landing: merge ?? landing ?? [] }
1149
+ })
1150
+
1151
+ export const configSchema = normalizedConfigSchema.superRefine((config, ctx) => {
1152
+ for (const kind of ['verify', 'finalize'] as const) {
1153
+ const section = config[kind]
1154
+ if (!section) continue
1155
+ for (const name of new Set([...section.steps, ...Object.keys(section.stepConfigs)])) {
1156
+ if (!isSafeStepName(name))
1157
+ ctx.addIssue({
1158
+ code: 'custom',
1159
+ path: [kind, name],
1160
+ message: `${kind} step "${name}" must contain only ASCII letters, digits, ., _ or - and cannot be . or ..`,
1161
+ })
1162
+ }
1163
+ }
1164
+
1218
1165
  const firstPluginIndex = new Map<string, number>()
1219
1166
  config.plugins.forEach((specifier, index) => {
1220
1167
  const firstIndex = firstPluginIndex.get(specifier)
@@ -1274,7 +1221,15 @@ export const configSchema = configRootSchema.superRefine((config, ctx) => {
1274
1221
  // while sibling issues are collected. Guard the cross-check so malformed
1275
1222
  // tables report validation feedback instead of throwing inside validation.
1276
1223
  if (config.verify?.stepConfigs !== undefined) {
1224
+ const seen = new Set<string>()
1277
1225
  config.verify.steps.forEach((step, index) => {
1226
+ if (seen.has(step))
1227
+ ctx.addIssue({
1228
+ code: 'custom',
1229
+ path: ['verify', 'steps', index],
1230
+ message: `duplicate verify step ${JSON.stringify(step)} across or within stages`,
1231
+ })
1232
+ seen.add(step)
1278
1233
  if (!Object.hasOwn(config.verify.stepConfigs, step)) {
1279
1234
  ctx.addIssue({
1280
1235
  code: 'custom',
@@ -1391,38 +1346,7 @@ export const configSchema = configRootSchema.superRefine((config, ctx) => {
1391
1346
  // `createWorkspaceProvider` (construction) and `validateInitReadiness`
1392
1347
  // (init validation), both of which run after plugin load; no site loads
1393
1348
  // plugins earlier to widen parse-time coverage.
1394
- // Wake globs are validated with the same compiler `ab watch` uses, over the
1395
- // build AND repository-journal catalogs — the wake pass scans both — so a
1396
- // typo'd glob fails at parse time instead of silently matching nothing —
1397
- // regardless of `enabled`, since a later enablement would inherit the
1398
- // already-broken value.
1399
- if (config.orchestrator.wake !== undefined) {
1400
- try {
1401
- compileEventGlobs(config.orchestrator.wake, {
1402
- repository: true,
1403
- usage: '[orchestrator].wake',
1404
- })
1405
- } catch (error) {
1406
- ctx.addIssue({
1407
- code: 'custom',
1408
- path: ['orchestrator', 'wake'],
1409
- message: error instanceof Error ? error.message : String(error),
1410
- })
1411
- }
1412
- }
1413
-
1414
1349
  if (config.orchestrator.enabled) {
1415
- // The turn runner's model is not optional when the orchestrator is on:
1416
- // an enabled table without one would fail at first turn start, far from
1417
- // the edit that caused it.
1418
- if (config.orchestrator.model === undefined) {
1419
- ctx.addIssue({
1420
- code: 'custom',
1421
- path: ['orchestrator', 'model'],
1422
- message:
1423
- '[orchestrator].enabled = true requires [orchestrator].model — name the provider-qualified model string the turn runner uses (same vocabulary as [roles], resolved through the deployment gateway credential)',
1424
- })
1425
- }
1426
1350
  const providerForbidden =
1427
1351
  BUILTIN_WORKSPACE_PROVIDER_CONFIG.get(config.workspace.provider)?.sandboxForbiddenEnv ?? []
1428
1352
  config.orchestrator.sandbox.environmentVariables.forEach((name, index) => {
@@ -0,0 +1,26 @@
1
+ /** Session scratch names are direct children of .ab, shared across rounds. */
2
+ export function isSafeStepName(name: string): boolean {
3
+ return /^[A-Za-z0-9._-]+$/.test(name) && name !== '.' && name !== '..'
4
+ }
5
+
6
+ export function contextDirectory(phase: string, finalizeStep?: string): string {
7
+ const base = phase.split('@')[0]!
8
+ const step = finalizeStep ?? (base.startsWith('verify:') ? base.slice(7) : undefined)
9
+ if (step !== undefined && !isSafeStepName(step)) {
10
+ throw new Error(`Invalid context step name "${step}"`)
11
+ }
12
+ return `.ab/${finalizeStep !== undefined ? `finalize-${step}` : base.replace(':', '-')}`
13
+ }
14
+
15
+ export function resolveContextDirectory(phase: string, explicit?: string): string {
16
+ const expected = contextDirectory(phase)
17
+ if (explicit === undefined) return expected
18
+ if (explicit === expected) return explicit
19
+ if (
20
+ phase.split('@')[0] === 'finalize' &&
21
+ explicit.startsWith('.ab/finalize-') &&
22
+ isSafeStepName(explicit.slice('.ab/finalize-'.length))
23
+ )
24
+ return explicit
25
+ throw new Error(`AB_CONTEXT_DIR "${explicit}" must name the session directory ${expected}`)
26
+ }
@@ -66,10 +66,16 @@ export async function packageDistribution(
66
66
  root: string,
67
67
  exec: PackagingExec = spawnExec,
68
68
  signal?: AbortSignal,
69
+ filesystem: { mkdtemp(prefix: string): Promise<string>; rm: typeof rm } = { mkdtemp, rm },
69
70
  ): Promise<Uint8Array> {
70
- const staging = await mkdtemp(join(tmpdir(), 'autobuild-pack-staging-'))
71
- const destination = await mkdtemp(join(tmpdir(), 'autobuild-pack-'))
71
+ const staging = await filesystem.mkdtemp(join(tmpdir(), 'autobuild-pack-staging-'))
72
+ let destination: string | undefined
73
+ let failure: unknown
74
+ let failed = false
75
+ let bytes!: Uint8Array
76
+ let errors: unknown[] = []
72
77
  try {
78
+ destination = await filesystem.mkdtemp(join(tmpdir(), 'autobuild-pack-'))
73
79
  // Pack from a staging copy of the repo's `files` set rather than the repo
74
80
  // root: the packed manifest must differ from the repo manifest (above), and
75
81
  // rewriting the repo manifest in place would leave a window where tracked
@@ -108,9 +114,24 @@ export async function packageDistribution(
108
114
  const archives = (await readdir(destination)).filter((name) => name.endsWith('.tgz'))
109
115
  if (archives.length !== 1)
110
116
  throw new Error('Autobuild packaging did not produce exactly one archive')
111
- return new Uint8Array(await readFile(join(destination, archives[0]!)))
117
+ bytes = new Uint8Array(await readFile(join(destination, archives[0]!)))
118
+ } catch (error) {
119
+ failed = true
120
+ failure = error
112
121
  } finally {
113
- await rm(staging, { recursive: true, force: true })
114
- await rm(destination, { recursive: true, force: true })
122
+ const results = await Promise.allSettled(
123
+ [staging, destination]
124
+ .filter((path): path is string => path !== undefined)
125
+ .map((path) => filesystem.rm(path, { recursive: true, force: true })),
126
+ )
127
+ errors = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []))
115
128
  }
129
+ if (errors.length)
130
+ throw new AggregateError(
131
+ failed ? [failure, ...errors] : errors,
132
+ 'Distribution packaging cleanup failed',
133
+ failed ? { cause: failure } : undefined,
134
+ )
135
+ if (failed) throw failure
136
+ return bytes
116
137
  }