@defrex/autobuild 1.0.1 → 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
@@ -1,3 +1,10 @@
1
+ import {
2
+ advanceVerifyStage,
3
+ initialVerifyStageState,
4
+ verifyMemberKey,
5
+ runningVerifyMembers,
6
+ type VerifyStageState,
7
+ } from './verify-stage-state'
1
8
  import { advancePollingActivity } from './node-polling'
2
9
  import { integrationFailed } from './integration-state'
3
10
  import {
@@ -47,6 +54,8 @@ export interface OpenEscalation {
47
54
  phase: EscalationTarget
48
55
  round?: number
49
56
  source: EscalationSource
57
+ /** Raising agent identity, for occurrence-scoped cancellation. */
58
+ session?: string
50
59
  /** Policy guard identity. Absent only on historical policy raises. */
51
60
  policyCause?: PolicyEscalationCause
52
61
  deferral?: 'own-build-read'
@@ -320,14 +329,19 @@ export interface BuildState {
320
329
  *
321
330
  * `cycleSince` is the seq after which results describe the CURRENT code
322
331
  * (§15.6-A): max(restartSince, latest code-review approve, latest
323
- * `reconcile.completed`). Results at or before it describe code that no
332
+ * `reconcile.completed`, config capture/supersession). Results at or before it describe code that no
324
333
  * longer exists — implement or reconcile changed it, and a new cycle re-runs
325
334
  * from the FIRST step. 0 before any boundary lands. This is the same filter
326
335
  * engine.ts:275-276 applies over its post-restart index. */
336
+ verifyStage: VerifyStageState
327
337
  verify: {
328
338
  maxAttemptSeen: number
329
339
  results: VerifyResult[]
330
340
  currentStep?: string
341
+ running?: string[]
342
+ configPin?: import('../events/payloads').EventPayload<'verify.config-captured'> & {
343
+ seq: number
344
+ }
331
345
  cycleSince: number
332
346
  }
333
347
  /** Highest `reconcile.started.attempt` — the kernel's own occurrence
@@ -427,6 +441,7 @@ export interface BuildAcc {
427
441
  codeReviewApproval: BuildState['codeReviewApproval']
428
442
  planReviewFindings: Finding[][]
429
443
  codeReviewFindings: Finding[][]
444
+ verifyStage: VerifyStageState
430
445
  verify: BuildState['verify']
431
446
  reconcileAttempts: number
432
447
  observations: ObservationRecord[]
@@ -448,7 +463,7 @@ export interface BuildAcc {
448
463
  }
449
464
 
450
465
  /** Bump when `BuildAcc`'s shape or the fold's semantics change. */
451
- export const BUILD_REDUCER_VERSION = 21
466
+ export const BUILD_REDUCER_VERSION = 24
452
467
 
453
468
  function initialBuildAcc(): BuildAcc {
454
469
  return {
@@ -475,6 +490,7 @@ function initialBuildAcc(): BuildAcc {
475
490
  codeReviewApproval: undefined,
476
491
  planReviewFindings: [],
477
492
  codeReviewFindings: [],
493
+ verifyStage: initialVerifyStageState(),
478
494
  verify: { maxAttemptSeen: 0, results: [], cycleSince: 0 },
479
495
  reconcileAttempts: 0,
480
496
  observations: [],
@@ -620,6 +636,26 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
620
636
  acc.nodeRestack ??= { items: [] }
621
637
  advanceNodeRestack(acc.nodeRestack, [event])
622
638
  }
639
+ advanceVerifyStage(acc.verifyStage, event)
640
+ if (event.type === 'verify.cancelled') {
641
+ for (const escalation of [...openEscalations.values(), ...answeredEscalations]) {
642
+ const session = escalation.session
643
+ const key = session === undefined ? undefined : acc.verifyStage.owners[session]
644
+ const cancellation = key === undefined ? undefined : acc.verifyStage.cancellations[key]
645
+ if (!cancellation) continue
646
+ if (
647
+ 'answeredSeq' in escalation &&
648
+ 'resolution' in escalation &&
649
+ escalation.resolution === 'abort'
650
+ )
651
+ pending.abort = pending.abort.filter((command) => command.seq !== escalation.answeredSeq)
652
+ openEscalations.delete(escalation.id)
653
+ const index = answeredEscalations.findIndex((e) => e.id === escalation.id)
654
+ if (index >= 0) answeredEscalations.splice(index, 1)
655
+ if (!acc.verifyStage.superseded.some((e) => e.escalation.id === escalation.id))
656
+ acc.verifyStage.superseded.push({ escalation, cancellation })
657
+ }
658
+ }
623
659
  switch (event.type) {
624
660
  // Facts the projection does not need (workspace liveness is the
625
661
  // dispatcher's concern; finalize post-steps are failure-tolerant §5).
@@ -673,6 +709,8 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
673
709
  // pending publication. Recovery runs through the existing
674
710
  // abandoned-publication flow (abandonedPublicationPending), which re-runs
675
711
  // the phase — the reducer needs no state from it.
712
+ case 'publication.retry-scheduled':
713
+ case 'publication.retry-exhausted':
676
714
  case 'publication.lost':
677
715
  case 'dispatch.comment-posted':
678
716
  case 'pr-attachment.designated':
@@ -976,6 +1014,23 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
976
1014
  complete('code-review', event.seq, { round })
977
1015
  break
978
1016
 
1017
+ case 'verify.config-captured':
1018
+ verify.configPin = { ...event.payload, seq: event.seq }
1019
+ verify.cycleSince = Math.max(verify.cycleSince, event.seq)
1020
+ break
1021
+ case 'verify.config-superseded':
1022
+ case 'integration.prepared':
1023
+ verify.cycleSince = Math.max(verify.cycleSince, event.seq)
1024
+ break
1025
+ case 'verify.cancelled':
1026
+ if (
1027
+ acc.verifyStage.cancellations[verifyMemberKey(event.payload.step, event.payload.attempt)]
1028
+ ?.seq === event.seq
1029
+ )
1030
+ complete(verifyPhase(event.payload.step), event.seq, { attempt: event.payload.attempt })
1031
+ break
1032
+ case 'verify.stage-failed':
1033
+ break
979
1034
  case 'verify.started':
980
1035
  verify.maxAttemptSeen = Math.max(verify.maxAttemptSeen, event.payload.attempt)
981
1036
  verify.currentStep = event.payload.step
@@ -987,6 +1042,7 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
987
1042
  break
988
1043
  case 'verify.completed': {
989
1044
  const result = normalizeVerifyCompletion(event.payload)
1045
+ if (acc.verifyStage.cancellations[verifyMemberKey(result.step, result.attempt)]) break
990
1046
  verify.maxAttemptSeen = Math.max(verify.maxAttemptSeen, result.attempt)
991
1047
  verify.results.push({
992
1048
  ...(result.baseSha === undefined ? {} : { baseSha: result.baseSha }),
@@ -1101,20 +1157,27 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1101
1157
  seq: event.seq,
1102
1158
  })
1103
1159
  break
1104
- case 'escalation.raised':
1105
- openEscalations.set(event.payload.id, {
1160
+ case 'escalation.raised': {
1161
+ const escalation: OpenEscalation = {
1106
1162
  id: event.payload.id,
1107
1163
  phase: event.payload.phase,
1108
1164
  round: event.payload.round,
1109
1165
  source: event.payload.source,
1166
+ ...(event.actor.kind === 'agent' ? { session: event.actor.session } : {}),
1110
1167
  ...(event.payload.policyCause !== undefined
1111
1168
  ? { policyCause: event.payload.policyCause }
1112
1169
  : {}),
1113
1170
  question: event.payload.question,
1114
1171
  refs: event.payload.refs,
1115
1172
  seq: event.seq,
1116
- })
1173
+ }
1174
+ const key =
1175
+ escalation.session === undefined ? undefined : acc.verifyStage.owners[escalation.session]
1176
+ const cancellation = key === undefined ? undefined : acc.verifyStage.cancellations[key]
1177
+ if (cancellation) acc.verifyStage.superseded.push({ escalation, cancellation })
1178
+ else openEscalations.set(escalation.id, escalation)
1117
1179
  break
1180
+ }
1118
1181
  case 'escalation.answered': {
1119
1182
  // Matched by id — answers may arrive out of raise order. An answer
1120
1183
  // with no open raise is ignored (total over any prefix).
@@ -1172,6 +1235,19 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1172
1235
  acc.round = round
1173
1236
  acc.currentPhase = currentPhase
1174
1237
  acc.lastCompletedPhase = lastCompletedPhase
1238
+ const running = runningVerifyMembers(acc.verifyStage, verify.cycleSince)
1239
+ if (Object.keys(acc.verifyStage.members).length)
1240
+ verify.running = running.map((member) => member.step)
1241
+ if (acc.verifyStage.concurrent && running.length) {
1242
+ verify.currentStep = running.at(-1)!.step
1243
+ if (!currentPhase || currentPhase.phase.startsWith('verify:'))
1244
+ currentPhase = {
1245
+ phase: verifyPhase(running.at(-1)!.step),
1246
+ attempt: running.at(-1)!.attempt,
1247
+ seq: running.at(-1)!.seq,
1248
+ }
1249
+ } else if (acc.verifyStage.concurrent) verify.currentStep = undefined
1250
+ acc.currentPhase = currentPhase
1175
1251
  acc.openEscalations = [...openEscalations.values()]
1176
1252
  acc.pr = pr
1177
1253
  acc.prState = prState
@@ -1262,6 +1338,7 @@ function finishBuild(acc: BuildAcc): BuildState {
1262
1338
  codeReviewApproved: acc.codeReviewApproved,
1263
1339
  codeReviewApproval: acc.codeReviewApproval,
1264
1340
  reviewFindings: { planReview: acc.planReviewFindings, codeReview: acc.codeReviewFindings },
1341
+ verifyStage: acc.verifyStage,
1265
1342
  verify: acc.verify,
1266
1343
  reconcileAttempts: acc.reconcileAttempts,
1267
1344
  observations: acc.observations,
@@ -0,0 +1,45 @@
1
+ import type { EventPayload } from '../events/payloads'
2
+ import type { Exec } from '../ports/workspace/git-worktree'
3
+ import type { Forge } from '../ports/types'
4
+
5
+ /** Advisory destination-only commits, pinned to both immutable tips. */
6
+ export async function sampleTargetDistance(input: {
7
+ branch: string
8
+ sha: string
9
+ buildBranch: string
10
+ localPath?: string
11
+ exec: Exec
12
+ forge: Pick<Forge, 'compareBranches'>
13
+ }): Promise<EventPayload<'target.distance'>> {
14
+ const { branch, sha, buildBranch, localPath, exec, forge } = input
15
+ const unknown = { branch, sha, head: null, count: null }
16
+ if (localPath) {
17
+ const git = async (...args: string[]) => {
18
+ const result = await exec(['git', ...args], { cwd: localPath })
19
+ if (result.exitCode !== 0) throw new Error(result.stderr || `git ${args[0]} failed`)
20
+ return result.stdout.trim()
21
+ }
22
+ const head = await git('rev-parse', '--verify', `refs/heads/${buildBranch}^{commit}`)
23
+ if (!/^[a-f0-9]{40,64}$/.test(head)) return unknown
24
+ const object = await exec(['git', 'cat-file', '-e', `${sha}^{commit}`], { cwd: localPath })
25
+ if (object.exitCode !== 0)
26
+ await git('fetch', '--no-tags', '--no-write-fetch-head', '--refmap=', 'origin', sha)
27
+ const output = await git('rev-list', '--count', `${head}..${sha}`)
28
+ if (!/^\d+$/.test(output)) return unknown
29
+ const count = Number(output)
30
+ if (!Number.isSafeInteger(count) || count < 0) return unknown
31
+ if ((await git('rev-parse', '--verify', `refs/heads/${buildBranch}^{commit}`)) !== head)
32
+ return unknown
33
+ return { branch, sha, head, count }
34
+ }
35
+ if (!forge.compareBranches) return unknown
36
+ const compared = await forge.compareBranches(buildBranch, branch)
37
+ if (
38
+ compared.headSha !== sha ||
39
+ !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(compared.parentSha) ||
40
+ !Number.isSafeInteger(compared.ahead) ||
41
+ compared.ahead < 0
42
+ )
43
+ return unknown
44
+ return { branch, sha, head: compared.parentSha, count: compared.ahead }
45
+ }
@@ -13,7 +13,7 @@ interface TerminalGuardAcc {
13
13
  export function terminalGuardReducer(env: CliEnv) {
14
14
  const spec = phaseSpecFor(env.phase)
15
15
  return defineReducer<TerminalGuardAcc, AbEvent, { diagnostic?: string }>({
16
- version: 2,
16
+ version: 3,
17
17
  initial: () => ({ reconcileAttempt: 0 }),
18
18
  fold(acc, events) {
19
19
  for (const event of events) {
@@ -101,6 +101,15 @@ function checkEvent(
101
101
  'Remote publication is pending; do not run ab done again (§8.4).',
102
102
  )
103
103
  }
104
+ if (
105
+ event.type === 'verify.cancelled' &&
106
+ isVerifyPhase(env.phase) &&
107
+ event.payload.step === verifyStep(env.phase) &&
108
+ event.payload.attempt === env.round
109
+ )
110
+ throw new Error(
111
+ `terminal rejected: ${env.phase}@${env.round} was cancelled by verify:${event.payload.cause.step}`,
112
+ )
104
113
  if (event.type !== spec.terminalEvent) return
105
114
  if (
106
115
  (event.type === 'verify.completed' || event.type === 'finalize.completed') &&
@@ -0,0 +1,123 @@
1
+ import type { AbEvent } from '../events/catalog'
2
+ import type { EventPayload } from '../events/payloads'
3
+ import { normalizeVerifyCompletion } from '../events/payloads'
4
+ import type { OpenEscalation, AnsweredEscalation } from './reducer'
5
+
6
+ export interface VerifyMember extends EventPayload<'verify.started'> {
7
+ seq: number
8
+ }
9
+ export interface VerifyCancellation extends EventPayload<'verify.cancelled'> {
10
+ seq: number
11
+ }
12
+ export interface VerifyStageFailure extends EventPayload<'verify.stage-failed'> {
13
+ seq: number
14
+ }
15
+ export interface VerifyStageState {
16
+ cycle: number
17
+ concurrent: boolean
18
+ executionSeq: number
19
+ cleanupExecutionSeq?: number
20
+ members: Record<string, VerifyMember>
21
+ owners: Record<string, string>
22
+ outcomes: Record<string, number>
23
+ cancellations: Record<string, VerifyCancellation>
24
+ failures: VerifyStageFailure[]
25
+ implementations: Record<string, number>
26
+ superseded: Array<{
27
+ escalation: OpenEscalation | AnsweredEscalation
28
+ cancellation: VerifyCancellation
29
+ }>
30
+ }
31
+ export function verifyMemberKey(step: string, attempt: number): string {
32
+ return JSON.stringify([step, attempt])
33
+ }
34
+ export function initialVerifyStageState(): VerifyStageState {
35
+ return {
36
+ cycle: 0,
37
+ concurrent: false,
38
+ executionSeq: 0,
39
+ members: {},
40
+ owners: {},
41
+ outcomes: {},
42
+ cancellations: {},
43
+ failures: [],
44
+ implementations: {},
45
+ superseded: [],
46
+ }
47
+ }
48
+ export function advanceVerifyStage(state: VerifyStageState, event: AbEvent): void {
49
+ switch (event.type) {
50
+ case 'verify.config-captured':
51
+ case 'verify.config-superseded':
52
+ case 'spec.revised':
53
+ case 'reconcile.completed':
54
+ case 'integration.prepared':
55
+ state.cycle = event.seq
56
+ break
57
+ case 'code-review.verdict':
58
+ if (event.payload.verdict === 'approve') state.cycle = event.seq
59
+ break
60
+ case 'execution.started':
61
+ state.executionSeq = event.seq
62
+ break
63
+ case 'verify.started': {
64
+ const key = verifyMemberKey(event.payload.step, event.payload.attempt)
65
+ if (
66
+ Object.entries(state.members).some(
67
+ ([other, member]) =>
68
+ other !== key &&
69
+ member.seq > state.cycle &&
70
+ !state.outcomes[other] &&
71
+ !state.cancellations[other],
72
+ )
73
+ )
74
+ state.concurrent = true
75
+ state.members[key] = { ...event.payload, seq: event.seq }
76
+ break
77
+ }
78
+ case 'session.started': {
79
+ const { phase, round, session } = event.payload
80
+ if (phase?.startsWith('verify:') && round !== undefined) {
81
+ const key = verifyMemberKey(phase.slice(7), round)
82
+ if (state.members[key]) state.owners[session] = key
83
+ }
84
+ break
85
+ }
86
+ case 'verify.completed': {
87
+ const result = normalizeVerifyCompletion(event.payload)
88
+ const key = verifyMemberKey(result.step, result.attempt)
89
+ if (!state.cancellations[key]) state.outcomes[key] = event.seq
90
+ break
91
+ }
92
+ case 'verify.cancelled': {
93
+ const key = verifyMemberKey(event.payload.step, event.payload.attempt)
94
+ if (!state.outcomes[key] && !state.cancellations[key]) {
95
+ state.cancellations[key] = { ...event.payload, seq: event.seq }
96
+ state.cleanupExecutionSeq = state.executionSeq
97
+ }
98
+ break
99
+ }
100
+ case 'verify.stage-failed':
101
+ state.failures.push({ ...event.payload, seq: event.seq })
102
+ break
103
+ case 'implement.started':
104
+ if (
105
+ event.payload.verifyStageFailure !== undefined &&
106
+ state.failures.some(
107
+ (f) =>
108
+ f.seq === event.payload.verifyStageFailure &&
109
+ f.seq < event.seq &&
110
+ f.cycle === state.cycle,
111
+ )
112
+ )
113
+ state.implementations[String(event.payload.round)] = event.payload.verifyStageFailure
114
+ break
115
+ }
116
+ }
117
+ export function runningVerifyMembers(state: VerifyStageState, cycle: number): VerifyMember[] {
118
+ return Object.entries(state.members)
119
+ .filter(
120
+ ([key, member]) => member.seq > cycle && !state.outcomes[key] && !state.cancellations[key],
121
+ )
122
+ .map(([, member]) => member)
123
+ }
@@ -0,0 +1,39 @@
1
+ import { verifyStages, type VerifyConfig } from '../config/schema'
2
+ import type { VerifyRecord } from './log-index'
3
+ import type { VerifyStageState } from './verify-stage-state'
4
+
5
+ /** Pure barrier selection shared by leaf and integration verification. */
6
+ export function activeVerifyStage(
7
+ config: VerifyConfig,
8
+ results: readonly VerifyRecord[],
9
+ state: VerifyStageState,
10
+ cycle: number,
11
+ ) {
12
+ const stages = verifyStages(config)
13
+ for (const stage of stages) {
14
+ const outcomes = stage.map((step) =>
15
+ results.find((result) => result.seq > cycle && result.step === step),
16
+ )
17
+ if (outcomes.every((result) => result?.outcome === 'pass' || result?.outcome === 'skipped'))
18
+ continue
19
+ const cancellations = Object.values(state.cancellations).filter(
20
+ (item) => item.seq > cycle && stage.includes(item.step),
21
+ )
22
+ const unfinished = stage.filter(
23
+ (step, index) => !outcomes[index] && !cancellations.some((item) => item.step === step),
24
+ )
25
+ const failures = outcomes.filter((result): result is VerifyRecord => result?.outcome === 'fail')
26
+ const cause = [...failures]
27
+ .filter((result) => config.stepConfigs[result.step]?.failFast === true)
28
+ .sort((a, b) => a.seq - b.seq)[0]
29
+ return {
30
+ stage: [...stage],
31
+ failures,
32
+ cancellations,
33
+ unfinished,
34
+ cause,
35
+ settled: unfinished.length === 0,
36
+ }
37
+ }
38
+ return undefined
39
+ }
@@ -112,6 +112,7 @@ export const policyEscalationCauseSchema = z.enum([
112
112
  'execution-no-progress',
113
113
  'setup-failure-limit',
114
114
  'infrastructure-failure-limit',
115
+ 'publication-retry-limit',
115
116
  'phase-attempt-limit',
116
117
  'non-retryable-phase-failure',
117
118
  ])
@@ -26,6 +26,12 @@ export interface ToolAnnotationsTableEntry {
26
26
 
27
27
  /** The exact version-one tool names; the registry's closed table must match. */
28
28
  export const OPERATOR_TOOL_ANNOTATIONS = {
29
+ 'merges.list': {
30
+ readOnlyHint: true,
31
+ destructiveHint: false,
32
+ idempotentHint: true,
33
+ approval: 'never',
34
+ },
29
35
  'landings.list': {
30
36
  readOnlyHint: true,
31
37
  destructiveHint: false,
@@ -37,7 +37,7 @@ export async function setRepositorySetting(opts: {
37
37
  if (opts.setting === 'auto-merge-default')
38
38
  throw new OperatorControlError(
39
39
  'retired-setting',
40
- 'Auto-merge default is retired; configure [[landing]] rules in autobuild.toml',
40
+ 'Auto-merge default is retired; configure [[merge]] rules in autobuild.toml',
41
41
  )
42
42
  await opts.store.ensureRepo(opts.repo)
43
43
  const payload = {
@@ -54,13 +54,7 @@ export {
54
54
  OrchestratorConfigError,
55
55
  orchestratorConfig,
56
56
  } from './query'
57
- export {
58
- orchestratorWakeGlobs,
59
- ORCHESTRATOR_ROUTE_LIMIT_SECONDS,
60
- type OrchestratorConfig,
61
- } from '../config/schema'
62
- export type { OrchestratorTurnRunner } from '../orchestrator/turn-runner'
63
- export { createOrchestratorTurnRunner } from '../orchestrator/turn-runner'
57
+ export type { OrchestratorConfig } from '../config/schema'
64
58
  export { randomIds } from '../ids'
65
59
  export type { Config } from '../config/schema'
66
60
  export {
@@ -24,7 +24,11 @@ export async function listOperatorLandings(opts: {
24
24
  if (digest.terminal !== undefined) continue
25
25
  const facts = await view.buildFacts(record.slug)
26
26
  const artifact = facts.state.landing?.decision
27
- ? await view.getArtifact(record.slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
27
+ ? await view.getArtifact(
28
+ record.slug,
29
+ facts.state.verify.configPin?.artifact.kind ?? BUILD_EFFECTIVE_CONFIG_ARTIFACT,
30
+ facts.state.verify.configPin?.artifact.rev,
31
+ )
28
32
  : null
29
33
  const expected = artifact ? parseEffectiveBuildConfig(artifact).verify.steps : undefined
30
34
  const tree = projectTree(record, facts.state, facts.log.restack, expected)
@@ -1,5 +1,10 @@
1
1
  export { capacityExplanation } from '../kernel/dispatch-capacity'
2
- export { landingPolicyDisplay } from '../cli/dashboard/landing-display'
2
+ export {
3
+ landingPolicyDisplay,
4
+ mergeVocabulary,
5
+ mergeSummary,
6
+ mergedChildren,
7
+ } from '../cli/dashboard/landing-display'
3
8
  export {
4
9
  pauseResumeHelp,
5
10
  buildActionAvailability,
@@ -1,3 +1,4 @@
1
+ import { normalizeEffectiveConfigArtifact } from '../config/effective-artifact'
1
2
  import { migrationIdentity } from '../kernel/ticket-migrations'
2
3
  import { enrichDrainingRow, projectHandoffs } from '../cli/dashboard/handoff'
3
4
  import { enrichIntegrationRows } from '../cli/dashboard/integration-row'
@@ -196,7 +197,7 @@ export function decodeEffectiveConfig(content: Uint8Array, label: string): Confi
196
197
  `effective config ${label} is not valid JSON`,
197
198
  )
198
199
  }
199
- const parsed = configSchema.safeParse(raw)
200
+ const parsed = configSchema.safeParse(normalizeEffectiveConfigArtifact(raw))
200
201
  if (!parsed.success) {
201
202
  throw new OperatorQueryError(
202
203
  'effective-config-unavailable',
@@ -228,10 +229,15 @@ async function readPinnedConfig(
228
229
  store: BuildStore,
229
230
  slug: string,
230
231
  live: Config,
232
+ pin?: BuildState['verify']['configPin'],
231
233
  ): Promise<PinnedProjection> {
232
234
  let artifact: Artifact | null
233
235
  try {
234
- artifact = await store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
236
+ artifact = await store.getArtifact(
237
+ slug,
238
+ pin?.artifact.kind ?? BUILD_EFFECTIVE_CONFIG_ARTIFACT,
239
+ pin?.artifact.rev,
240
+ )
235
241
  } catch {
236
242
  artifact = null
237
243
  }
@@ -282,7 +288,7 @@ export async function getOperatorBuild(opts: {
282
288
  const { config, repositoryEvents } = await effectiveConfig(opts.store, opts.repo)
283
289
  let dashboardRow: DashboardBuild | null = null
284
290
  if (!projectsNoDashboardRow(state)) {
285
- const pinned = await readPinnedConfig(opts.store, opts.slug, config)
291
+ const pinned = await readPinnedConfig(opts.store, opts.slug, config, state.verify.configPin)
286
292
  const row = projectBuildFromFacts(record, state, facts, config, undefined, pinned.config)
287
293
  // Implied by the gate; kept as an explicit check (not an assertion) so the
288
294
  // code never lies if `effectiveStatus` and `projectBuild` ever drift.
@@ -409,7 +415,7 @@ async function dashboardFromView(
409
415
  (await readBuildFacts(view, record.slug)).value.provisionMarker !== undefined,
410
416
  })
411
417
  if (projectsNoDashboardRow(facts.state)) continue
412
- const pinned = await readPinnedConfig(view, record.slug, config)
418
+ const pinned = await readPinnedConfig(view, record.slug, config, facts.state.verify.configPin)
413
419
  const row = projectBuildFromFacts(
414
420
  record,
415
421
  facts.state,
@@ -468,10 +474,7 @@ async function dashboardFromView(
468
474
  }
469
475
  }
470
476
 
471
- /** Thrown when a deposited `dispatcher-effective-config` artifact exists but
472
- * cannot be parsed or validated: the hosted message route maps this to a 500
473
- * `internal` — a broken config must never silently disable the orchestrator
474
- * (AUT-342). */
477
+ /** A deposited sandbox-gate config artifact is unreadable or invalid. */
475
478
  export class OrchestratorConfigError extends Error {
476
479
  constructor(message: string) {
477
480
  super(message)
@@ -479,17 +482,10 @@ export class OrchestratorConfigError extends Error {
479
482
  }
480
483
  }
481
484
 
482
- /** The repository's orchestrator configuration, resolved from the latest
483
- * deposited `dispatcher-effective-config` artifact (AUT-342). Returns null
484
- * when no artifact exists — the orchestrator is disabled, and message
485
- * posting behaves exactly as it did before this feature. Throws
486
- * `OperatorQueryError` (code `effective-config-unavailable`) when an
487
- * artifact exists but is unreadable or invalid: a deployment that deposited
488
- * a broken config must fail loudly (a 500 on the message route), never
489
- * silently disable the orchestrator. */
485
+ /** Resolve the sandbox gate from the latest effective config; absent/disabled returns null. */
490
486
  export async function orchestratorConfig(store: BuildStore, repo: string): Promise<Config | null> {
491
487
  // A repository the store has no record for has no deposited artifact and
492
- // no dispatcher history: the orchestrator is disabled there.
488
+ // no dispatcher history: sandbox tools are disabled there.
493
489
  if ((await store.getRepo(repo)) === null) return null
494
490
  const artifacts = await store.listRepoArtifacts(repo, DISPATCHER_EFFECTIVE_CONFIG_ARTIFACT)
495
491
  if (artifacts.length === 0) return null
@@ -508,7 +504,7 @@ export async function orchestratorConfig(store: BuildStore, repo: string): Promi
508
504
  `effective config ${latest.kind}@${latest.revision} is not valid JSON`,
509
505
  )
510
506
  }
511
- const parsed = configSchema.safeParse(raw)
507
+ const parsed = configSchema.safeParse(normalizeEffectiveConfigArtifact(raw))
512
508
  if (!parsed.success) {
513
509
  throw new OrchestratorConfigError(
514
510
  `effective config ${latest.kind}@${latest.revision} is invalid: ${parsed.error.message}`,
@@ -266,9 +266,9 @@ const buildControlInput = z.strictObject({
266
266
  repo: repoField,
267
267
  slug: slugField,
268
268
  action: z
269
- .enum(['pause', 'cancel-pause', 'resume', 'land', 'hold', 'abort', 'discard'])
269
+ .enum(['pause', 'cancel-pause', 'resume', 'merge', 'land', 'hold', 'abort', 'discard'])
270
270
  .describe(
271
- 'Control to request: "pause" (or "cancel-pause" to revoke a pending pause), "resume" a paused build, "land" for landing consent or "hold" to withdraw consent — or the destructive "abort" (cancels the build, cleans up its PR and workspace, returns the ticket to triage) and "discard" (dequeue a queued build).',
271
+ 'Control to request: "pause" (or "cancel-pause" to revoke a pending pause), "resume" a paused build, "merge" (deprecated alias "land") for merge consent or "hold" to withdraw consent — or the destructive "abort" (cancels the build, cleans up its PR and workspace, returns the ticket to triage) and "discard" (dequeue a queued build).',
272
272
  ),
273
273
  })
274
274
 
@@ -478,9 +478,16 @@ function defineTool(
478
478
  * here and a row in `operator/annotations.ts`; the contract suite proves the
479
479
  * two stay in lockstep. */
480
480
  export const TOOLS: readonly ToolEntry[] = [
481
+ defineTool(
482
+ 'merges.list',
483
+ 'List ready merges awaiting consent or held, with frozen effective targets and verification evidence.',
484
+ repositoryStatusInput,
485
+ 'JSON array ordered by slug: kind, target, branch, candidate, reason, verification and node completeness.',
486
+ async (raw, ctx) => listOperatorLandings({ store: ctx.store, ...(raw as { repo: string }) }),
487
+ ),
481
488
  defineTool(
482
489
  'landings.list',
483
- 'List ready landings awaiting consent or held, with frozen effective targets and verification evidence.',
490
+ 'Deprecated alias for merges.list. List ready merges awaiting consent or held, with frozen effective targets and verification evidence.',
484
491
  repositoryStatusInput,
485
492
  'JSON array ordered by slug: kind, target, branch, candidate, reason, verification and node completeness.',
486
493
  async (raw, ctx) => listOperatorLandings({ store: ctx.store, ...(raw as { repo: string }) }),
@@ -591,11 +598,15 @@ export const TOOLS: readonly ToolEntry[] = [
591
598
  ),
592
599
  defineTool(
593
600
  'builds.control',
594
- 'Pause immediately suspends a live agent session. Resume continues where stopped when supported; remote and unsupported sessions rerun fresh. Request a durable control for one active build: pause/cancel-pause, resume, hold or land — or the destructive abort and discard. Land requires a ready candidate; hold withdraws landing consent.',
601
+ 'Pause immediately suspends a live agent session. Resume continues where stopped when supported; remote and unsupported sessions rerun fresh. Request a durable control for one active build: pause/cancel-pause, resume, hold or merge — or the destructive abort and discard. Merge requires a ready candidate; hold withdraws merge consent.',
595
602
  buildControlInput,
596
603
  'Either {kind: "command", slug, command, event} for an accepted control, or {kind: "answer-required", slug, escalationIds} when a resume needs its open escalations answered first.',
597
604
  async (raw, ctx) => {
598
- const input = raw as z.infer<typeof buildControlInput>
605
+ const received = raw as z.infer<typeof buildControlInput>
606
+ const input = {
607
+ ...received,
608
+ action: received.action === 'merge' ? ('land' as const) : received.action,
609
+ }
599
610
  await controlPrechecks(ctx.store, input.repo, input.slug, input.action)
600
611
  // The route maps BOTH pause and cancel-pause to `dashboard-pause`:
601
612
  // on a running build it requests a pause, and on a build with a pending
@@ -695,7 +706,7 @@ export const TOOLS: readonly ToolEntry[] = [
695
706
  'repository.bulk_control',
696
707
  'Pause or resume the whole repository: hold queued builds, set intake, and request per-build pause/resume in one walk.',
697
708
  bulkControlInput,
698
- '{direction, slugs, paused, intake}: the direction, the slugs that received a durable request, and the repository-wide hold/intake values written. A partial walk surfaces as a refusal with code "bulk-partial" and a progress object naming what landed.',
709
+ '{direction, slugs, paused, intake}: the direction, the slugs that received a durable request, and the repository-wide hold/intake values written. A partial walk surfaces as a refusal with code "bulk-partial" and a progress object naming what merged.',
699
710
  async (raw, ctx) => {
700
711
  const input = raw as z.infer<typeof bulkControlInput>
701
712
  return bulkControlRepository({