@defrex/autobuild 1.7.0 → 1.8.1

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 (116) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +316 -47
  3. package/docs/answering-blocked-builds.md +44 -3
  4. package/docs/architecture.md +62 -7
  5. package/docs/cli.md +1 -0
  6. package/docs/configuration-overview.md +1 -1
  7. package/docs/configuration.md +49 -9
  8. package/docs/dispatcher.md +1 -1
  9. package/docs/integration-overview.md +2 -2
  10. package/docs/integration-tree.md +7 -4
  11. package/docs/merge-policy.md +78 -6
  12. package/docs/migration-1.0.md +4 -2
  13. package/docs/operating.md +3 -2
  14. package/docs/operator-api.md +26 -5
  15. package/docs/operator-surfaces.md +10 -0
  16. package/docs/plugin-authoring.md +1 -1
  17. package/docs/remote-store-protocol.md +9 -1
  18. package/docs/restacking.md +23 -4
  19. package/docs/ticket-dependencies.md +9 -4
  20. package/docs/tickets.md +1 -1
  21. package/docs/troubleshooting.md +1 -1
  22. package/package.json +3 -3
  23. package/packages/core/src/cli/attention.ts +1 -0
  24. package/packages/core/src/cli/build-control.ts +65 -7
  25. package/packages/core/src/cli/context.ts +55 -14
  26. package/packages/core/src/cli/dashboard/actions.ts +13 -4
  27. package/packages/core/src/cli/dashboard/landing-display.ts +32 -8
  28. package/packages/core/src/cli/dashboard/model.ts +61 -8
  29. package/packages/core/src/cli/dashboard/render.ts +28 -3
  30. package/packages/core/src/cli/dashboard/tree.ts +9 -1
  31. package/packages/core/src/cli/help.ts +69 -7
  32. package/packages/core/src/cli/landings.ts +1 -1
  33. package/packages/core/src/cli/main.ts +60 -9
  34. package/packages/core/src/cli/publication-settlement.ts +10 -0
  35. package/packages/core/src/cli/status.ts +178 -12
  36. package/packages/core/src/cli/terminals.ts +197 -4
  37. package/packages/core/src/cli/wait.ts +1 -0
  38. package/packages/core/src/cli/watch.ts +71 -0
  39. package/packages/core/src/config/landing.ts +12 -0
  40. package/packages/core/src/config/path-selectors.ts +68 -0
  41. package/packages/core/src/config/schema.ts +40 -58
  42. package/packages/core/src/events/catalog.ts +17 -3
  43. package/packages/core/src/events/compatibility.ts +2 -1
  44. package/packages/core/src/events/head-paths-limits.ts +25 -0
  45. package/packages/core/src/events/payloads.ts +315 -20
  46. package/packages/core/src/events/policy.ts +21 -0
  47. package/packages/core/src/events/repository.ts +30 -1
  48. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +247 -6
  49. package/packages/core/src/kernel/consent-revocation.ts +72 -0
  50. package/packages/core/src/kernel/dispatch-capacity.ts +19 -8
  51. package/packages/core/src/kernel/engine.ts +48 -8
  52. package/packages/core/src/kernel/head-paths-state.ts +63 -0
  53. package/packages/core/src/kernel/head-paths.ts +401 -0
  54. package/packages/core/src/kernel/landing-policy-identity.ts +20 -0
  55. package/packages/core/src/kernel/landing-policy.ts +55 -2
  56. package/packages/core/src/kernel/landing-readiness.ts +104 -9
  57. package/packages/core/src/kernel/landing-state.ts +44 -4
  58. package/packages/core/src/kernel/leaf-restack-base.ts +34 -0
  59. package/packages/core/src/kernel/leaf-restack-state.ts +22 -2
  60. package/packages/core/src/kernel/log-index.ts +27 -1
  61. package/packages/core/src/kernel/node-polling.ts +13 -3
  62. package/packages/core/src/kernel/node-restack-state.ts +8 -1
  63. package/packages/core/src/kernel/node-restack-transaction.ts +45 -0
  64. package/packages/core/src/kernel/read-deferrals.ts +3 -1
  65. package/packages/core/src/kernel/read-facts.ts +28 -1
  66. package/packages/core/src/kernel/reducer-registry.ts +22 -1
  67. package/packages/core/src/kernel/reducer.ts +316 -17
  68. package/packages/core/src/kernel/target-observation.ts +2 -5
  69. package/packages/core/src/kernel/terminal-guard.ts +52 -3
  70. package/packages/core/src/kernel/ticket-handbacks.ts +40 -0
  71. package/packages/core/src/kernel/ticket-preparation.ts +12 -1
  72. package/packages/core/src/kernel/ticket-wait.ts +345 -0
  73. package/packages/core/src/kernel/verify-applicability.ts +9 -19
  74. package/packages/core/src/ontology.ts +1 -0
  75. package/packages/core/src/operator/annotations.ts +6 -0
  76. package/packages/core/src/operator/index.ts +3 -0
  77. package/packages/core/src/operator/protocol.ts +15 -2
  78. package/packages/core/src/operator/registry.ts +97 -5
  79. package/packages/core/src/operator/repository-events.ts +67 -0
  80. package/packages/core/src/ports/tickets/fake.ts +5 -0
  81. package/packages/core/src/ports/types.ts +3 -2
  82. package/packages/core/src/processes/build-execution-state.ts +30 -1
  83. package/packages/core/src/processes/build-runner.ts +150 -18
  84. package/packages/core/src/processes/dispatcher.ts +739 -97
  85. package/packages/core/src/processes/execution-no-progress.ts +22 -2
  86. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  87. package/packages/core/src/processes/publication-state.ts +6 -1
  88. package/packages/core/src/store/digest.ts +41 -2
  89. package/packages/core/src/store/reduced-reads.ts +4 -1
  90. package/packages/core/src/store/reducer-value-shapes.json +10108 -8432
  91. package/packages/core/src/store/remote/client.ts +28 -2
  92. package/packages/core/src/store/remote/protocol.ts +11 -1
  93. package/packages/core/src/store/remote/released-clients.json +22 -0
  94. package/packages/core/src/store/remote/released-reducer-values/1.8.0.json +29043 -0
  95. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  96. package/packages/core/src/store/repo-state-events.ts +2 -0
  97. package/packages/core/src/store/types.ts +16 -0
  98. package/packages/core/src/testing/reduced-read-budget.ts +347 -0
  99. package/skills/code-review/SKILL.md +8 -0
  100. package/skills/finalize/SKILL.md +4 -0
  101. package/skills/guide/SKILL.md +125 -26
  102. package/skills/guide/references/integration-tree.md +7 -4
  103. package/skills/guide/references/merge-policy.md +78 -6
  104. package/skills/guide/references/migration-1.0.md +4 -2
  105. package/skills/guide/references/operator-api.md +26 -5
  106. package/skills/guide/references/plugin-authoring.md +1 -1
  107. package/skills/guide/references/remote-store-protocol.md +9 -1
  108. package/skills/guide/references/restacking.md +23 -4
  109. package/skills/guide/references/ticket-dependencies.md +9 -4
  110. package/skills/implement/SKILL.md +15 -1
  111. package/skills/operate/SKILL.md +104 -13
  112. package/skills/plan/SKILL.md +17 -2
  113. package/skills/plan-review/SKILL.md +8 -0
  114. package/skills/reconcile/SKILL.md +21 -5
  115. package/skills/tickets/SKILL.md +5 -4
  116. package/templates/hosted-service/package.json +2 -2
@@ -1,4 +1,6 @@
1
1
  import { readBuildPage } from '../store/event-reads'
2
+ import { abortDestinationSchema } from '../events/payloads'
3
+ import { readRepositoryAttentionPage } from './repository-events'
2
4
  import { requestNodeRestack } from './restack'
3
5
  import { listOperatorLandings } from './landings'
4
6
  import { getOperatorTicketTree } from './tickets'
@@ -33,7 +35,12 @@ import { TicketAssigneesUnsupported } from '../ports/tickets/assignees'
33
35
  * every mutator, and — for constrained bindings — repository targeting.
34
36
  */
35
37
  import { z } from 'zod'
36
- import { controlBuild, BuildControlError, type BuildControlAction } from '../cli/build-control'
38
+ import {
39
+ controlBuild,
40
+ BuildControlError,
41
+ parseConsentHead,
42
+ type BuildControlAction,
43
+ } from '../cli/build-control'
37
44
  import type { Via } from '../events/envelope'
38
45
  import { bulkControlRepository, BulkWalkError } from '../cli/bulk-control'
39
46
  import { systemClock, type BuildStore, type Clock } from '../store/types'
@@ -271,12 +278,57 @@ const buildArtifactInput = z.strictObject({
271
278
  })
272
279
 
273
280
  const buildControlInput = z.strictObject({
281
+ head: z
282
+ .string()
283
+ .min(1)
284
+ .optional()
285
+ .describe(
286
+ 'Only with "merge"/"land": the candidate head (full SHA or ≥7-character prefix) the operator reviewed. Consent is refused, with nothing recorded, unless it is the current candidate head.',
287
+ ),
288
+
274
289
  repo: repoField,
275
290
  slug: slugField,
276
291
  action: z
277
292
  .enum(['pause', 'cancel-pause', 'resume', 'merge', 'land', 'hold', 'abort', 'discard'])
278
293
  .describe(
279
- '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).',
294
+ '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, hands the ticket back to triage, or to ready with `to`) and "discard" (dequeue a queued build).',
295
+ ),
296
+ to: abortDestinationSchema
297
+ .optional()
298
+ .describe(
299
+ 'Abort only: where cleanup hands the ticket back — "triage" (the default) or "ready" (blockers kept, redispatched once they merge; falls back to triage when the ticket no longer conforms to the spec standard).',
300
+ ),
301
+ reason: z
302
+ .string()
303
+ .optional()
304
+ .describe('Abort only: why, 1–2000 characters; quoted in the hand-back ticket comment.'),
305
+ })
306
+
307
+ const repositoryEventsInput = z.strictObject({
308
+ repo: repoField,
309
+ cursor: z
310
+ .number()
311
+ .int()
312
+ .min(0)
313
+ .safe()
314
+ .optional()
315
+ .describe(
316
+ 'Repository journal cursor: return events with seq strictly greater than this. Omit to receive no events and a baseline cursor for the current head.',
317
+ ),
318
+ waitSeconds: z
319
+ .number()
320
+ .int()
321
+ .min(0)
322
+ .max(30)
323
+ .default(0)
324
+ .describe(
325
+ 'Bounded wait: hold the call for at most this many seconds waiting for a new event before returning an empty page (0–30; 0 returns immediately).',
326
+ ),
327
+ filter: z
328
+ .enum(['attention', 'all'])
329
+ .default('attention')
330
+ .describe(
331
+ '"attention" (the default) returns only the repository events `ab watch --operator` reports by default, such as ticket.handed-back; "all" returns every scanned event.',
280
332
  ),
281
333
  })
282
334
 
@@ -536,7 +588,7 @@ export const TOOLS: readonly ToolEntry[] = [
536
588
  'builds.list',
537
589
  'List one repository’s builds, newest first, with effective status derived from the build log.',
538
590
  buildListInput,
539
- 'JSON array of build summaries: slug, ticket ref, effective status, phase/round/attempt, PR number/url/state, updatedAt, lease health, and durable-event progress.',
591
+ 'JSON array of build summaries: slug, ticket ref, effective status, phase/round/attempt, PR number/url/state, updatedAt, lease health, durable-event progress, and any ticket wait (`wait` with its state and tickets; `waitOnly` when the wait is the only open escalation).',
540
592
  async (raw, ctx) => {
541
593
  const input = raw as z.infer<typeof buildListInput>
542
594
  return listOperatorBuilds({
@@ -616,7 +668,7 @@ export const TOOLS: readonly ToolEntry[] = [
616
668
  ),
617
669
  defineTool(
618
670
  'builds.control',
619
- '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.',
671
+ '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, and an optional head binds consent to the reviewed head; hold withdraws merge consent.',
620
672
  buildControlInput,
621
673
  '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.',
622
674
  async (raw, ctx) => {
@@ -625,6 +677,24 @@ export const TOOLS: readonly ToolEntry[] = [
625
677
  ...received,
626
678
  action: received.action === 'merge' ? ('land' as const) : received.action,
627
679
  }
680
+ let head: string | undefined
681
+ if (input.head !== undefined) {
682
+ if (input.action !== 'land')
683
+ throw new RouteRefusalError({
684
+ kind: 'validation',
685
+ error: 'head applies only to the merge action',
686
+ })
687
+ head = parseConsentHead(input.head)
688
+ if (head === undefined)
689
+ throw new RouteRefusalError({
690
+ kind: 'validation',
691
+ error: 'head must be a nonblank commit SHA without whitespace',
692
+ })
693
+ }
694
+ if (input.action !== 'abort' && (input.to !== undefined || input.reason !== undefined)) {
695
+ const error = `"to" and "reason" apply only to the abort action, not "${received.action}"`
696
+ throw new RegistryError('validation', error, { kind: 'validation', error })
697
+ }
628
698
  await controlPrechecks(ctx.store, input.repo, input.slug, input.action)
629
699
  // The route maps BOTH pause and cancel-pause to `dashboard-pause`:
630
700
  // on a running build it requests a pause, and on a build with a pending
@@ -635,7 +705,15 @@ export const TOOLS: readonly ToolEntry[] = [
635
705
  ? { kind: 'dashboard-pause' }
636
706
  : input.action === 'resume'
637
707
  ? { kind: 'dashboard-resume' }
638
- : { kind: input.action }
708
+ : input.action === 'land' && head !== undefined
709
+ ? { kind: 'land', head }
710
+ : input.action === 'abort'
711
+ ? {
712
+ kind: 'abort',
713
+ ...(input.to !== undefined ? { to: input.to } : {}),
714
+ ...(input.reason !== undefined ? { reason: input.reason } : {}),
715
+ }
716
+ : { kind: input.action }
639
717
  return controlBuild({
640
718
  store: ctx.store,
641
719
  ...operatorControlTickets({ store: ctx.store, repo: input.repo, backend: ctx.tickets }),
@@ -708,6 +786,20 @@ export const TOOLS: readonly ToolEntry[] = [
708
786
  return getRepositoryStatus(ctx.store, input.repo)
709
787
  },
710
788
  ),
789
+ defineTool(
790
+ 'repository.events',
791
+ 'Read one repository’s journal after a cursor, optionally waiting (bounded, ≤30s) for a new event — the connected agent’s repository attention watch, matching `ab watch --operator`’s default repository filter (for example ticket.handed-back after a ticket hand-back). Build attention comes from builds.events.',
792
+ repositoryEventsInput,
793
+ '{events, cursor, hasMore}: the matching events among at most 256 scanned journal rows in sequence order, and the cursor to pass next time — the last scanned seq, which advances past filtered events. hasMore means more rows are already waiting. An expired cursor fails with code "cursor-too-old": re-baseline by omitting the cursor and reconcile with repository.status.',
794
+ async (raw, ctx) => {
795
+ const input = raw as z.infer<typeof repositoryEventsInput>
796
+ return readRepositoryAttentionPage(ctx.store, input.repo, {
797
+ ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),
798
+ waitSeconds: input.waitSeconds,
799
+ filter: input.filter,
800
+ })
801
+ },
802
+ ),
711
803
  defineTool(
712
804
  'repository.settings',
713
805
  'Set or toggle a durable repository setting: ticket intake or the claim-time auto-merge default.',
@@ -0,0 +1,67 @@
1
+ import { repositoryNeedsAttention } from '../cli/attention'
2
+ import type { RepositoryEvent } from '../events/repository'
3
+ import { BUILD_EVENT_PAGE_SIZE, CursorTooOldError } from '../store/event-reads'
4
+ import type { BuildStore } from '../store/types'
5
+ import { RegistryError } from './registry'
6
+
7
+ /** One `repository.events` call scans at most this many journal rows. */
8
+ export const REPOSITORY_EVENTS_PAGE = BUILD_EVENT_PAGE_SIZE
9
+
10
+ export interface RepositoryEventsPage {
11
+ events: RepositoryEvent[]
12
+ cursor: number
13
+ hasMore: boolean
14
+ }
15
+
16
+ /** The connected agent's repository attention watch: one bounded page of the
17
+ * repository journal after `cursor`, filtered by the same predicate as
18
+ * `ab watch --operator`. The read itself is bounded to `(cursor, cursor+256]`
19
+ * and the cursor advances past filtered events, so successive pages scan
20
+ * disjoint ranges. An omitted cursor reads only the repository record and
21
+ * its high-water mark. */
22
+ export async function readRepositoryAttentionPage(
23
+ store: BuildStore,
24
+ repo: string,
25
+ opts: { cursor?: number; waitSeconds?: number; filter?: 'attention' | 'all' } = {},
26
+ ): Promise<RepositoryEventsPage> {
27
+ // A repository no dispatcher has recorded yet has an empty journal, as
28
+ // `ab watch` treats it; one record read, no event rows.
29
+ if ((await store.getRepo(repo)) === null)
30
+ return { events: [], cursor: opts.cursor ?? 0, hasMore: false }
31
+ if (opts.cursor === undefined)
32
+ return { events: [], cursor: await store.getRepoHighWater(repo), hasMore: false }
33
+ const cursor = opts.cursor
34
+ if (store.getRepositoryTail === undefined) {
35
+ const error = 'this store cannot serve bounded repository event reads'
36
+ throw new RegistryError('domain', error, {
37
+ kind: 'refusal',
38
+ error,
39
+ code: 'unsupported-operation',
40
+ })
41
+ }
42
+ const through = cursor + REPOSITORY_EVENTS_PAGE
43
+ let scanned: RepositoryEvent[]
44
+ try {
45
+ scanned = await store.getRepositoryTail(repo, cursor, {
46
+ through,
47
+ ...(opts.waitSeconds ? { waitSeconds: opts.waitSeconds } : {}),
48
+ })
49
+ } catch (error) {
50
+ if (error instanceof CursorTooOldError)
51
+ throw new RegistryError('domain', error.message, {
52
+ kind: 'conflict',
53
+ error: error.message,
54
+ code: 'cursor-too-old',
55
+ })
56
+ throw error
57
+ }
58
+ // An older server that ignores `through` can never widen the page.
59
+ scanned = scanned.filter((event) => event.seq > cursor && event.seq <= through)
60
+ const next = scanned.at(-1)?.seq ?? cursor
61
+ const hasMore = next < (await store.getRepoHighWater(repo))
62
+ return {
63
+ events: opts.filter === 'all' ? scanned : scanned.filter(repositoryNeedsAttention),
64
+ cursor: next,
65
+ hasMore,
66
+ }
67
+ }
@@ -103,6 +103,11 @@ export class FakeTicketSource implements TicketSource {
103
103
  this.tickets.set(ticket.ref.id, cloneTicket(ticket, this.doneState))
104
104
  }
105
105
 
106
+ /** Delete a ticket from the source, as a tracker deletion would. */
107
+ remove(id: string): void {
108
+ this.tickets.delete(id)
109
+ }
110
+
106
111
  async listReady(criteria: {
107
112
  labels?: string[]
108
113
  state?: string
@@ -389,8 +389,9 @@ export interface TicketSource {
389
389
  /**
390
390
  * Dependency-graph nodes for `ids`. The result covers EVERY requested id, in
391
391
  * request order; a missing id comes back `{exists: false, resolved: false,
392
- * blockedBy: []}`. Read at ticket creation and at dispatch time only — both
393
- * are initiation, so §13's "never consulted mid-build" is untouched.
392
+ * blockedBy: []}`. Read at ticket creation, at dispatch time, and by the
393
+ * dispatcher for open ticket waits — one batched call per tick while any
394
+ * wait is open, the one mid-build consultation §13 allows.
394
395
  */
395
396
  dependencyStates(ids: string[]): Promise<DependencyState[]>
396
397
  /**
@@ -5,7 +5,7 @@ import { BUILD_OWNED_CONFIG_PATHS } from '../config/live'
5
5
  import { isPipelineSourceRef, type PipelineSourceMeta } from '../config/pipeline-source'
6
6
  import type { AbEvent } from '../events/catalog'
7
7
  import { defineReducer } from '../kernel/incremental'
8
- import type { Artifact, ArtifactInput } from '../store/types'
8
+ import type { Artifact, ArtifactInput, BuildStore } from '../store/types'
9
9
 
10
10
  export const BUILD_EFFECTIVE_CONFIG_ARTIFACT = 'build-runner-effective-config'
11
11
  export const BUILD_RUNNER_DIAGNOSTIC_ARTIFACT = 'build-runner-diagnostic'
@@ -57,6 +57,35 @@ export function parseEffectiveBuildConfig(artifact: Artifact): Config {
57
57
  return result.data
58
58
  }
59
59
 
60
+ /** The latest deposited pipeline exists but cannot be parsed. */
61
+ export class EffectivePipelineUnreadable extends Error {
62
+ constructor(
63
+ readonly revision: number,
64
+ cause: unknown,
65
+ ) {
66
+ super(cause instanceof Error ? cause.message : String(cause))
67
+ this.name = 'EffectivePipelineUnreadable'
68
+ }
69
+ }
70
+
71
+ /** The dispatcher's first pipeline read: the latest deposited
72
+ * `build-runner-effective-config`, parsed. `null` when none is deposited (the
73
+ * dispatcher then decides with its deployment config); throws when the read
74
+ * fails, or `EffectivePipelineUnreadable` when the deposit does not parse.
75
+ * `ab build status` uses the same definition of readable. */
76
+ export async function readEffectivePipeline(
77
+ store: Pick<BuildStore, 'getArtifact'>,
78
+ slug: string,
79
+ ): Promise<{ config: Config; revision: number } | null> {
80
+ const artifact = await store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
81
+ if (artifact === null) return null
82
+ try {
83
+ return { config: parseEffectiveBuildConfig(artifact), revision: artifact.meta.revision }
84
+ } catch (error) {
85
+ throw new EffectivePipelineUnreadable(artifact.meta.revision, error)
86
+ }
87
+ }
88
+
60
89
  /** Read the artifact metadata's revision + pipeline-source projection. Old
61
90
  * deposits (and externally written ones) carry no `pipelineSource`; status and
62
91
  * the dashboard render that as "unknown (pre-pin)" instead of guessing. */
@@ -1,3 +1,4 @@
1
+ import { leafLandingBase, parseNulChangedPaths, recordHeadPaths } from '../kernel/head-paths'
1
2
  import { StoreWriteTooLargeError } from '../store/remote/errors'
2
3
  import { observeTarget } from '../kernel/target-observation'
3
4
  import { readBuildRange } from '../store/event-reads'
@@ -20,6 +21,7 @@ import type { RuntimeIdentity } from '../events/runtime'
20
21
  import { relaunchTarget } from './execution-relaunch'
21
22
  import { runtimeIdentity } from '../runtime-identity'
22
23
  import { publishExact } from '../kernel/publication'
24
+ import { waitResumeSupersedes } from '../kernel/ticket-wait'
23
25
  import {
24
26
  deferMixedVersion,
25
27
  MixedVersionDeferral,
@@ -461,6 +463,9 @@ export function phaseFailuresReducer(phase: Phase, round: number) {
461
463
  deferral: 'own-build-read',
462
464
  }
463
465
  break
466
+ // A ticket wait's escalation (`wait.entered`) is deliberately not
467
+ // registered: ending a wait is not a failure retry, so its answer
468
+ // re-arms no budget.
464
469
  case 'escalation.raised':
465
470
  acc.raised[event.payload.id] = {
466
471
  phase: event.payload.phase,
@@ -541,7 +546,7 @@ export const setupStreakReducer = defineReducer<
541
546
  finish: (acc) => acc.failures.filter((seq) => seq > acc.boundary).length,
542
547
  })
543
548
 
544
- export const PUBLISHED_BRANCH_HEAD_REDUCER_VERSION = 4
549
+ export const PUBLISHED_BRANCH_HEAD_REDUCER_VERSION = 5
545
550
 
546
551
  /** Latest event-checkpointed branch head that kernel plumbing published;
547
552
  * undefined while the build has none. */
@@ -565,6 +570,13 @@ export const publishedBranchHeadReducer = defineReducer<
565
570
  acc.head = reconcileRewriteHead(event.payload)
566
571
  } else if (event.type === 'reconcile.completed') {
567
572
  acc.head = reconcileHead(event.payload)
573
+ } else if (
574
+ event.type === 'wait.requested' &&
575
+ event.payload.publication?.settlement === 'published'
576
+ ) {
577
+ acc.head = event.payload.publication.sha
578
+ } else if (event.type === 'wait.published') {
579
+ acc.head = event.payload.sha
568
580
  } else if (
569
581
  event.type === 'finalize.step-completed' &&
570
582
  event.payload.ok &&
@@ -589,7 +601,7 @@ export function selectPublishedBranchHead(events: readonly AbEvent[]): string {
589
601
  return head
590
602
  }
591
603
 
592
- export const VERIFY_DIFF_BASE_REDUCER_VERSION = 2
604
+ export const VERIFY_DIFF_BASE_REDUCER_VERSION = 3
593
605
 
594
606
  /**
595
607
  * The durable tree against which a conditional verifier evaluates the
@@ -611,6 +623,11 @@ export const verifyDiffBaseReducer = defineReducer<
611
623
  if (acc.provisioned === undefined) acc.provisioned = event.payload.base.sha
612
624
  } else if (event.type === 'restack.completed') {
613
625
  acc.promoted = event.payload.targetBase
626
+ } else if (event.type === 'restack.advanced') {
627
+ acc.promoted = event.payload.to
628
+ } else if (event.type === 'reconcile.superseded') {
629
+ // An abandoned occurrence's base never promotes.
630
+ delete acc.pendingReconcileBase
614
631
  } else if (event.type === 'reconcile.started') {
615
632
  acc.pendingReconcileBase = event.payload.baseSha
616
633
  } else if (event.type === 'reconcile.completed') {
@@ -638,18 +655,7 @@ export function selectVerifyDiffBase(events: readonly AbEvent[]): string {
638
655
  return base
639
656
  }
640
657
 
641
- /** Parse `git diff --name-only -z`; malformed output fails closed. */
642
- export function parseNulChangedPaths(output: string): string[] {
643
- if (output.length === 0) return []
644
- if (!output.endsWith('\0')) {
645
- throw new Error('git diff --name-only -z returned non-NUL-terminated output')
646
- }
647
- const paths = output.slice(0, -1).split('\0')
648
- if (paths.some((path) => path.length === 0)) {
649
- throw new Error('git diff --name-only -z returned an empty path entry')
650
- }
651
- return paths
652
- }
658
+ export { parseNulChangedPaths }
653
659
 
654
660
  /** Terminal events of loop phases carry `round`; finalize.completed and
655
661
  * reconcile.completed do not (§15.3). Payloads are schema-validated at
@@ -2097,6 +2103,12 @@ export class BuildRunner {
2097
2103
  }
2098
2104
  try {
2099
2105
  await this.assertAutomaticRewriteOwnership()
2106
+ // A reconcile session that waited left its occurrence frozen onto the
2107
+ // old target. Abandon it so the resume replays onto the current one.
2108
+ if (decision.trigger === 'wait-resume' && waitResumeSupersedes(facts.state, facts.log)) {
2109
+ await this.supersedeReconcile(decision)
2110
+ facts = (await readBuildFacts(store, slug)).value
2111
+ }
2100
2112
  if (facts.log.restack.intent)
2101
2113
  await publicationRetryGate(
2102
2114
  { ...this.deps, actor: KERNEL },
@@ -2110,6 +2122,14 @@ export class BuildRunner {
2110
2122
  >
2111
2123
  let id: string
2112
2124
  let targetBase: string
2125
+ if (
2126
+ transaction === undefined &&
2127
+ decision.trigger === 'wait-resume' &&
2128
+ (await readBuildSelector(store, slug, 'publishedBranchHead')) === undefined
2129
+ ) {
2130
+ await this.advanceWaitResume(decision)
2131
+ return
2132
+ }
2113
2133
  if (transaction === undefined) {
2114
2134
  targetBase = await this.refreshReconcileBase(true)
2115
2135
  const branch = facts.lastCreated?.payload.baseBranch
@@ -2190,6 +2210,21 @@ export class BuildRunner {
2190
2210
  throw new Error('recovered automatic replay differs from its frozen publication intent')
2191
2211
  await retainReplay(deps, headSha, transaction.targetBase)
2192
2212
  const intent = { ...transaction, headSha }
2213
+ await recordHeadPaths(
2214
+ {
2215
+ store,
2216
+ slug,
2217
+ exec: this.deps.exec,
2218
+ workspacePath: this.deps.workspacePath,
2219
+ actor: KERNEL,
2220
+ },
2221
+ {
2222
+ source: 'restack',
2223
+ head: headSha,
2224
+ destination: transaction.targetBase,
2225
+ state: facts.state,
2226
+ },
2227
+ )
2193
2228
  if (facts.log.restack.intent === undefined)
2194
2229
  await store.append(slug, {
2195
2230
  actor: KERNEL,
@@ -2255,6 +2290,90 @@ export class BuildRunner {
2255
2290
  }
2256
2291
  }
2257
2292
 
2293
+ /** Abandon the open reconcile occurrence whose session declared a ticket
2294
+ * wait: abort its workspace operation, then record `reconcile.superseded`.
2295
+ * Only the resolver's undeposited, uncommitted resolution is discarded;
2296
+ * every published head and recorded transaction stays. Idempotent up to
2297
+ * the append, so a crash before it repeats harmlessly. */
2298
+ private async supersedeReconcile(
2299
+ decision: Extract<Decision, { kind: 'restack' }>,
2300
+ ): Promise<void> {
2301
+ const { store, slug, workspacePath } = this.deps
2302
+ await this.assertAutomaticRewriteOwnership()
2303
+ const facts = (await readBuildFacts(store, slug)).value
2304
+ const open = facts.log.openReconcile
2305
+ if (open === undefined) throw new Error('no open reconcile occurrence to supersede')
2306
+ const head = await readBuildSelector(store, slug, 'publishedBranchHead')
2307
+ if (head === undefined) throw new Error('a reconcile occurrence has no published head')
2308
+ const git = async (args: string[]) => {
2309
+ const result = await this.deps.exec(['git', ...args], { cwd: workspacePath })
2310
+ if (result.exitCode !== 0)
2311
+ throw new Error(`git ${args.join(' ')} exited ${result.exitCode}: ${result.stderr.trim()}`)
2312
+ }
2313
+ const picking = await this.deps.exec(
2314
+ ['git', 'rev-parse', '-q', '--verify', 'CHERRY_PICK_HEAD'],
2315
+ { cwd: workspacePath },
2316
+ )
2317
+ if (picking.exitCode === 0) await git(['cherry-pick', '--abort'])
2318
+ await git(['reset', '-q', '--hard'])
2319
+ await git(['checkout', '-q', '--detach', head])
2320
+ await store.append(slug, {
2321
+ actor: KERNEL,
2322
+ type: 'reconcile.superseded',
2323
+ payload: {
2324
+ attempt: open.attempt,
2325
+ cycle: decision.cycle,
2326
+ cause: 'wait-resume',
2327
+ ...(open.restackId === undefined ? {} : { restackId: open.restackId }),
2328
+ },
2329
+ })
2330
+ }
2331
+
2332
+ /** A wait-resume restack with nothing published: the local branch has no
2333
+ * commits beyond its contribution base, so it fast-forwards to the fresh
2334
+ * target snapshot and records `restack.advanced`. No remote write; no
2335
+ * conflict is possible. */
2336
+ private async advanceWaitResume(decision: Extract<Decision, { kind: 'restack' }>): Promise<void> {
2337
+ const { store, slug, workspacePath, branch } = this.deps
2338
+ const targetBase = await this.refreshReconcileBase(true)
2339
+ const facts = (await readBuildFacts(store, slug)).value
2340
+ const oldBase = await readBuildSelector(store, slug, 'verifyDiffBase')
2341
+ if (oldBase === undefined) throw new Error('missing contribution base')
2342
+ const git = async (args: string[], allowFailure = false) => {
2343
+ const result = await this.deps.exec(['git', ...args], { cwd: workspacePath })
2344
+ if (result.exitCode !== 0 && !allowFailure)
2345
+ throw new Error(
2346
+ `git ${args.join(' ')} exited ${result.exitCode}: ${result.stderr.trim() || '(no output)'}`,
2347
+ )
2348
+ return result
2349
+ }
2350
+ const local = (await git(['rev-parse', '--verify', `refs/heads/${branch}`])).stdout.trim()
2351
+ if (local !== targetBase) {
2352
+ // Every commit the target already contains is safe to move past; that
2353
+ // also covers a crash after an earlier fast-forward.
2354
+ if ((await git(['merge-base', '--is-ancestor', local, targetBase], true)).exitCode !== 0)
2355
+ throw new Error(
2356
+ `local branch ${branch} has unpublished commits at ${local}; a wait-resume restack replays only published work`,
2357
+ )
2358
+ const status = (await git(['status', '--porcelain', '--untracked-files=no'])).stdout.trim()
2359
+ if (status !== '') throw new Error(`workspace has uncommitted tracked changes:\n${status}`)
2360
+ await this.assertAutomaticRewriteOwnership()
2361
+ await git(['checkout', '-q', '-B', branch, targetBase])
2362
+ }
2363
+ await store.append(slug, {
2364
+ actor: KERNEL,
2365
+ type: 'restack.advanced',
2366
+ payload: {
2367
+ trigger: 'wait-resume',
2368
+ cycle: decision.cycle,
2369
+ observation: facts.log.restack.target!.seq,
2370
+ branch,
2371
+ from: oldBase,
2372
+ to: targetBase,
2373
+ },
2374
+ })
2375
+ }
2376
+
2258
2377
  /** Snapshot the frozen target in a build-private ref without tracking-ref updates. */
2259
2378
  private async refreshReconcileBase(recordAccepted = false): Promise<string> {
2260
2379
  const baseBranch = await readBuildSelector(this.deps.store, this.deps.slug, 'baseBranch')
@@ -2812,8 +2931,21 @@ export class BuildRunner {
2812
2931
  head,
2813
2932
  )
2814
2933
  if (scratchPaths.length > 0) throw phaseScratchRejection(scratchPaths)
2815
- const remote = (await readBuildFacts(this.deps.store, this.deps.slug)).value
2816
- .remoteWorkspace
2934
+ const facts = (await readBuildFacts(this.deps.store, this.deps.slug)).value
2935
+ await recordHeadPaths(
2936
+ { ...this.deps, actor: KERNEL },
2937
+ {
2938
+ source: 'finalize-step',
2939
+ head,
2940
+ destination: await leafLandingBase(
2941
+ this.deps.store,
2942
+ this.deps.slug,
2943
+ facts.log.restack,
2944
+ ),
2945
+ state: facts.state,
2946
+ },
2947
+ )
2948
+ const remote = facts.remoteWorkspace
2817
2949
  if (remote) {
2818
2950
  await this.deps.store.append(this.deps.slug, {
2819
2951
  actor,
@@ -3758,7 +3890,7 @@ export class BuildRunner {
3758
3890
  (event) =>
3759
3891
  spec.isTerminal(event) ||
3760
3892
  isPublicationBoundary(event, spec, session) ||
3761
- (event.type === 'escalation.raised' &&
3893
+ ((event.type === 'escalation.raised' || event.type === 'wait.requested') &&
3762
3894
  event.actor.kind === 'agent' &&
3763
3895
  event.actor.session === session),
3764
3896
  )
@@ -4080,7 +4212,7 @@ export class BuildRunner {
4080
4212
  (event) =>
4081
4213
  spec.isTerminal(event) ||
4082
4214
  isPublicationBoundary(event, spec, session) ||
4083
- (event.type === 'escalation.raised' &&
4215
+ ((event.type === 'escalation.raised' || event.type === 'wait.requested') &&
4084
4216
  event.actor.kind === 'agent' &&
4085
4217
  event.actor.session === session),
4086
4218
  )