@defrex/autobuild 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/README.md +10 -18
  2. package/SPEC.md +499 -238
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +119 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/answering-blocked-builds.md +2 -2
  7. package/docs/architecture.md +262 -53
  8. package/docs/assets/headline-wide.png +0 -0
  9. package/docs/build-store.md +3 -41
  10. package/docs/builds.md +4 -4
  11. package/docs/cli.md +18 -4
  12. package/docs/configuration-overview.md +115 -4
  13. package/docs/configuration.md +488 -334
  14. package/docs/dispatcher-hosting.md +19 -34
  15. package/docs/dispatcher.md +1 -1
  16. package/docs/forges.md +5 -5
  17. package/docs/getting-started.md +2 -2
  18. package/docs/glossary.md +6 -6
  19. package/docs/intake.md +2 -0
  20. package/docs/integration-overview.md +15 -15
  21. package/docs/integration-tree.md +45 -38
  22. package/docs/integration.md +6 -6
  23. package/{skills/guide/references/landing-policy.md → docs/merge-policy.md} +40 -24
  24. package/docs/migration-1.0.md +17 -13
  25. package/docs/operating.md +41 -19
  26. package/docs/operator-api.md +180 -51
  27. package/docs/operator-surfaces.md +5 -18
  28. package/docs/overview.md +3 -3
  29. package/docs/plugin-authoring.md +21 -0
  30. package/docs/remote-store-protocol.md +242 -68
  31. package/docs/remote-ticket-protocol.md +30 -50
  32. package/docs/restacking.md +54 -15
  33. package/docs/seams.md +8 -8
  34. package/docs/setup.md +59 -119
  35. package/docs/skills.md +1 -1
  36. package/docs/spec-standard.md +6 -6
  37. package/docs/ticket-dependencies.md +7 -7
  38. package/docs/ticket-sources.md +18 -0
  39. package/docs/tickets.md +8 -2
  40. package/docs/troubleshooting.md +8 -12
  41. package/docs/upgrading.md +9 -4
  42. package/docs/verification.md +60 -14
  43. package/docs/workspaces.md +4 -4
  44. package/package.json +17 -6
  45. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  46. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  47. package/packages/core/src/accounts/local-credentials.ts +194 -0
  48. package/packages/core/src/accounts/local-inference.ts +106 -0
  49. package/packages/core/src/accounts/local-owner.ts +123 -0
  50. package/packages/core/src/accounts/sensitive.ts +2 -0
  51. package/packages/core/src/cli/accounts.ts +147 -0
  52. package/packages/core/src/cli/binary-direct.ts +13 -1
  53. package/packages/core/src/cli/binary-lifecycle.ts +65 -2
  54. package/packages/core/src/cli/binary.ts +3 -1
  55. package/packages/core/src/cli/build-control.ts +83 -28
  56. package/packages/core/src/cli/connect.ts +3 -3
  57. package/packages/core/src/cli/context.ts +81 -38
  58. package/packages/core/src/cli/dashboard/facts.ts +2 -1
  59. package/packages/core/src/cli/dashboard/integration-detail.ts +8 -8
  60. package/packages/core/src/cli/dashboard/integration-row.ts +40 -13
  61. package/packages/core/src/cli/dashboard/landing-display.ts +25 -0
  62. package/packages/core/src/cli/dashboard/model.ts +56 -33
  63. package/packages/core/src/cli/dashboard/poll.ts +9 -3
  64. package/packages/core/src/cli/dashboard/render.ts +59 -37
  65. package/packages/core/src/cli/dashboard/target-distance.ts +14 -0
  66. package/packages/core/src/cli/dashboard/tree.ts +3 -2
  67. package/packages/core/src/cli/dispatch-args.ts +1 -1
  68. package/packages/core/src/cli/dispatch-frontend.ts +6 -3
  69. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  70. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  71. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  72. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  73. package/packages/core/src/cli/dispatch.ts +106 -11
  74. package/packages/core/src/cli/env.ts +4 -0
  75. package/packages/core/src/cli/help.ts +46 -23
  76. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  77. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  78. package/packages/core/src/cli/init-validation.ts +160 -18
  79. package/packages/core/src/cli/main.ts +68 -8
  80. package/packages/core/src/cli/node-verification-provenance.ts +1 -97
  81. package/packages/core/src/cli/publication-settlement.ts +47 -21
  82. package/packages/core/src/cli/repository-status.ts +20 -9
  83. package/packages/core/src/cli/secrets.ts +173 -0
  84. package/packages/core/src/cli/status.ts +42 -5
  85. package/packages/core/src/cli/store-opening.ts +17 -2
  86. package/packages/core/src/cli/terminal.ts +22 -1
  87. package/packages/core/src/cli/terminals.ts +14 -10
  88. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  89. package/packages/core/src/cli/upgrade-landing.ts +70 -30
  90. package/packages/core/src/cli/upgrade.ts +3 -1
  91. package/packages/core/src/cli/wait.ts +15 -7
  92. package/packages/core/src/cli/watch-lifetime.ts +111 -0
  93. package/packages/core/src/cli/watch.ts +635 -510
  94. package/packages/core/src/config/accounts.ts +101 -0
  95. package/packages/core/src/config/effective-artifact.fixture.ts +27 -0
  96. package/packages/core/src/config/effective-artifact.ts +13 -0
  97. package/packages/core/src/config/landing.ts +1 -1
  98. package/packages/core/src/config/live.ts +14 -1
  99. package/packages/core/src/config/load.ts +21 -1
  100. package/packages/core/src/config/pipeline-source.ts +28 -0
  101. package/packages/core/src/config/reference-metadata.ts +2 -0
  102. package/packages/core/src/config/reference.ts +22 -7
  103. package/packages/core/src/config/roles.ts +54 -3
  104. package/packages/core/src/config/schema.ts +146 -162
  105. package/packages/core/src/context-directory.ts +26 -0
  106. package/packages/core/src/distribution-packaging.ts +26 -5
  107. package/packages/core/src/events/catalog.ts +10 -2
  108. package/packages/core/src/events/compatibility.ts +2 -1
  109. package/packages/core/src/events/globs.ts +1 -1
  110. package/packages/core/src/events/payloads.ts +73 -1
  111. package/packages/core/src/events/policy.ts +7 -0
  112. package/packages/core/src/events/repository.ts +4 -4
  113. package/packages/core/src/events/sessions.ts +6 -6
  114. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +574 -0
  115. package/packages/core/src/kernel/auto-merge.ts +2 -2
  116. package/packages/core/src/kernel/engine.ts +255 -26
  117. package/packages/core/src/kernel/generators/leaf-restack-log.ts +10 -0
  118. package/packages/core/src/kernel/integration-landing.ts +3 -3
  119. package/packages/core/src/kernel/integration-state.ts +27 -4
  120. package/packages/core/src/kernel/leaf-restack-state.ts +28 -3
  121. package/packages/core/src/kernel/log-index.ts +13 -1
  122. package/packages/core/src/kernel/node-landing.ts +8 -8
  123. package/packages/core/src/kernel/node-parent.ts +2 -2
  124. package/packages/core/src/kernel/node-restack-transaction.ts +1 -1
  125. package/packages/core/src/kernel/node-verification-context.ts +216 -0
  126. package/packages/core/src/kernel/phases.ts +1 -1
  127. package/packages/core/src/kernel/plan-verify-selection.ts +16 -0
  128. package/packages/core/src/kernel/publication-retry.ts +168 -0
  129. package/packages/core/src/kernel/reconcile-restack.ts +29 -1
  130. package/packages/core/src/kernel/reducer.ts +85 -5
  131. package/packages/core/src/kernel/target-distance.ts +45 -0
  132. package/packages/core/src/kernel/terminal-guard.ts +10 -1
  133. package/packages/core/src/kernel/verify-stage-state.ts +123 -0
  134. package/packages/core/src/kernel/verify-stages.ts +39 -0
  135. package/packages/core/src/ontology.ts +1 -0
  136. package/packages/core/src/operator/annotations.ts +6 -0
  137. package/packages/core/src/operator/control.ts +1 -1
  138. package/packages/core/src/operator/index.ts +3 -7
  139. package/packages/core/src/operator/landings.ts +5 -1
  140. package/packages/core/src/operator/presentation.ts +6 -1
  141. package/packages/core/src/operator/protocol.ts +6 -0
  142. package/packages/core/src/operator/query.ts +14 -18
  143. package/packages/core/src/operator/registry.ts +39 -7
  144. package/packages/core/src/operator/sandbox-host.ts +64 -40
  145. package/packages/core/src/operator/sandbox.ts +3 -0
  146. package/packages/core/src/operator/ticket-source-backend.ts +3 -12
  147. package/packages/core/src/operator/tickets.ts +25 -4
  148. package/packages/core/src/plugins/manifest.ts +2 -1
  149. package/packages/core/src/ports/forge/contract.ts +2 -2
  150. package/packages/core/src/ports/forge/git-rewrite.ts +25 -2
  151. package/packages/core/src/ports/forge/github-readiness.ts +2 -2
  152. package/packages/core/src/ports/forge/github.ts +26 -7
  153. package/packages/core/src/ports/forge/local-git.ts +4 -4
  154. package/packages/core/src/ports/forge/readiness.ts +1 -1
  155. package/packages/core/src/ports/forge-failure.ts +24 -0
  156. package/packages/core/src/ports/runner/account-env.ts +88 -0
  157. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  158. package/packages/core/src/ports/runner/claude.ts +26 -2
  159. package/packages/core/src/ports/runner/codex.ts +63 -31
  160. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  161. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  162. package/packages/core/src/ports/runner/routing.ts +35 -4
  163. package/packages/core/src/ports/tickets/contract.ts +58 -0
  164. package/packages/core/src/ports/tickets/tree.ts +1 -1
  165. package/packages/core/src/ports/types.ts +28 -7
  166. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  167. package/packages/core/src/ports/workspace/build-execution.ts +9 -2
  168. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  169. package/packages/core/src/ports/workspace/create.ts +2 -0
  170. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  171. package/packages/core/src/ports/workspace/phase-scratch.ts +4 -3
  172. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  173. package/packages/core/src/ports/workspace/vercel-sandbox.ts +182 -72
  174. package/packages/core/src/processes/build-child.ts +6 -8
  175. package/packages/core/src/processes/build-execution-state.ts +8 -5
  176. package/packages/core/src/processes/build-runner.ts +554 -99
  177. package/packages/core/src/processes/dispatcher.ts +209 -101
  178. package/packages/core/src/processes/execution-no-progress.ts +8 -1
  179. package/packages/core/src/processes/execution-settlement.ts +21 -3
  180. package/packages/core/src/processes/harvest-runner.ts +68 -8
  181. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  182. package/packages/core/src/processes/publication-loss.ts +8 -2
  183. package/packages/core/src/processes/publication-state.ts +42 -4
  184. package/packages/core/src/processes/repo-view.ts +14 -0
  185. package/packages/core/src/processes/verify-cycle-config.ts +96 -0
  186. package/packages/core/src/project-secrets.ts +105 -0
  187. package/packages/core/src/{integration → scenarios}/harness.ts +330 -317
  188. package/packages/core/src/secret-name.ts +41 -0
  189. package/packages/core/src/store/account-redaction.ts +156 -0
  190. package/packages/core/src/store/adapter.ts +1 -0
  191. package/packages/core/src/store/build-scope.ts +9 -0
  192. package/packages/core/src/store/contract.ts +116 -2
  193. package/packages/core/src/store/local/schema.ts +13 -0
  194. package/packages/core/src/store/local/store.ts +42 -0
  195. package/packages/core/src/store/memory.ts +47 -0
  196. package/packages/core/src/store/operator-presence.ts +21 -0
  197. package/packages/core/src/store/phase-session.ts +10 -0
  198. package/packages/core/src/store/reducer-value-shapes.json +5185 -4156
  199. package/packages/core/src/store/remote/client.ts +89 -48
  200. package/packages/core/src/store/remote/compatibility.ts +20 -0
  201. package/packages/core/src/store/remote/protocol.ts +4 -0
  202. package/packages/core/src/store/remote/version.ts +3 -1
  203. package/packages/core/src/store/retention.ts +2 -3
  204. package/packages/core/src/store/session-handle.ts +9 -0
  205. package/packages/core/src/store/streams/session-writer.ts +1 -1
  206. package/packages/core/src/store/types.ts +12 -2
  207. package/packages/core/src/testing/dispatch-read-budget.ts +122 -0
  208. package/packages/core/src/testing/index.ts +12 -1
  209. package/packages/core/src/testing/reduced-read-budget.ts +47 -0
  210. package/packages/core/src/testing/temp-directories.ts +58 -0
  211. package/skills/code-review/SKILL.md +23 -9
  212. package/skills/finalize/SKILL.md +15 -7
  213. package/skills/guide/SKILL.md +373 -148
  214. package/skills/guide/references/accounts.md +119 -0
  215. package/skills/guide/references/integration-tree.md +45 -38
  216. package/{docs/landing-policy.md → skills/guide/references/merge-policy.md} +40 -24
  217. package/skills/guide/references/migration-1.0.md +17 -13
  218. package/skills/guide/references/operator-api.md +180 -51
  219. package/skills/guide/references/plugin-authoring.md +21 -0
  220. package/skills/guide/references/remote-store-protocol.md +242 -68
  221. package/skills/guide/references/remote-ticket-protocol.md +30 -50
  222. package/skills/guide/references/restacking.md +54 -15
  223. package/skills/guide/references/setup.md +59 -119
  224. package/skills/guide/references/spec-standard.md +6 -6
  225. package/skills/guide/references/ticket-dependencies.md +7 -7
  226. package/skills/harvest/SKILL.md +3 -1
  227. package/skills/harvest-review/SKILL.md +3 -1
  228. package/skills/implement/SKILL.md +43 -17
  229. package/skills/operate/SKILL.md +118 -118
  230. package/skills/plan/SKILL.md +39 -13
  231. package/skills/plan-review/SKILL.md +15 -10
  232. package/skills/reconcile/SKILL.md +22 -3
  233. package/skills/spec/SKILL.md +20 -20
  234. package/skills/tickets/SKILL.md +12 -9
  235. package/templates/autobuild.toml +1 -1
  236. package/templates/hosted-service/package.json +2 -2
  237. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  238. package/docs/hosted-dispatcher.md +0 -275
  239. package/docs/hosted-service.md +0 -293
  240. package/docs/mcp.md +0 -149
  241. package/packages/core/src/orchestrator/approvals.ts +0 -115
  242. package/packages/core/src/orchestrator/conversation.ts +0 -167
  243. package/packages/core/src/orchestrator/model.ts +0 -86
  244. package/packages/core/src/orchestrator/prompt.ts +0 -63
  245. package/packages/core/src/orchestrator/tools.ts +0 -117
  246. package/packages/core/src/orchestrator/turn-runner.ts +0 -457
  247. package/packages/core/src/processes/orchestrator-tick.ts +0 -360
@@ -136,6 +136,7 @@ export interface LogIndex {
136
136
  /** Latest post-restart policy fact; authoritative only for its originating
137
137
  * reconcile completion, never for a newer review or reconcile cycle. */
138
138
  reconcilePolicy?: {
139
+ cycle?: number
139
140
  reconcileSeq: number
140
141
  steps: { step: string; enabled: boolean; source: string }[]
141
142
  }
@@ -162,6 +163,7 @@ export interface LogIndex {
162
163
  maxVerifyAttemptEver: number
163
164
  /** seq of the latest post-restart `reconcile.completed` — cycle boundary
164
165
  * input: reconciliation changed code, verify re-runs in full (§15.7). */
166
+ verifyConfigBoundary: number
165
167
  lastReconcileCompletedSeq: number
166
168
  /** seq of the latest post-restart `implement.completed` — a verify failure
167
169
  * with an implement round after it was already routed (§15.6-A). */
@@ -194,7 +196,7 @@ export interface LogIndex {
194
196
  guidanceDeliveries: GuidanceDelivery[]
195
197
  }
196
198
 
197
- export const LOG_INDEX_REDUCER_VERSION = 5
199
+ export const LOG_INDEX_REDUCER_VERSION = 6
198
200
 
199
201
  type ReviewVerdictPayload = EventPayload<'plan-review.verdict'>
200
202
 
@@ -228,6 +230,7 @@ export type LogIndexCandidate =
228
230
  | { kind: 'finalize-completed'; seq: number }
229
231
  | { kind: 'finalize-step'; seq: number; step: string }
230
232
  | { kind: 'reconcile-completed'; seq: number }
233
+ | { kind: 'config-superseded'; seq: number }
231
234
 
232
235
  export interface LogIndexAcc {
233
236
  readDeferrals: ReadDeferralsAcc
@@ -371,6 +374,10 @@ function foldLogIndex(acc: LogIndexAcc, events: readonly AbEvent[]): void {
371
374
  acc.candidates.push(verdictCandidate('code', event.payload, event.seq))
372
375
  break
373
376
 
377
+ case 'verify.config-captured':
378
+ case 'verify.config-superseded':
379
+ acc.candidates.push({ kind: 'config-superseded', seq: event.seq })
380
+ break
374
381
  case 'verify.started':
375
382
  noteGuidanceStart(
376
383
  `${verifyPhase(event.payload.step)}@${event.payload.attempt}`,
@@ -497,6 +504,7 @@ function finishLogIndex(acc: LogIndexAcc): LogIndex {
497
504
  const verifyStarted: VerifyStartRecord[] = []
498
505
  const finalizeStepsDone = new Set<string>()
499
506
  let reconcilePolicy: LogIndex['reconcilePolicy']
507
+ let verifyConfigBoundary = 0
500
508
  let lastReconcileCompletedSeq = 0
501
509
  let lastImplementCompletedSeq = 0
502
510
  let finalizeCompleted = false
@@ -564,6 +572,9 @@ function finishLogIndex(acc: LogIndexAcc): LogIndex {
564
572
  case 'implement-completed':
565
573
  lastImplementCompletedSeq = candidate.seq
566
574
  break
575
+ case 'config-superseded':
576
+ verifyConfigBoundary = Math.max(verifyConfigBoundary, candidate.seq)
577
+ break
567
578
  case 'verify-started':
568
579
  verifyStarted.push({
569
580
  seq: candidate.seq,
@@ -652,6 +663,7 @@ function finishLogIndex(acc: LogIndexAcc): LogIndex {
652
663
  verifyStarted,
653
664
  maxVerifyAttemptEver: acc.maxVerifyAttemptEver,
654
665
  reconcilePolicy,
666
+ verifyConfigBoundary,
655
667
  lastReconcileCompletedSeq,
656
668
  lastImplementCompletedSeq,
657
669
  finalizeCompleted,
@@ -38,7 +38,7 @@ export async function preflightNodeLanding(
38
38
  })
39
39
  if (!forge.rewrite || !forge.inspectLandingGate || !forge.inspectLandingPr)
40
40
  return defer(
41
- `Node landing requires rewrite, inspectLandingGate and inspectLandingPr capabilities; upgrade ${forge.name}. Native auto-merge is withheld to serialize node writes.`,
41
+ `Node merge requires rewrite, inspectLandingGate and inspectLandingPr capabilities; upgrade ${forge.name}. Native auto-merge is withheld to serialize node writes.`,
42
42
  )
43
43
  const pr = await forge.inspectLandingPr(workspacePath, prNumber)
44
44
  if (!pr.open || pr.base !== destination || pr.head !== branch)
@@ -63,7 +63,7 @@ export async function landIntoNode(
63
63
  })
64
64
  if (!forge.rewrite || !forge.inspectLandingGate || !forge.inspectLandingPr)
65
65
  return defer(
66
- `Node landing requires rewrite, inspectLandingGate and inspectLandingPr capabilities; upgrade ${forge.name}. Native auto-merge is withheld to serialize node writes.`,
66
+ `Node merge requires rewrite, inspectLandingGate and inspectLandingPr capabilities; upgrade ${forge.name}. Native auto-merge is withheld to serialize node writes.`,
67
67
  )
68
68
  if (
69
69
  (await deferMixedVersion(store, deps.slug, KERNEL)) ||
@@ -92,14 +92,14 @@ export async function landIntoNode(
92
92
  )
93
93
  throw new Error('destination node no longer admits writes')
94
94
  if (!(await store.renewNodeWriter(node, deps.holder)))
95
- throw new Error('node landing writer lease lost')
95
+ throw new Error('node merge writer lease lost')
96
96
  return state
97
97
  }
98
98
  let revision: number
99
99
  const append = async (event: EventWrite) => {
100
100
  await authority()
101
101
  const written = await store.appendIfCurrent(node, revision, event)
102
- if (!written) throw new Error('node landing reservation advanced')
102
+ if (!written) throw new Error('node merge reservation advanced')
103
103
  revision = written.seq
104
104
  }
105
105
  try {
@@ -141,7 +141,7 @@ export async function landIntoNode(
141
141
  cwd: workspacePath,
142
142
  })
143
143
  if (parents.exitCode !== 0 || message.exitCode !== 0)
144
- throw new Error('cannot inspect canonical node landing')
144
+ throw new Error('cannot inspect canonical node merge')
145
145
  if (
146
146
  deps.stack
147
147
  ? expected !== deps.stack.parent || candidate !== deps.stack.head
@@ -163,7 +163,7 @@ export async function landIntoNode(
163
163
  !deps.stack &&
164
164
  JSON.stringify(buildTrailers(message.stdout)) !== JSON.stringify([deps.slug])
165
165
  )
166
- throw new Error('node landing requires exactly one canonical source identity')
166
+ throw new Error('node merge requires exactly one canonical source identity')
167
167
  if (deps.stack) {
168
168
  const source = (await readBuildFacts(store, deps.slug)).value.state
169
169
  if (source.nodeRestack?.parentRequest || source.nodeRestack?.parentChange) return undefined
@@ -261,7 +261,7 @@ export async function landIntoNode(
261
261
  pr.headSha !== active.parent
262
262
  ) {
263
263
  await abandon()
264
- return defer('Reserved node landing no longer matches the PR; human action required.')
264
+ return defer('Reserved node merge no longer matches the PR; human action required.')
265
265
  }
266
266
  const gate = await forge.inspectLandingGate(deps.destination)
267
267
  if (gate.kind !== 'proved-ungated') {
@@ -363,7 +363,7 @@ export async function acknowledgeNodeLanding(
363
363
  await forge.commentOnPr?.(
364
364
  workspacePath,
365
365
  number,
366
- `Landed by Autobuild at commit ${sha}. Closing the review after the guarded fast-forward.`,
366
+ `Merged by Autobuild at commit ${sha}. Closing the review after the guarded fast-forward.`,
367
367
  )
368
368
  } catch {
369
369
  /* Still attempt closure when the comment service is unavailable. */
@@ -67,8 +67,8 @@ export function nodeParentBusy(state: BuildState): string | undefined {
67
67
  )
68
68
  return 'node is no longer open'
69
69
  if (state.pendingCommands.some((c) => c.command === 'abort')) return 'node is closing'
70
- if (state.integration?.intent && !state.integration.landing) return 'node is landing'
71
- if (state.nodeRestack?.active?.operation === 'landing') return 'node has a reserved child landing'
70
+ if (state.integration?.intent && !state.integration.landing) return 'node is merging'
71
+ if (state.nodeRestack?.active?.operation === 'landing') return 'node has a reserved child merge'
72
72
  return undefined
73
73
  }
74
74
  export async function validateNodeParent(
@@ -221,7 +221,7 @@ export async function runNodeTransaction(
221
221
  }
222
222
  const active = node!.active!
223
223
  if (active.operation !== 'restack')
224
- throw new Error('recover reserved node landing before restacking')
224
+ throw new Error('recover reserved node merge before restacking')
225
225
  if (
226
226
  active.merges.some((proof) => proof.build || proof.missing.length) &&
227
227
  state.answeredEscalations.some(
@@ -0,0 +1,216 @@
1
+ import { z } from 'zod'
2
+ import { commitRangeSchema, ticketRefSchema } from '../ontology'
3
+ import type { BuildState } from './reducer'
4
+ import { buildTrailers, validateBuildSlug } from './build-identity'
5
+ import { originalForeign } from './change-presence'
6
+ import { history, nodeInventory, type NodeGit } from './node-restack'
7
+ import type { CommitRange, TicketRef } from '../ontology'
8
+ import { readBuildFacts } from '../store/reduced-reads'
9
+ import type { BuildStore } from '../store/types'
10
+
11
+ export interface NodeContribution {
12
+ build: string
13
+ ticket: TicketRef
14
+ spec: { kind: 'spec'; rev: number }
15
+ specPath: string
16
+ commits: string[]
17
+ }
18
+ export interface NodeVerificationIndex {
19
+ range: CommitRange
20
+ handPushedCommits: { sha: string; originalSha: string; message: string }[]
21
+ contributions: NodeContribution[]
22
+ unattributedCommits: string[]
23
+ commits: { sha: string; build?: string }[]
24
+ }
25
+
26
+ /** Reachability, rather than the current child inventory, establishes membership. */
27
+ export async function collectNodeVerificationProvenance(
28
+ store: BuildStore,
29
+ repo: string,
30
+ range: CommitRange,
31
+ git: NodeGit,
32
+ ownership: { contributionBase: string; foreignAliases?: Record<string, string> },
33
+ ): Promise<{ index: NodeVerificationIndex; specs: Map<string, string> }> {
34
+ const index: NodeVerificationIndex = {
35
+ range,
36
+ handPushedCommits: [],
37
+ contributions: [],
38
+ unattributedCommits: [],
39
+ commits: [],
40
+ }
41
+ const owned = new Set((await nodeInventory(git, range.head, ownership.contributionBase)).foreign)
42
+ const aliases = new Map(Object.entries(ownership.foreignAliases ?? {}))
43
+ const specs = new Map<string, string>()
44
+ const byBuild = new Map<string, NodeContribution>()
45
+ for (const commit of await history(
46
+ git,
47
+ [`${range.base}..${range.head}`],
48
+ ['--reverse', '--topo-order'],
49
+ )) {
50
+ if (owned.has(commit.sha))
51
+ index.handPushedCommits.push({
52
+ sha: commit.sha,
53
+ originalSha: originalForeign(commit.sha, aliases),
54
+ message: commit.message,
55
+ })
56
+ const trailers = buildTrailers(commit.message)
57
+ if (trailers.length > 1) throw new Error(`ambiguous build identity on ${commit.sha}`)
58
+ const build = trailers[0]
59
+ if (build === undefined) {
60
+ index.commits.push({ sha: commit.sha })
61
+ index.unattributedCommits.push(commit.sha)
62
+ continue
63
+ }
64
+ try {
65
+ validateBuildSlug(build)
66
+ } catch {
67
+ throw new Error(`invalid build identity on ${commit.sha}: ${JSON.stringify(build)}`)
68
+ }
69
+ let contribution = byBuild.get(build)
70
+ if (contribution === undefined) {
71
+ try {
72
+ const record = await store.getBuild(build)
73
+ if (!record) throw new Error('unknown build')
74
+ if (record.repo !== repo) throw new Error('build belongs to a different repository')
75
+ if (!record.ticket) throw new Error('missing ticket identity')
76
+ const { state } = (await readBuildFacts(store, build)).value
77
+ if (state.specRev === undefined) throw new Error('missing authoritative spec revision')
78
+ const artifact = await store.getArtifact(build, 'spec', state.specRev)
79
+ if (!artifact) throw new Error(`missing spec@${state.specRev}`)
80
+ contribution = {
81
+ build,
82
+ ticket: record.ticket,
83
+ spec: { kind: 'spec', rev: state.specRev },
84
+ specPath: '',
85
+ commits: [],
86
+ }
87
+ byBuild.set(build, contribution)
88
+ index.contributions.push(contribution)
89
+ specs.set(build, new TextDecoder().decode(artifact.content))
90
+ } catch (error) {
91
+ throw new Error(
92
+ `node verification contribution ${build} at ${commit.sha}: ${error instanceof Error ? error.message : String(error)}`,
93
+ )
94
+ }
95
+ }
96
+ contribution.commits.push(commit.sha)
97
+ index.commits.push({ sha: commit.sha, build })
98
+ }
99
+ return { index, specs }
100
+ }
101
+
102
+ export const NODE_VERIFICATION_CONTEXT = 'node-verification-context'
103
+ const sha = z.string().min(1)
104
+ const buildIdentity = z.string().refine((value) => {
105
+ try {
106
+ validateBuildSlug(value)
107
+ return true
108
+ } catch {
109
+ return false
110
+ }
111
+ }, 'invalid build identity')
112
+ const payloadSchema = z.strictObject({
113
+ version: z.literal(1),
114
+ cycle: z.string().min(1),
115
+ range: commitRangeSchema,
116
+ index: z.strictObject({
117
+ range: commitRangeSchema,
118
+ handPushedCommits: z.array(z.strictObject({ sha, originalSha: sha, message: z.string() })),
119
+ contributions: z.array(
120
+ z.strictObject({
121
+ build: buildIdentity,
122
+ ticket: ticketRefSchema,
123
+ spec: z.strictObject({ kind: z.literal('spec'), rev: z.number().int().nonnegative() }),
124
+ specPath: z.literal(''),
125
+ commits: z.array(sha),
126
+ }),
127
+ ),
128
+ unattributedCommits: z.array(sha),
129
+ commits: z.array(z.strictObject({ sha, build: buildIdentity.optional() })),
130
+ }),
131
+ specs: z.record(z.string(), z.string()),
132
+ })
133
+ export function parseNodeVerificationContext(
134
+ content: string,
135
+ cycle: { id: string; parent: string; head: string },
136
+ ) {
137
+ const payload = payloadSchema.parse(JSON.parse(content))
138
+ if (
139
+ payload.cycle !== cycle.id ||
140
+ payload.range.base !== cycle.parent ||
141
+ payload.range.head !== cycle.head ||
142
+ payload.index.range.base !== cycle.parent ||
143
+ payload.index.range.head !== cycle.head
144
+ )
145
+ throw new Error('node verification prepared input cycle/range mismatch')
146
+ const builds = payload.index.contributions.map((c) => c.build)
147
+ if (
148
+ new Set(builds).size !== builds.length ||
149
+ Object.keys(payload.specs).length !== builds.length ||
150
+ builds.some((build) => !Object.hasOwn(payload.specs, build))
151
+ )
152
+ throw new Error('node verification prepared input spec membership mismatch')
153
+ const commits = new Map(payload.index.commits.map((c) => [c.sha, c.build]))
154
+ const unattributed = payload.index.commits.filter((c) => c.build === undefined).map((c) => c.sha)
155
+ if (
156
+ new Set(payload.index.unattributedCommits).size !== payload.index.unattributedCommits.length ||
157
+ unattributed.length !== payload.index.unattributedCommits.length ||
158
+ unattributed.some((sha) => !payload.index.unattributedCommits.includes(sha)) ||
159
+ payload.index.contributions.some(
160
+ (c) => c.commits.length === 0 || new Set(c.commits).size !== c.commits.length,
161
+ )
162
+ )
163
+ throw new Error('node verification prepared input commit membership mismatch')
164
+
165
+ if (
166
+ commits.size !== payload.index.commits.length ||
167
+ payload.index.contributions.some((c) =>
168
+ c.commits.some((sha) => commits.get(sha) !== c.build),
169
+ ) ||
170
+ payload.index.commits.some(
171
+ (c) =>
172
+ c.build !== undefined &&
173
+ !payload.index.contributions.some(
174
+ (item) => item.build === c.build && item.commits.includes(c.sha),
175
+ ),
176
+ ) ||
177
+ payload.index.unattributedCommits.some(
178
+ (sha) => !commits.has(sha) || commits.get(sha) !== undefined,
179
+ ) ||
180
+ payload.index.handPushedCommits.some((c) => !commits.has(c.sha))
181
+ )
182
+ throw new Error('node verification prepared input commit membership mismatch')
183
+ return { ...payload, index: payload.index as NodeVerificationIndex }
184
+ }
185
+
186
+ /** Called only from repository-authorized preparation, never from a guest. */
187
+ export async function prepareNodeVerificationContext(
188
+ store: BuildStore,
189
+ repo: string,
190
+ cycle: { id: string; parent: string; head: string },
191
+ state: Pick<BuildState, 'nodeRestack' | 'nodeOpened'>,
192
+ git: NodeGit,
193
+ ): Promise<string> {
194
+ const contributionBase =
195
+ state.nodeRestack?.contributionBoundaries?.[cycle.head] ??
196
+ state.nodeRestack?.contributionBase ??
197
+ state.nodeOpened?.sha
198
+ if (!contributionBase)
199
+ throw new Error(
200
+ 'node verification is missing its durable contribution boundary; restore node opening evidence',
201
+ )
202
+ const range = { base: cycle.parent, head: cycle.head }
203
+ const { index, specs } = await collectNodeVerificationProvenance(store, repo, range, git, {
204
+ contributionBase,
205
+ foreignAliases: state.nodeRestack?.foreignAliases,
206
+ })
207
+ const content = JSON.stringify({
208
+ version: 1,
209
+ cycle: cycle.id,
210
+ range,
211
+ index,
212
+ specs: Object.fromEntries(specs),
213
+ })
214
+ parseNodeVerificationContext(content, cycle)
215
+ return content
216
+ }
@@ -53,7 +53,7 @@ export interface ContextInputs {
53
53
  */
54
54
  answeredGuidance?: boolean
55
55
  /** The ticket assets the build froze at claim (SPEC §6.3), written under
56
- * `.ab/assets/`. Every phase receives them. */
56
+ * `$AB_CONTEXT_DIR/assets/`. Every phase receives them. */
57
57
  assets?: boolean
58
58
  }
59
59
 
@@ -103,3 +103,19 @@ export function resolvePlanVerifySteps(plan: string, config: Config): string[] {
103
103
 
104
104
  return config.verify.steps.filter((step) => selected.has(step))
105
105
  }
106
+
107
+ /** Runtime drift is distinct from strict plan-deposit validation above. */
108
+ export function resolveApprovedVerifySelection(
109
+ steps: readonly string[] | undefined,
110
+ config: Config,
111
+ ) {
112
+ const unknown = [
113
+ ...new Set(
114
+ steps?.filter(
115
+ (step) =>
116
+ !config.verify.steps.includes(step) || !Object.hasOwn(config.verify.stepConfigs, step),
117
+ ) ?? [],
118
+ ),
119
+ ].sort()
120
+ return { unknown, selected: steps === undefined || unknown.length ? undefined : new Set(steps) }
121
+ }
@@ -0,0 +1,168 @@
1
+ import type { AbEvent } from '../events/catalog'
2
+ import type { Actor } from '../events/envelope'
3
+ import type { BuildStore, Clock } from '../store/types'
4
+ import { readBuildFacts } from '../store/reduced-reads'
5
+ import { isForgeFailure } from '../ports/forge-failure'
6
+ import { ForgeRequestDeferred } from '../ports/forge-request-context'
7
+
8
+ /** A failed retry write must escape phase accounting and destructive release. */
9
+ export class PublicationRetryPersistenceError extends Error {
10
+ constructor(cause: unknown) {
11
+ super(
12
+ `publication retry persistence failed: ${cause instanceof Error ? cause.message : String(cause)}`,
13
+ { cause },
14
+ )
15
+ }
16
+ }
17
+ async function persistRetry<T>(write: () => Promise<T>): Promise<T> {
18
+ try {
19
+ return await write()
20
+ } catch (error) {
21
+ throw new PublicationRetryPersistenceError(error)
22
+ }
23
+ }
24
+
25
+ export const PUBLICATION_RETRY_SECONDS = [30, 60, 120, 240, 300, 300] as const
26
+ export type PublicationOperation = 'restack' | 'reconcile'
27
+ export type PublicationRetryEvent = Extract<
28
+ AbEvent,
29
+ {
30
+ type: 'publication.retry-scheduled' | 'publication.retry-exhausted' | 'escalation.answered'
31
+ }
32
+ >
33
+ export function publicationEscalationId(
34
+ operation: PublicationOperation,
35
+ id: string,
36
+ anchor: number,
37
+ ) {
38
+ return `publication:${operation}:${id}:${anchor}`
39
+ }
40
+ export function publicationRetryState(
41
+ events: readonly PublicationRetryEvent[],
42
+ operation: PublicationOperation,
43
+ rewriteId: string,
44
+ ) {
45
+ let anchor = 0
46
+ let latest: Exclude<PublicationRetryEvent, { type: 'escalation.answered' }> | undefined
47
+ for (const event of events) {
48
+ if (event.type === 'escalation.answered') {
49
+ if (
50
+ latest?.type === 'publication.retry-exhausted' &&
51
+ event.payload.id === publicationEscalationId(operation, rewriteId, anchor)
52
+ ) {
53
+ anchor = event.seq
54
+ latest = undefined
55
+ }
56
+ } else if (
57
+ event.payload.operation === operation &&
58
+ event.payload.rewriteId === rewriteId &&
59
+ event.payload.anchor === anchor
60
+ )
61
+ latest = event
62
+ }
63
+ return { anchor, latest }
64
+ }
65
+
66
+ export interface PublicationRetryDeps {
67
+ store: BuildStore
68
+ slug: string
69
+ clock: Clock
70
+ actor: Actor
71
+ }
72
+ /** Retry facts are written outside the provider catch: store failures propagate. */
73
+ export async function publicationRetryGate(
74
+ deps: PublicationRetryDeps,
75
+ operation: PublicationOperation,
76
+ id: string,
77
+ ) {
78
+ const facts = (await readBuildFacts(deps.store, deps.slug)).value
79
+ const state = facts.publication.retry(operation, id)
80
+ if (state.latest?.type === 'publication.retry-exhausted') {
81
+ const payload = state.latest.payload
82
+ const escalationId = publicationEscalationId(operation, id, state.anchor)
83
+ if (!facts.state.openEscalations.some((e) => e.id === escalationId)) {
84
+ const raised = await persistRetry(() =>
85
+ deps.store.appendIfCurrent(deps.slug, facts.state.lastSeq, {
86
+ actor: deps.actor,
87
+ type: 'escalation.raised',
88
+ payload: {
89
+ id: escalationId,
90
+ phase: 'reconcile',
91
+ round: payload.round,
92
+ source: 'policy',
93
+ policyCause: 'publication-retry-limit',
94
+ question: `${operation} publication exhausted after 6 retries; last error: ${payload.error}`,
95
+ },
96
+ }),
97
+ )
98
+ if (!raised) return publicationRetryGate(deps, operation, id)
99
+ }
100
+ throw new ForgeRequestDeferred('publication retry budget exhausted; awaiting answer')
101
+ }
102
+ if (
103
+ state.latest?.type === 'publication.retry-scheduled' &&
104
+ Date.parse(state.latest.payload.retryAt) > deps.clock().getTime()
105
+ )
106
+ throw new ForgeRequestDeferred(
107
+ `publication retry scheduled for ${state.latest.payload.retryAt}`,
108
+ )
109
+ }
110
+
111
+ export async function recordPublicationFailure(
112
+ deps: PublicationRetryDeps,
113
+ operation: PublicationOperation,
114
+ rewriteId: string,
115
+ round: number,
116
+ error: unknown,
117
+ ): Promise<never> {
118
+ if (error instanceof ForgeRequestDeferred) throw error
119
+ if (isForgeFailure(error) && error.details.kind === 'rate-limited')
120
+ throw new ForgeRequestDeferred(`forge cooldown until ${error.details.resetAt}`)
121
+ if (!isForgeFailure(error) || error.details.kind !== 'transient') throw error
122
+ const state = (await readBuildFacts(deps.store, deps.slug)).value.publication.retry(
123
+ operation,
124
+ rewriteId,
125
+ )
126
+ const failure = (state.latest?.payload.failure ?? 0) + 1
127
+ const payload = { operation, rewriteId, round, anchor: state.anchor, error: error.message }
128
+ if (failure <= PUBLICATION_RETRY_SECONDS.length) {
129
+ await persistRetry(() =>
130
+ deps.store.append(deps.slug, {
131
+ actor: deps.actor,
132
+ type: 'publication.retry-scheduled',
133
+ payload: {
134
+ ...payload,
135
+ failure,
136
+ retryAt: new Date(
137
+ deps.clock().getTime() + PUBLICATION_RETRY_SECONDS[failure - 1]! * 1000,
138
+ ).toISOString(),
139
+ },
140
+ }),
141
+ )
142
+ } else {
143
+ await persistRetry(() =>
144
+ deps.store.append(deps.slug, {
145
+ actor: deps.actor,
146
+ type: 'publication.retry-exhausted',
147
+ payload: { ...payload, failure: 7 },
148
+ }),
149
+ )
150
+ await publicationRetryGate(deps, operation, rewriteId)
151
+ }
152
+ throw new ForgeRequestDeferred('publication retry scheduled')
153
+ }
154
+
155
+ export async function retryPublicationEffect<T>(
156
+ deps: PublicationRetryDeps,
157
+ operation: PublicationOperation,
158
+ id: string,
159
+ round: number,
160
+ effect: () => Promise<T>,
161
+ ): Promise<T> {
162
+ await publicationRetryGate(deps, operation, id)
163
+ try {
164
+ return await effect()
165
+ } catch (error) {
166
+ return recordPublicationFailure(deps, operation, id, round, error)
167
+ }
168
+ }
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto'
1
2
  import { deferMixedVersion, MixedVersionDeferral } from './mixed-version'
2
3
  import { suspendNativeLanding } from './landing-publication'
3
4
  import { readBuildFacts } from '../store/reduced-reads'
@@ -517,7 +518,7 @@ export async function validateRestack(
517
518
  if ((await deps.exec(['test', '-d', path], { cwd: deps.workspacePath })).exitCode === 0)
518
519
  throw new Error(`finish the Git ${directory} operation before completing reconcile`)
519
520
  }
520
- if ((await output(deps, ['status', '--porcelain'])) !== '')
521
+ if ((await output(deps, ['status', '--porcelain', '--untracked-files=no'])) !== '')
521
522
  throw new Error('reconcile publication requires a clean worktree')
522
523
  if ((await output(deps, ['ls-files', '-u'])) !== '') throw new Error('unmerged files remain')
523
524
  const parents = await output(deps, ['show', '-s', '--format=%P', head])
@@ -552,6 +553,33 @@ export async function publishRestack(
552
553
  )
553
554
  throw new Error('rewrite target does not equal the authoritative reconcile start')
554
555
  await validateRestack(deps, intent, intent.headSha)
556
+ const files = (await git(deps, ['ls-files', '--others', '--exclude-standard', '-z'])).stdout
557
+ .split('\0')
558
+ .filter((path) => path !== '')
559
+ .sort()
560
+ if (files.length > 0) {
561
+ const operation = deps.automatic === undefined ? 'reconcile' : 'restack'
562
+ const pathsHash = createHash('sha256').update(JSON.stringify(files)).digest('hex')
563
+ const id = `${operation}:${intent.id}:${intent.headSha}:untracked:${pathsHash}`
564
+ const { observations } = (await readBuildFacts(deps.store, deps.slug)).value
565
+ if (
566
+ !observations.some(
567
+ (entry) => entry.id === id && JSON.stringify(entry.files) === JSON.stringify(files),
568
+ )
569
+ ) {
570
+ await deps.store.append(deps.slug, {
571
+ actor: KERNEL,
572
+ type: 'observation.recorded',
573
+ payload: {
574
+ id,
575
+ kind: 'followup',
576
+ summary: `Restack/reconcile publication excludes untracked files: ${files.map((path) => JSON.stringify(path)).join(', ')}`,
577
+ files,
578
+ refs: [`${operation}:${intent.id}`, intent.headSha],
579
+ },
580
+ })
581
+ }
582
+ }
555
583
  const archives = await archiveTips(deps, [intent.headSha])
556
584
  await deps.beforeRewrite?.()
557
585
  await suspendNativeLanding(deps, intent.id)