@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defrex/autobuild",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Agent-driven software delivery from groomed ticket to merged PR",
5
5
  "repository": {
6
6
  "type": "git",
@@ -127,10 +127,12 @@
127
127
  "release": "bun tools/release.ts",
128
128
  "postgres:migrate": "bun packages/postgres-store/src/bin.ts migrate",
129
129
  "docs:configuration": "bun tools/configuration-reference.ts --write",
130
- "check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/workspace-manifest-check.ts && bun tools/package-boundary-check.ts && bun tools/bin-mode-check.ts && bun tools/publish-contents-check.ts && bun tools/publish-imports-check.ts",
130
+ "check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/package-boundary-check.ts",
131
+ "check:build": "bun tools/workspace-manifest-check.ts && bun tools/bin-mode-check.ts && bun tools/publish-contents-check.ts && bun tools/publish-imports-check.ts",
131
132
  "format:staged": "git-format-staged --formatter './node_modules/.bin/biome format --stdin-file-path {}' '*.js' '*.jsx' '*.ts' '*.tsx' '*.json' '*.jsonc' '*.css' '*.graphql' '*.gql'",
132
133
  "prepare": "husky",
133
- "test": "bun test packages/*/src tools bin packages/hosted-store-service/app",
134
+ "test": "bun tools/test-temp-leaks.ts unit",
135
+ "test:integration": "bun tools/test-temp-leaks.ts integration",
134
136
  "typecheck": "tsc --noEmit"
135
137
  },
136
138
  "dependencies": {
@@ -145,8 +147,8 @@
145
147
  },
146
148
  "devDependencies": {
147
149
  "@biomejs/biome": "2.5.5",
148
- "@defrex/autobuild-postgres-store": "1.0.0",
149
- "@defrex/autobuild-vercel-sandbox": "1.0.0",
150
+ "@defrex/autobuild-postgres-store": "1.1.0",
151
+ "@defrex/autobuild-vercel-sandbox": "1.1.0",
150
152
  "@resvg/resvg-js": "2.6.2",
151
153
  "@types/bun": "^1.3.14",
152
154
  "@types/node": "^24.0.0",
@@ -26,6 +26,7 @@ import { systemClock } from '../store/types'
26
26
  import { resolveMainRepo } from './repo-state'
27
27
 
28
28
  import {
29
+ installWatchTermination,
29
30
  usesGenericSessionlessSigintHandler,
30
31
  installSessionlessSigintHandler,
31
32
  withDispatchTerminalRestore,
@@ -46,13 +47,21 @@ export async function runDirectBinary(
46
47
 
47
48
  delete process.env.AB_DISPATCH_GENERATION
48
49
 
50
+ let watchTermination: ReturnType<typeof installWatchTermination> | undefined
49
51
  const unscopedDeps = {
50
52
  workspacePath: process.cwd(),
51
53
  processEnv: process.env,
52
54
  exec: spawnExec,
53
55
  stdout: (line: string) => {
56
+ if (watchTermination) {
57
+ watchTermination.write(line)
58
+ return
59
+ }
54
60
  if (command !== 'dispatch' || ownsDispatchPresentation()) console.log(line)
55
61
  },
62
+ flushStdout: async () => {
63
+ await watchTermination?.flush()
64
+ },
56
65
  stderr: (line: string) => {
57
66
  if (command !== 'dispatch' || ownsDispatchPresentation()) console.error(line)
58
67
  },
@@ -67,12 +76,13 @@ export async function runDirectBinary(
67
76
  // cleanly at the next tick boundary (§15.6-C: in-flight leases expire and
68
77
  // a future dispatch re-attaches).
69
78
  const controller = new AbortController()
79
+ if (command === 'watch') watchTermination = installWatchTermination(controller)
70
80
  const onSigint = (): void => controller.abort('SIGINT')
71
81
  const ownsSigint = usesGenericSessionlessSigintHandler(command)
72
82
  const terminal = processTerminal(process.stdout)
73
83
  const removeSigint = installSessionlessSigintHandler(command, onSigint)
74
84
  try {
75
- return await withDispatchTerminalRestore(
85
+ const code = await withDispatchTerminalRestore(
76
86
  command,
77
87
  terminal,
78
88
  () =>
@@ -92,7 +102,9 @@ export async function runDirectBinary(
92
102
  process as unknown as TerminalRestoreProcess,
93
103
  (signal) => controller.abort(signal),
94
104
  )
105
+ return watchTermination ? await watchTermination.complete(code) : code
95
106
  } finally {
107
+ watchTermination?.close()
96
108
  removeSigint()
97
109
  }
98
110
  }
@@ -13,7 +13,7 @@ export interface SessionlessSigintBoundary {
13
13
  removeListener(event: 'SIGINT', listener: () => void): unknown
14
14
  }
15
15
 
16
- /** Dispatch keeps its listener through the complete child drain; ordinary
16
+ /** Dispatch and watch keep their listeners through shutdown cleanup; ordinary
17
17
  * sessionless commands preserve the historical one-shot cancellation. */
18
18
  export function installSessionlessSigintHandler(
19
19
  command: string | undefined,
@@ -21,7 +21,7 @@ export function installSessionlessSigintHandler(
21
21
  boundary: SessionlessSigintBoundary = process,
22
22
  ): () => void {
23
23
  if (!usesGenericSessionlessSigintHandler(command)) return () => {}
24
- if (command === 'dispatch') boundary.on('SIGINT', onSigint)
24
+ if (command === 'dispatch' || command === 'watch') boundary.on('SIGINT', onSigint)
25
25
  else boundary.once('SIGINT', onSigint)
26
26
  return () => boundary.removeListener('SIGINT', onSigint)
27
27
  }
@@ -44,3 +44,66 @@ export async function withDispatchTerminalRestore<T>(
44
44
  hook?.close()
45
45
  }
46
46
  }
47
+
48
+ /** Watch alone catches termination long enough to withdraw advisory presence.
49
+ * SIGTERM/HUP are re-raised after cleanup to retain the shell's signal outcome. */
50
+ export function installWatchTermination(controller: AbortController): {
51
+ close: () => void
52
+ write: (line: string) => void
53
+ flush: () => Promise<void>
54
+ complete: (code: number) => Promise<number>
55
+ } {
56
+ const pending = new Set<Promise<void>>()
57
+ let broken = false
58
+ let signal: 'SIGTERM' | 'SIGHUP' | undefined
59
+ const stop = (value: 'SIGTERM' | 'SIGHUP'): void => {
60
+ signal ??= value
61
+ controller.abort(value)
62
+ }
63
+ const term = (): void => stop('SIGTERM')
64
+ const hup = (): void => stop('SIGHUP')
65
+ const pipe = (error: NodeJS.ErrnoException): void => {
66
+ if (error.code !== 'EPIPE') throw error
67
+ broken = true
68
+ controller.abort('EPIPE')
69
+ }
70
+ process.on('SIGTERM', term)
71
+ process.on('SIGHUP', hup)
72
+ process.stdout.on('error', pipe)
73
+ const close = (): void => {
74
+ process.removeListener('SIGTERM', term)
75
+ process.removeListener('SIGHUP', hup)
76
+ process.stdout.removeListener('error', pipe)
77
+ }
78
+ return {
79
+ close,
80
+ write(line) {
81
+ if (broken || signal !== undefined) return
82
+ const written = new Promise<void>((resolve) => {
83
+ try {
84
+ process.stdout.write(`${line}\n`, (error) => {
85
+ if (error) pipe(error)
86
+ resolve()
87
+ })
88
+ } catch (error) {
89
+ pipe(error as NodeJS.ErrnoException)
90
+ resolve()
91
+ }
92
+ })
93
+ pending.add(written)
94
+ void written.then(() => pending.delete(written))
95
+ },
96
+ async flush() {
97
+ await Promise.all(pending)
98
+ },
99
+ async complete(code) {
100
+ close()
101
+ if (signal) {
102
+ process.kill(process.pid, signal)
103
+ // Wait for default signal delivery before the entry point can exit.
104
+ await new Promise<never>(() => {})
105
+ }
106
+ return broken ? 1 : code
107
+ },
108
+ }
109
+ }
@@ -165,7 +165,7 @@ async function appendCommand(
165
165
  switch (command) {
166
166
  case 'hold':
167
167
  case 'land':
168
- throw new Error('Landing commands require compare-and-append authorization')
168
+ throw new Error('Merge commands require compare-and-append authorization')
169
169
  case 'pause':
170
170
  event = await store.append(slug, {
171
171
  actor,
@@ -212,6 +212,18 @@ async function appendCommand(
212
212
  return { kind: 'command', slug, command, event }
213
213
  }
214
214
 
215
+ function rejectCancelledAnswer(state: BuildState, captured?: Set<string>): void {
216
+ if (
217
+ state.verifyStage.superseded.some((item) =>
218
+ captured ? captured.has(item.escalation.id) : state.openEscalations.length === 0,
219
+ )
220
+ )
221
+ throw new BuildControlError(
222
+ 'no-open-escalations',
223
+ 'Cannot answer a stale escalation: its verifier occurrence was cancelled by fail-fast',
224
+ )
225
+ }
226
+
215
227
  function selectedOpen(state: BuildState, captured?: Set<string>): OpenEscalation[] {
216
228
  return captured === undefined
217
229
  ? state.openEscalations
@@ -354,7 +366,7 @@ export function decideRevise(
354
366
  if (open.length === 0) {
355
367
  const paused =
356
368
  state.status === 'paused'
357
- ? ` If a revision already landed, the build remains paused; run ab resume ${slug}.`
369
+ ? ` If a revision already merged, the build remains paused; run ab resume ${slug}.`
358
370
  : ''
359
371
  return {
360
372
  kind: 'refuse',
@@ -529,7 +541,7 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
529
541
  if (opts.action.kind === 'land') {
530
542
  if (!landPreconditions(current, facts.log.restack))
531
543
  throw new Error(
532
- 'Landing is not ready; wait for current-base verification and finalize before running ab land',
544
+ 'Merge is not ready; wait for current-base verification and finalize before running ab merge',
533
545
  )
534
546
  if (current.kind === 'node') {
535
547
  if (!opts.ticketSource)
@@ -545,7 +557,7 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
545
557
  !observed.contributions.length
546
558
  )
547
559
  throw new Error(
548
- 'Node is incomplete; wait for its children and verification before running ab land',
560
+ 'Node is incomplete; wait for its children and verification before running ab merge',
549
561
  )
550
562
  }
551
563
  }
@@ -564,13 +576,13 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
564
576
  })
565
577
  if (event) return { kind: 'command', slug: opts.slug, command: opts.action.kind, event }
566
578
  }
567
- throw new Error('Landing command was not recorded')
579
+ throw new Error('Merge command was not recorded')
568
580
  }
569
581
  case 'auto-merge-on':
570
582
  case 'auto-merge-off':
571
583
  case 'toggle-auto-merge':
572
584
  throw new Error(
573
- 'Auto-merge controls are retired; use ab hold or ab land and [[landing]] policy',
585
+ 'Auto-merge controls are retired; use ab hold or ab merge and [[merge]] policy',
574
586
  )
575
587
 
576
588
  case 'dashboard-pause': {
@@ -611,6 +623,10 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
611
623
  case 'answer': {
612
624
  const captured =
613
625
  opts.action.escalationIds === undefined ? undefined : new Set(opts.action.escalationIds)
626
+ // An unblocked node revision is an independent repair operation, not
627
+ // an answer to a historical verifier question.
628
+ if (captured || state.kind !== 'node' || opts.action.resolve?.kind !== 'revise-spec')
629
+ rejectCancelledAnswer(state, captured)
614
630
  const guidance = (opts.action.text ?? '').trim()
615
631
  const actor = humanActor(user, opts.via)
616
632
  const requestedCeiling = opts.action.reviewRoundCeiling
@@ -805,15 +821,43 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
805
821
  },
806
822
  })
807
823
  }
808
- await opts.store.append(opts.slug, {
809
- actor: KERNEL,
810
- type: 'spec.revised',
811
- payload: {
812
- artifact,
813
- escalation: decision.escalationSeq,
814
- ...(assets !== undefined ? { assets } : {}),
815
- },
816
- })
824
+ if (freshState.verifyStage.concurrent) {
825
+ // Cancellation can supersede the verifier while body preparation or
826
+ // answer writes are in flight. Revalidate effective authorization at
827
+ // the atomic revision boundary, rather than trusting that old read.
828
+ for (;;) {
829
+ const current = (await readBuildFacts(opts.store, opts.slug)).value.state
830
+ const authorization = decideRevise(opts.slug, current, captured)
831
+ if (authorization.kind === 'refuse') throwRefusal(authorization)
832
+ if (authorization.kind !== 'complete')
833
+ throw new BuildControlError(
834
+ 'missing-authorization',
835
+ 'Spec revision authorization is no longer effective',
836
+ )
837
+ if (
838
+ await opts.store.appendIfCurrent(opts.slug, current.lastSeq, {
839
+ actor: KERNEL,
840
+ type: 'spec.revised',
841
+ payload: {
842
+ artifact: authorization.artifact,
843
+ escalation: authorization.escalationSeq,
844
+ ...(authorization.assets === undefined ? {} : { assets: authorization.assets }),
845
+ },
846
+ })
847
+ )
848
+ break
849
+ }
850
+ } else {
851
+ await opts.store.append(opts.slug, {
852
+ actor: KERNEL,
853
+ type: 'spec.revised',
854
+ payload: {
855
+ artifact,
856
+ escalation: decision.escalationSeq,
857
+ ...(assets !== undefined ? { assets } : {}),
858
+ },
859
+ })
860
+ }
817
861
  if (alsoPaused) {
818
862
  await opts.store.append(opts.slug, {
819
863
  actor,
@@ -905,19 +949,30 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
905
949
  const alsoPaused = state.status === 'paused'
906
950
  // Appends are intentionally one-at-a-time. If an append fails midway, a
907
951
  // retry re-reduces the log and filters already answered ids out.
952
+ let answeredCount = 0
908
953
  for (const escalation of open) {
909
- await opts.store.append(opts.slug, {
910
- actor,
911
- type: 'escalation.answered',
912
- payload: {
913
- id: escalation.id,
914
- answer,
915
- resolution,
916
- ...(ceilingEscalation?.id === escalation.id
917
- ? { reviewRoundCeiling: requestedCeiling }
918
- : {}),
919
- },
920
- })
954
+ for (;;) {
955
+ const fresh = (await readBuildFacts(opts.store, opts.slug)).value.state
956
+ rejectCancelledAnswer(fresh, new Set([escalation.id]))
957
+ if (!fresh.openEscalations.some((item) => item.id === escalation.id)) break
958
+ if (
959
+ await opts.store.appendIfCurrent(opts.slug, fresh.lastSeq, {
960
+ actor,
961
+ type: 'escalation.answered',
962
+ payload: {
963
+ id: escalation.id,
964
+ answer,
965
+ resolution,
966
+ ...(ceilingEscalation?.id === escalation.id
967
+ ? { reviewRoundCeiling: requestedCeiling }
968
+ : {}),
969
+ },
970
+ })
971
+ ) {
972
+ answeredCount += 1
973
+ break
974
+ }
975
+ }
921
976
  }
922
977
  if (alsoPaused) {
923
978
  await opts.store.append(opts.slug, {
@@ -929,7 +984,7 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
929
984
  return {
930
985
  kind: 'answered',
931
986
  slug: opts.slug,
932
- count: open.length,
987
+ count: answeredCount,
933
988
  resolution,
934
989
  resumed: alsoPaused,
935
990
  ...(ceilingEscalation !== undefined && requestedCeiling !== undefined
@@ -1,7 +1,8 @@
1
+ import { resolveContextDirectory } from '../context-directory'
1
2
  import {
2
- collectNodeVerificationProvenance,
3
+ parseNodeVerificationContext,
3
4
  type NodeVerificationIndex,
4
- } from './node-verification-provenance'
5
+ } from '../kernel/node-verification-context'
5
6
  import { compatibilityDiagnostic } from '../kernel/mixed-version'
6
7
  import { readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
7
8
  /**
@@ -9,11 +10,10 @@ import { readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
9
10
  * gitignored `.ab/` scratch dir. Everything derives from
10
11
  * `PHASE_SPECS[phase].inputs` — the table drives, so the CLI, the manifest,
11
12
  * and the engine all validate against the same data (no per-phase switch
12
- * sprawl). Scoping is deliberate: what a phase *can't* see is part of its
13
- * design (the planner never sees code-review rounds; the reviewer sees prior
14
- * findings but not the producer's session).
13
+ * sprawl). Each manifest selects the current phase's inputs. Sibling phase
14
+ * directories remain readable; scratch separation is not filesystem isolation.
15
15
  *
16
- * Disposable `.ab/` content is wiped and recreated on every run — stale
16
+ * Disposable session-directory content is wiped and recreated on every run — stale
17
17
  * context is worse than no context — while legacy tracked entries are restored
18
18
  * byte-for-byte from the index. Git's local exclude keeps generated scratch
19
19
  * ignored without mutating the repository's own `.gitignore`.
@@ -62,7 +62,7 @@ export interface ContextDeps {
62
62
  ids?: IdSource
63
63
  }
64
64
 
65
- /** Paths are relative to `.ab/`, forward-slash separated. */
65
+ /** Paths are relative to the session directory, forward-slash separated. */
66
66
  export type MaterializedEntry = ArtifactRef | 'derived'
67
67
 
68
68
  /**
@@ -83,11 +83,13 @@ export interface ContextManifest {
83
83
  */
84
84
  required: string[]
85
85
  allowedTerminals: TerminalCommand[]
86
+ /** Workspace-relative directory for this session. */
87
+ contextDir: string
86
88
  /** Workspace-relative path where this manifest was written. */
87
89
  manifestPath: string
88
90
  /** Safe workspace-relative producer notes path (implement/reconcile only). */
89
91
  notesPath?: string
90
- /** relPath (under .ab/) → source artifact ref, or 'derived'. */
92
+ /** relPath (under the session directory) → source artifact ref, or 'derived'. */
91
93
  materialized: Record<string, MaterializedEntry>
92
94
  /** The ticket assets this build froze (SPEC §6.3), each written to `path`
93
95
  * (relative to the workspace). Omitted when the build pinned none. */
@@ -119,6 +121,9 @@ export interface ContextManifest {
119
121
  /** Agent-verify: the step's config from the workspace's autobuild.toml (§16.1). */
120
122
  step?: { name: string; config: VerifyStepConfig }
121
123
  /** The feedback this phase occurrence was started with (§15.3, §10). */
124
+ verifyStageFailure?: import('../kernel/verify-stage-state').VerifyStageFailure
125
+ verifyReports?: { step: string; report: import('../ontology').ArtifactRef; path: string }[]
126
+ cancelledVerify?: { step: string; attempt: number; cause: { step: string }; status: 'not-run' }[]
122
127
  feedback?: Feedback
123
128
  /** Chains a human resolved via dismiss-finding — the reviewer is told so (§15.6-B). */
124
129
  dismissedFindingIds?: string[]
@@ -141,7 +146,7 @@ function currentFeedback(events: CurrentBuildFacts, phase: Phase, round: number)
141
146
  return explicit ?? (phase === 'plan' ? (events.planFeedback[String(round)] ?? null) : null)
142
147
  }
143
148
 
144
- /** Empty and recreate `.ab/`; callers restore any tracked legacy entries. */
149
+ /** Empty and recreate the session directory; callers restore any tracked legacy entries. */
145
150
  async function wipeAbDir(abDir: string): Promise<void> {
146
151
  await rm(abDir, { recursive: true, force: true })
147
152
  await mkdir(abDir, { recursive: true })
@@ -161,7 +166,7 @@ function dismissedIds(state: BuildState, events: CurrentBuildFacts): string[] {
161
166
 
162
167
  /**
163
168
  * Materialize the phase's `.ab/` tree and return the manifest (also written
164
- * as `.ab/context.json`).
169
+ * as `$AB_CONTEXT_DIR/context.json`).
165
170
  */
166
171
  export async function buildContext(deps: ContextDeps): Promise<ContextManifest> {
167
172
  const { store, env, workspacePath } = deps
@@ -196,18 +201,29 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
196
201
  // Preserve legacy tracked scratch exactly while replacing disposable files.
197
202
  // Some adapter contract fixtures intentionally use a non-Git workspace;
198
203
  // context hydration still works there, while publication remains Git-only.
199
- const abDir = join(workspacePath, '.ab')
204
+ const contextDir = resolveContextDirectory(phase, env.contextDir)
205
+ const abDir = join(workspacePath, contextDir)
200
206
  const gitWorkspace =
201
207
  deps.exec !== undefined &&
202
208
  (await deps.exec(['git', 'rev-parse', '--is-inside-work-tree'], { cwd: workspacePath }))
203
209
  .exitCode === 0
204
210
  const tracked = gitWorkspace ? await trackedScratchPaths(deps.exec!, workspacePath) : []
211
+ if (tracked.some((path) => contextDir === path || contextDir.startsWith(`${path}/`))) {
212
+ throw new Error(
213
+ `Tracked content blocks context directory ${contextDir}; move that content before retrying`,
214
+ )
215
+ }
205
216
  await wipeAbDir(abDir)
206
217
  if (gitWorkspace) {
207
- await restoreTrackedScratch(deps.exec!, workspacePath, tracked)
218
+ await restoreTrackedScratch(
219
+ deps.exec!,
220
+ workspacePath,
221
+ tracked.filter((path) => path.startsWith(`${contextDir}/`)),
222
+ )
208
223
  await ensureScratchExcluded(deps.exec!, workspacePath)
209
224
  }
210
- if (!tracked.includes('.ab/.gitignore')) await writeFile(join(abDir, '.gitignore'), '*\n')
225
+ if (!tracked.includes('.ab/.gitignore'))
226
+ await writeFile(join(workspacePath, '.ab', '.gitignore'), '*\n')
211
227
 
212
228
  const trackedSet = new Set(tracked)
213
229
  const allocated = new Set<string>()
@@ -215,13 +231,15 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
215
231
  const locate = (desired: string): string => {
216
232
  const prior = locations.get(desired)
217
233
  if (prior !== undefined) return prior
218
- const path = allocateScratchPath(desired, trackedSet, allocated)
234
+ const path = allocateScratchPath(desired, trackedSet, allocated, `${contextDir}/`)
219
235
  locations.set(desired, path)
220
236
  return path
221
237
  }
222
238
  const manifestRelPath = locate('context.json')
223
239
  const notesRelPath =
224
240
  phase === 'implement' || phase === 'reconcile' ? locate(`${phase}-notes.md`) : undefined
241
+ if (notesRelPath !== undefined)
242
+ await mkdir(dirname(join(abDir, notesRelPath)), { recursive: true })
225
243
  const materialized: Record<string, MaterializedEntry> = {}
226
244
 
227
245
  async function writeDerived(desiredPath: string, content: string): Promise<string> {
@@ -230,12 +248,16 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
230
248
  await mkdir(dirname(target), { recursive: true })
231
249
  await writeFile(target, content)
232
250
  materialized[relPath] = 'derived'
233
- return `.ab/${relPath}`
251
+ return `${contextDir}/${relPath}`
234
252
  }
235
253
 
236
254
  /** Latest rev when `rev` omitted; silently skips absent kinds — the tree is
237
255
  * a projection of what exists, and the manifest shows what materialized. */
238
- async function writeArtifact(desiredPath: string, kind: string, rev?: number): Promise<void> {
256
+ async function writeArtifact(
257
+ desiredPath: string,
258
+ kind: string,
259
+ rev?: number,
260
+ ): Promise<string | undefined> {
239
261
  const node = state.nodeRestack
240
262
  const sourceKind =
241
263
  phase === 'reconcile' && node?.conflict && ['spec', 'plan', 'implement-notes'].includes(kind)
@@ -252,6 +274,7 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
252
274
  await mkdir(dirname(target), { recursive: true })
253
275
  await writeFile(target, artifact.content)
254
276
  materialized[relPath] = { kind: artifact.meta.kind, rev: artifact.meta.revision }
277
+ return `${contextDir}/${relPath}`
255
278
  }
256
279
 
257
280
  const manifest: ContextManifest = {
@@ -266,8 +289,9 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
266
289
  round,
267
290
  required: requiredKinds(spec, phase),
268
291
  allowedTerminals: allowedTerminals(phase),
269
- manifestPath: `.ab/${manifestRelPath}`,
270
- ...(notesRelPath !== undefined ? { notesPath: `.ab/${notesRelPath}` } : {}),
292
+ contextDir,
293
+ manifestPath: `${contextDir}/${manifestRelPath}`,
294
+ ...(notesRelPath !== undefined ? { notesPath: `${contextDir}/${notesRelPath}` } : {}),
271
295
  materialized,
272
296
  }
273
297
 
@@ -324,7 +348,7 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
324
348
  revision: pinned.revision,
325
349
  layout: pinned.layout,
326
350
  size: pinned.size,
327
- path: `.ab/${relPath}`,
351
+ path: `${contextDir}/${relPath}`,
328
352
  })
329
353
  }
330
354
  }
@@ -374,6 +398,32 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
374
398
  }
375
399
 
376
400
  if (inputs.findings === 'current' || inputs.currentFeedback === true) {
401
+ if (phase === 'implement') {
402
+ const receiptSeq = state.verifyStage.implementations[String(round)]
403
+ const receipt = state.verifyStage.failures.find((f) => f.seq === receiptSeq)
404
+ if (receipt) {
405
+ manifest.verifyStageFailure = receipt
406
+ manifest.verifyReports = []
407
+ for (const failed of receipt.failed) {
408
+ if (!failed.report) continue
409
+ const path = await writeArtifact(
410
+ `verify/${failed.step}.md`,
411
+ failed.report.kind,
412
+ failed.report.rev,
413
+ )
414
+ if (path === undefined)
415
+ throw new Error(
416
+ `Missing routed verify report ${failed.report.kind}@${failed.report.rev}`,
417
+ )
418
+ manifest.verifyReports.push({ step: failed.step, report: failed.report, path })
419
+ }
420
+ manifest.cancelledVerify = receipt.cancelled.map((c) => ({
421
+ ...c,
422
+ attempt: receipt.attempt,
423
+ status: 'not-run' as const,
424
+ }))
425
+ }
426
+ }
377
427
  const feedback = currentFeedback(events, phase, round)
378
428
  if (feedback !== null) {
379
429
  manifest.feedback = feedback
@@ -384,7 +434,7 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
384
434
  .map((id) => byId.get(id))
385
435
  .filter((finding): finding is Finding => finding !== undefined)
386
436
  await writeDerived('findings.json', `${JSON.stringify(resolved, null, 2)}\n`)
387
- } else if ('verify' in feedback) {
437
+ } else if ('verify' in feedback && manifest.verifyReports === undefined) {
388
438
  // The verify failure report routed back into the code loop (§5) — the
389
439
  // exact rev the feedback cites, not just the latest.
390
440
  await writeArtifact(
@@ -392,7 +442,7 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
392
442
  feedback.verify.report.kind,
393
443
  feedback.verify.report.rev,
394
444
  )
395
- } else {
445
+ } else if ('guidance' in feedback) {
396
446
  // A human escalation answer fed in as authoritative feedback (§15.6-B).
397
447
  await writeDerived('guidance.json', `${JSON.stringify(feedback.guidance, null, 2)}\n`)
398
448
  }
@@ -464,29 +514,21 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
464
514
  }
465
515
 
466
516
  if (isVerifyPhase(phase) && state.kind === 'node' && state.integration?.cycle) {
467
- if (!gitWorkspace)
468
- throw new Error('node verification provenance requires a Git workspace and exec')
469
- const record = await store.getBuild(build)
470
- if (!record) throw new Error(`node verification build ${build} is missing`)
471
- const contributionBase =
472
- state.nodeRestack?.contributionBoundaries?.[manifest.commitRange!.head] ??
473
- state.nodeRestack?.contributionBase ??
474
- state.nodeOpened?.sha
475
- if (!contributionBase)
517
+ const cycle = state.integration.cycle
518
+ if (!cycle.context)
476
519
  throw new Error(
477
- `node verification ${build} is missing its durable contribution boundary; restore node opening evidence`,
520
+ 'node verification is missing prepared context input; prepare a new integration cycle',
478
521
  )
479
- const { index, specs } = await collectNodeVerificationProvenance(
480
- store,
481
- record.repo,
482
- manifest.commitRange!,
483
- { exec: deps.exec!, workspacePath },
484
- { contributionBase, foreignAliases: state.nodeRestack?.foreignAliases },
522
+ const artifact = await store.getArtifact(build, cycle.context.kind, cycle.context.rev)
523
+ if (!artifact) throw new Error('node verification prepared context artifact is missing')
524
+ const { index, specs } = parseNodeVerificationContext(
525
+ new TextDecoder().decode(artifact.content),
526
+ cycle,
485
527
  )
486
528
  for (const contribution of index.contributions) {
487
529
  contribution.specPath = await writeDerived(
488
530
  `contributions/${contribution.build}/spec.md`,
489
- specs.get(contribution.build)!,
531
+ specs[contribution.build]!,
490
532
  )
491
533
  }
492
534
  const indexPath = await writeDerived(
@@ -565,6 +607,7 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
565
607
  // table in §16.1, so there is nothing to materialize yet — the input stays
566
608
  // in the table for when config grows one.
567
609
 
610
+ await mkdir(dirname(join(abDir, manifestRelPath)), { recursive: true })
568
611
  await writeFile(join(abDir, manifestRelPath), `${JSON.stringify(manifest, null, 2)}\n`)
569
612
 
570
613
  // Legacy tracked scratch is repository debt, not content Autobuild rewrites.
@@ -14,7 +14,7 @@ import type { AbEvent } from '../../events/catalog'
14
14
  import { defineReducer } from '../../kernel/incremental'
15
15
  import { verifyPhase } from '../../ontology'
16
16
 
17
- export const DASHBOARD_FACTS_REDUCER_VERSION = 2
17
+ export const DASHBOARD_FACTS_REDUCER_VERSION = 3
18
18
 
19
19
  /** One phase occurrence's wall-clock span, keyed by phase. `startSeq` is the
20
20
  * seq of the `*.started` event, so callers can scope by the same seq
@@ -130,6 +130,7 @@ function foldInterval(intervals: Record<string, PhaseTiming>, ev: AbEvent): void
130
130
  case 'verify.started':
131
131
  open(verifyPhase(ev.payload.step))
132
132
  break
133
+ case 'verify.cancelled':
133
134
  case 'verify.completed':
134
135
  close(verifyPhase(ev.payload.step))
135
136
  break