@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,6 +1,10 @@
1
+ import { WatchLifetime } from './watch-lifetime'
2
+ import { hostname } from 'node:os'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { OPERATOR_HEARTBEAT_MS, operatorIdentitySchema } from '../store/operator-presence'
1
5
  import { consentReady, consentIdentity, type ConsentReady } from './attention'
2
6
  import { formatReadinessFailure } from '../ports/forge/readiness'
3
- import { readBuildDigests } from '../store/reduced-reads'
7
+ import { readDispatchUpgrade, readBuildDigests } from '../store/reduced-reads'
4
8
  import { readBuildStreamSeed, readRepositoryAttention } from '../store/reduced-reads'
5
9
  import { buildStreamSeedReducer, type BuildStreamSeed } from '../kernel/read-facts'
6
10
  import { historicalBuildState, historicalRepositoryAttention } from './historical-build-state'
@@ -8,7 +12,7 @@ import { readDispatcherLiveness } from './dispatcher-liveness'
8
12
  import { projectDispatcherLiveness } from '../kernel/dispatcher-liveness'
9
13
  import type { RepositoryRecord } from '../store/types'
10
14
  /**
11
- * `ab watch` — the sessionless, read-only streaming half of the status family
15
+ * `ab watch` — the sessionless streaming half of the status family
12
16
  * (§8.2, §7.2). It follows the event logs of one, several, or all active
13
17
  * builds in the repository, plus the repository journal by default with no
14
18
  * slugs, and emits one record per matching event as it lands, carrying the durable
@@ -17,8 +21,8 @@ import type { RepositoryRecord } from '../store/types'
17
21
  *
18
22
  * Like `ab builds` / `ab build status`, the projection is pure and the IO is a
19
23
  * thin shell. The command composes the existing read surface — `listBuilds`,
20
- * `getEvents(since)`, `getRepoEvents(since)`, `getBuild` — and never widens
21
- * `BuildStore`: no event is appended, no lease claimed, no record created. It
24
+ * `getEvents(since)`, `getRepoEvents(since)`, `getBuild`. Only --operator
25
+ * writes mutable advisory liveness; neither form appends events or claims leases. It
22
26
  * deliberately does not reuse `pollingSubscribe` (store/subscribe.ts): that
23
27
  * helper is single-stream, fixed-membership, and build-only, while `watch`
24
28
  * needs dynamic membership (builds created mid-watch join), the repository
@@ -72,10 +76,10 @@ import {
72
76
  type RemotePollRunner,
73
77
  } from './remote-poll'
74
78
  import { buildInRepository, isRemoteStoreRef, normalizeGitRemoteUrl } from './repo-state'
75
- import { withAmbientReadStore, type StoreOpener } from './store-opening'
79
+ import { withAmbientReadStore, type OpenedStoreContext, type StoreOpener } from './store-opening'
76
80
 
77
81
  export const WATCH_USAGE =
78
- 'usage: ab watch [<slug>...] [--repository] [--event <glob>]... [--since <cursor>] ' +
82
+ 'usage: ab watch [<slug>...] [--repository] [--operator] [--event <glob>]... [--since <cursor>] ' +
79
83
  '[--timeout <duration>] [--interval <duration>] [--count <n>] [--json] [--store <ref>]'
80
84
 
81
85
  /** Default poll cadence and watch horizon. */
@@ -124,7 +128,7 @@ export const BUILD_ATTENTION_EVENTS = [
124
128
  * store read. Supplying any glob replaces the attention set entirely.
125
129
  *
126
130
  * The compiler itself lives in `events/globs.ts`, shared with the
127
- * `[orchestrator].wake` configuration validation (AUT-342).
131
+ * explicit session wake validation.
128
132
  */
129
133
  import { compileEventGlobs } from '../events/globs'
130
134
  export { compileEventGlobs } from '../events/globs'
@@ -138,6 +142,7 @@ function matchesBuildFilter(type: EventType, filters: readonly RegExp[]): boolea
138
142
  // ── The cursor ───────────────────────────────────────────────────────────────
139
143
 
140
144
  interface CursorPayload {
145
+ operator?: { id: string; startedAt: string }
141
146
  v: 1
142
147
  /** The resolved store reference this cursor's positions belong to. */
143
148
  store: string
@@ -206,7 +211,7 @@ export function decodeCursor(
206
211
  throw malformed()
207
212
  }
208
213
  if (typeof payload !== 'object' || payload === null) throw malformed()
209
- const { v, store, repo, streams, lostRuns, deliveredAttention } = payload as Record<
214
+ const { v, store, repo, streams, lostRuns, deliveredAttention, operator } = payload as Record<
210
215
  string,
211
216
  unknown
212
217
  >
@@ -222,6 +227,14 @@ export function decodeCursor(
222
227
  deliveredAttention.some((id) => !validAttentionIdentity(id)))
223
228
  )
224
229
  throw malformed()
230
+ if (operator !== undefined) {
231
+ if (
232
+ typeof operator !== 'object' ||
233
+ operator === null ||
234
+ !operatorIdentitySchema.pick({ id: true, startedAt: true }).safeParse(operator).success
235
+ )
236
+ throw malformed()
237
+ }
225
238
  if (v !== 1 || typeof store !== 'string' || typeof repo !== 'string') throw malformed()
226
239
  if (typeof streams !== 'object' || streams === null || Array.isArray(streams)) throw malformed()
227
240
  for (const seq of Object.values(streams)) {
@@ -244,6 +257,7 @@ export function decodeCursor(
244
257
  store,
245
258
  repo,
246
259
  streams: streams as Record<string, number>,
260
+ ...(operator === undefined ? {} : { operator: operator as { id: string; startedAt: string } }),
247
261
  ...(deliveredAttention === undefined
248
262
  ? {}
249
263
  : { deliveredAttention: deliveredAttention as string[] }),
@@ -291,6 +305,8 @@ export function watchSelection(storeRef: string): { intervalMs: number } {
291
305
  export interface WatchRecordState {
292
306
  status: BuildStatus
293
307
  phase: Phase | null
308
+ runningVerifySteps?: string[]
309
+ cancelledVerifySteps?: { step: string; cause: { step: string } }[]
294
310
  round: number
295
311
  openEscalations: { id: string; question: string }[]
296
312
  pr: { number: number; url: string; headSha: string } | null
@@ -364,6 +380,16 @@ function projectState(state: BuildState): WatchRecordState {
364
380
  return {
365
381
  status: state.status,
366
382
  phase: state.phase ?? null,
383
+ ...((state.verify.running?.length ?? 0) > 1
384
+ ? { runningVerifySteps: state.verify.running }
385
+ : {}),
386
+ ...(Object.values(state.verifyStage.cancellations).some((c) => c.seq > state.verify.cycleSince)
387
+ ? {
388
+ cancelledVerifySteps: Object.values(state.verifyStage.cancellations)
389
+ .filter((c) => c.seq > state.verify.cycleSince)
390
+ .map((c) => ({ step: c.step, cause: c.cause })),
391
+ }
392
+ : {}),
367
393
  round: state.round,
368
394
  openEscalations: state.openEscalations.map((escalation) => ({
369
395
  id: escalation.id,
@@ -410,6 +436,10 @@ const SUMMARY_MAX = 200
410
436
  */
411
437
  export function summarizeEvent(event: AbEvent | RepositoryEvent, state: BuildState | null): string {
412
438
  switch (event.type) {
439
+ case 'verify.cancelled':
440
+ return `verify:${event.payload.step} not run: cancelled by verify:${event.payload.cause.step} (attempt ${event.payload.attempt})`
441
+ case 'verify.stage-failed':
442
+ return `verify stage failed (attempt ${event.payload.attempt}): ${event.payload.failed.map((f) => f.step).join(', ')}; ${event.payload.cancelled.map((c) => `${c.step} cancelled by ${c.cause.step}`).join(', ')}`
413
443
  case 'integration.verification-failed':
414
444
  return `verification failed: ${event.payload.steps.join(', ')}; head ${event.payload.head}; parent ${event.payload.parent}; ${event.payload.guidance}`
415
445
  case 'build.janitor-failing':
@@ -523,11 +553,15 @@ export function assertReadScope(
523
553
  // ── The command shell ────────────────────────────────────────────────────────
524
554
 
525
555
  export interface AbWatchOpts {
556
+ operator?: boolean
557
+ operatorIdentity?: { host: string; pid: number; newId: () => string }
558
+ heartbeatDelay?: (ms: number, signal?: AbortSignal) => Promise<void>
526
559
  targetRepo: string
527
560
  /** Raw process environment: --store > AB_STORE > repository default (D8). */
528
561
  env: Record<string, string | undefined>
529
562
  exec: Exec
530
563
  stdout: (line: string) => void
564
+ flushStdout?: () => Promise<void>
531
565
  stderr: (line: string) => void
532
566
  /** Positional build slugs; none means every nonterminal build in the repo. */
533
567
  slugs?: readonly string[]
@@ -550,7 +584,7 @@ export interface AbWatchOpts {
550
584
  now?: () => Date
551
585
  /** Injectable tick-gap sleep so tests drive ticks deterministically. */
552
586
  delay?: (ms: number, signal?: AbortSignal) => Promise<void>
553
- /** Stop signal; the generic sessionless SIGINT handler aborts it. */
587
+ /** Termination signal from SIGINT/TERM/HUP or stdout EPIPE; ordinary completion does not abort it. */
554
588
  signal?: AbortSignal
555
589
  }
556
590
 
@@ -574,8 +608,7 @@ type Stream = BuildStream | RepositoryStream
574
608
  /**
575
609
  * `ab watch` — stream matching build and repository events until a timeout, a
576
610
  * record count, or (only when slugs were named) terminal status ends the
577
- * watch. Read-only: it appends no event, takes no lease, and creates no
578
- * record.
611
+ * watch. Unflagged watches are read-only; --operator adds advisory liveness.
579
612
  */
580
613
  export async function abWatch(opts: AbWatchOpts): Promise<void> {
581
614
  const now = opts.now ?? (() => new Date())
@@ -593,6 +626,20 @@ export async function abWatch(opts: AbWatchOpts): Promise<void> {
593
626
  ? parseDurationMs(opts.interval, { flag: '--interval', usage: WATCH_USAGE })
594
627
  : undefined
595
628
 
629
+ if (
630
+ opts.operator &&
631
+ (slugs.length > 0 ||
632
+ ['AB_BUILD', 'AB_SESSION', 'AB_PHASE', 'AB_ROUND', 'AB_HARVEST', 'AB_REPO'].some((key) =>
633
+ opts.env[key]?.trim(),
634
+ ))
635
+ ) {
636
+ throw new Error(
637
+ `--operator requires a repository-wide watch outside any build or scoped session — ${WATCH_USAGE}`,
638
+ )
639
+ }
640
+ if (opts.count !== undefined && (!Number.isSafeInteger(opts.count) || opts.count <= 0))
641
+ throw new Error(`--count requires a positive integer — ${WATCH_USAGE}`)
642
+
596
643
  // Ambient scope, before any store access.
597
644
  assertReadScope(slugs, { repository: followRepository, env: opts.env })
598
645
 
@@ -603,15 +650,17 @@ export async function abWatch(opts: AbWatchOpts): Promise<void> {
603
650
  usage: WATCH_USAGE,
604
651
  })
605
652
 
653
+ const lifetime = new WatchLifetime(opts.signal, opts.stderr)
606
654
  await withAmbientReadStore(
607
655
  {
656
+ closeDeadline: lifetime.deadline.signal,
608
657
  targetRepo: opts.targetRepo,
609
658
  env: opts.env,
610
659
  exec: opts.exec,
611
660
  ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
612
661
  ...(opts.openStore !== undefined ? { openStore: opts.openStore } : {}),
613
662
  },
614
- async (context) => {
663
+ lifetime.limitCallback(async (context: OpenedStoreContext) => {
615
664
  const { store, repo, storeRef, checkout } = context
616
665
  const { exec } = opts
617
666
  const interval = intervalMs ?? watchSelection(storeRef).intervalMs
@@ -639,145 +688,109 @@ export async function abWatch(opts: AbWatchOpts): Promise<void> {
639
688
  const resumedCursor = opts.since
640
689
  ? decodeCursor(opts.since, { store: storeRef, repo })
641
690
  : undefined
642
- const deliveredAttention = new Set(resumedCursor?.deliveredAttention ?? [])
643
- let repositoryAttention = new RepositoryAttention()
644
- let attentionInitialized = false
645
- let livenessEvents: RepositoryEvent[] = []
646
- const observedOwners = new Map<string, RepositoryRecord>()
647
- const streams = new Map<string, Stream>()
648
- // Every stream's position — matching or not, delivered or baselined —
649
- // lives here, so a resume never rescans or redelivers a filtered event.
650
- const positions: Record<string, number> = { ...sinceStreams }
651
- let emitted = 0
652
- let countCursor: string | undefined
653
- let stop = false
654
- // On the remote path this is the shared long-poll runner (the held
655
- // reads, their cancellation, and the gap sleeps it owns); on the local
656
- // path it stays undefined and a stop trips the `stop` flag alone.
657
- let runner: RemotePollRunner | undefined
658
- const requestStop = (): void => {
659
- stop = true
660
- runner?.requestStop()
661
- }
662
-
663
- const encodeCurrent = (): string =>
664
- encodeCursor({
665
- v: 1,
666
- store: storeRef,
667
- repo,
668
- streams: { ...positions },
669
- lostRuns: [...lostRuns],
670
- deliveredAttention: [...deliveredAttention],
671
- })
672
-
673
- /** One record, flushed the moment it is projected. `cursor` is the watch
674
- * position AFTER this event. */
675
- const emit = (event: AbEvent | RepositoryEvent, state: BuildState | null): void => {
676
- const cursor = encodeCurrent()
677
- if (opts.json === true) {
678
- opts.stdout(JSON.stringify(projectRecord(event, state, cursor)))
679
- } else {
680
- opts.stdout(renderWatchLine(event, state))
681
- }
682
- emitted += 1
683
- if (opts.count !== undefined && emitted >= opts.count) {
684
- // Events read but not delivered because the count tripped stay
685
- // unprocessed: the next run resumes from THIS record's cursor.
686
- countCursor = cursor
687
- requestStop()
688
- }
689
- }
690
-
691
- const emitObservation = (
692
- observation: MergeDecision | PersistenceObservation | ConsentReady,
693
- state: BuildState | null,
694
- scope: { build: string } | { repo: string },
695
- identity: string,
696
- ): void => {
697
- if (stop || deliveredAttention.has(identity)) return
698
- deliveredAttention.add(identity)
699
- const cursor = encodeCurrent()
700
- opts.stdout(
701
- opts.json
702
- ? JSON.stringify(projectAttentionRecord(observation, state, cursor, scope))
703
- : renderAttentionLine(observation, 'build' in scope ? scope.build : '(repository)'),
704
- )
705
- emitted += 1
706
- if (opts.count !== undefined && emitted >= opts.count) {
707
- countCursor = cursor
708
- requestStop()
691
+ const operator = opts.operator
692
+ ? operatorIdentitySchema.parse({
693
+ id: resumedCursor?.operator?.id ?? (opts.operatorIdentity?.newId ?? randomUUID)(),
694
+ startedAt: resumedCursor?.operator?.startedAt ?? now().toISOString(),
695
+ host: opts.operatorIdentity?.host ?? hostname(),
696
+ pid: opts.operatorIdentity?.pid ?? process.pid,
697
+ })
698
+ : undefined
699
+ const heartbeatStop = new AbortController()
700
+ let heartbeatTask: Promise<void> | undefined
701
+ if (operator) {
702
+ try {
703
+ await lifetime.register(store, repo, operator)
704
+ } catch (error) {
705
+ if (!lifetime.terminated) throw error
709
706
  }
707
+ heartbeatTask = (async () => {
708
+ let reported = false
709
+ let nextHeartbeatAt = now().getTime() + OPERATOR_HEARTBEAT_MS
710
+ while (!heartbeatStop.signal.aborted && !lifetime.terminated) {
711
+ await (opts.heartbeatDelay ?? defaultDelay)(
712
+ Math.max(0, nextHeartbeatAt - now().getTime()),
713
+ AbortSignal.any([heartbeatStop.signal, lifetime.writes.signal]),
714
+ )
715
+ if (heartbeatStop.signal.aborted || lifetime.terminated) break
716
+ nextHeartbeatAt = now().getTime() + OPERATOR_HEARTBEAT_MS
717
+ try {
718
+ await lifetime.renew()
719
+ reported = false
720
+ } catch (error) {
721
+ if (!reported && !lifetime.terminated)
722
+ opts.stderr(
723
+ `ab watch: operator heartbeat failed (${String(error)}); retrying at next heartbeat`,
724
+ )
725
+ reported = true
726
+ }
727
+ }
728
+ })()
710
729
  }
711
- const checkConsent = (stream: BuildStream): void => {
712
- if (filters.length || stop) return
713
- const observation = consentReady(stream.seed, now())
714
- if (observation)
715
- emitObservation(
716
- observation,
717
- buildReducer.finish(stream.seed.build),
718
- { build: stream.slug },
719
- consentIdentity(stream.slug, observation.position),
720
- )
721
- }
722
- const checkPersistence = (): void => {
723
- if (filters.length || !attentionInitialized || stop) return
724
- for (const { identity, observation } of repositoryAttention.pending(now())) {
725
- emitObservation(observation, null, { repo }, identity)
726
- if (stop) return
730
+ try {
731
+ const deliveredAttention = new Set(resumedCursor?.deliveredAttention ?? [])
732
+ let repositoryAttention = new RepositoryAttention()
733
+ let attentionInitialized = false
734
+ let livenessEvents: RepositoryEvent[] = []
735
+ const observedOwners = new Map<string, RepositoryRecord>()
736
+ const streams = new Map<string, Stream>()
737
+ // Every stream's position — matching or not, delivered or baselined —
738
+ // lives here, so a resume never rescans or redelivers a filtered event.
739
+ const positions: Record<string, number> = { ...sinceStreams }
740
+ let emitted = 0
741
+ let countCursor: string | undefined
742
+ let stop = false
743
+ // On the remote path this is the shared long-poll runner (the held
744
+ // reads, their cancellation, and the gap sleeps it owns); on the local
745
+ // path it stays undefined and a stop trips the `stop` flag alone.
746
+ let runner: RemotePollRunner | undefined
747
+ const requestStop = (): void => {
748
+ stop = true
749
+ runner?.requestStop()
727
750
  }
728
- }
729
- const baselineMerge = (slug: string, seed: BuildStreamSeed): void => {
730
- for (const pr of seed.mergeAttentionPrs) deliveredAttention.add(mergeIdentity(slug, pr))
731
- }
732
751
 
733
- const checkLiveness = async (): Promise<void> => {
734
- if (!followRepository || stop) return
735
- if ((await store.getRepo(repo)) === null) return
736
- livenessEvents = (await readDispatcherLiveness(store, repo, now())).events
737
- // Sample metadata after the journal. Recheck both immediately before
738
- // reporting: a failed read is infrastructure, never evidence of death.
739
- const record = await store.getRepo(repo)
740
- if (record?.lease) observedOwners.set(record.lease.holder, record)
741
- for (const [id, owner] of observedOwners) {
742
- if (
743
- stop ||
744
- lostRuns.has(id) ||
745
- !owner.lease ||
746
- Date.parse(owner.lease.expiresAt) > now().getTime()
747
- )
748
- continue
749
- livenessEvents = (await readDispatcherLiveness(store, repo, now())).events
750
- const current = await store.getRepo(repo)
751
- if (current?.lease?.holder === id) {
752
- observedOwners.set(id, current)
753
- if (Date.parse(current.lease.expiresAt) > now().getTime()) continue
752
+ const encodeCurrent = (): string =>
753
+ encodeCursor({
754
+ v: 1,
755
+ store: storeRef,
756
+ repo,
757
+ streams: { ...positions },
758
+ ...(operator ? { operator: { id: operator.id, startedAt: operator.startedAt } } : {}),
759
+ lostRuns: [...lostRuns],
760
+ deliveredAttention: [...deliveredAttention],
761
+ })
762
+
763
+ /** One record, flushed the moment it is projected. `cursor` is the watch
764
+ * position AFTER this event. */
765
+ const emit = (event: AbEvent | RepositoryEvent, state: BuildState | null): void => {
766
+ const cursor = encodeCurrent()
767
+ if (opts.json === true) {
768
+ opts.stdout(JSON.stringify(projectRecord(event, state, cursor)))
769
+ } else {
770
+ opts.stdout(renderWatchLine(event, state))
754
771
  }
755
- const evidence = projectDispatcherLiveness(
756
- current?.lease?.holder === id ? current : owner,
757
- livenessEvents,
758
- now(),
759
- )
760
- if (
761
- livenessEvents.some((e) => e.type === 'dispatcher.run-stopped' && e.payload.run === id)
762
- ) {
763
- observedOwners.delete(id)
764
- continue
772
+ emitted += 1
773
+ if (opts.count !== undefined && emitted >= opts.count) {
774
+ // Events read but not delivered because the count tripped stay
775
+ // unprocessed: the next run resumes from THIS record's cursor.
776
+ countCursor = cursor
777
+ requestStop()
765
778
  }
766
- if (!(filters.length ? filters.some((f) => f.test('dispatcher.lost')) : true)) continue
767
- if (stop) return
768
- lostRuns.add(id)
779
+ }
780
+
781
+ const emitObservation = (
782
+ observation: MergeDecision | PersistenceObservation | ConsentReady,
783
+ state: BuildState | null,
784
+ scope: { build: string } | { repo: string },
785
+ identity: string,
786
+ ): void => {
787
+ if (stop || deliveredAttention.has(identity)) return
788
+ deliveredAttention.add(identity)
769
789
  const cursor = encodeCurrent()
770
- const observation = {
771
- ...evidence.expiredHolder,
772
- type: 'dispatcher.lost',
773
- run: id,
774
- observedAt: now().toISOString(),
775
- leaseExpiresAt: (current?.lease?.holder === id ? current : owner).lease!.expiresAt,
776
- }
777
790
  opts.stdout(
778
791
  opts.json
779
- ? JSON.stringify({ repo, build: null, state: null, observation, cursor })
780
- : `dispatcher.lost ${id} — lease expired ${observation.leaseExpiresAt}`,
792
+ ? JSON.stringify(projectAttentionRecord(observation, state, cursor, scope))
793
+ : renderAttentionLine(observation, 'build' in scope ? scope.build : '(repository)'),
781
794
  )
782
795
  emitted += 1
783
796
  if (opts.count !== undefined && emitted >= opts.count) {
@@ -785,421 +798,531 @@ export async function abWatch(opts: AbWatchOpts): Promise<void> {
785
798
  requestStop()
786
799
  }
787
800
  }
788
- }
789
-
790
- /** Record one event. `prefix` is the event prefix ENDING at `event` —
791
- * the record's state is the reduction after THIS event, never a
792
- * reduction over events that landed after it. The poll path passes the
793
- * stream's just-extended array; the resume path replays the backlog
794
- * into a scratch prefix so a resumed record never leaks state from
795
- * events that landed after it. */
796
- const processBuildEvent = (stream: BuildStream, event: AbEvent): void => {
797
- if (stop) return
798
- stream.lastSeq = event.seq
799
- positions[stream.slug] = event.seq
800
- stream.seed = buildStreamSeedReducer.advance(stream.seed, [event])
801
- const state = buildReducer.finish(stream.seed.build)
802
- stream.status = state.status
803
- if (
804
- matchesBuildFilter(event.type, filters) ||
805
- (!filters.length && event.type === 'restack.replayed' && event.payload.conflicted)
806
- )
807
- emit(event, state)
808
- checkConsent(stream)
809
- if (!filters.length && !stop) {
810
- const observation = mergeDecisionFromFacts(state, stream.seed.deferral, now())
801
+ const checkConsent = (stream: BuildStream): void => {
802
+ if (filters.length || stop) return
803
+ const observation = consentReady(stream.seed, now())
811
804
  if (observation)
812
805
  emitObservation(
813
806
  observation,
814
- state,
807
+ buildReducer.finish(stream.seed.build),
815
808
  { build: stream.slug },
816
- mergeIdentity(stream.slug, observation.pr.number),
809
+ consentIdentity(stream.slug, observation.position),
817
810
  )
818
811
  }
819
- }
820
-
821
- const processRepositoryEvent = (stream: RepositoryStream, event: RepositoryEvent): void => {
822
- if (stop) return
823
- stream.lastSeq = event.seq
824
- positions[REPO_STREAM_KEY] = event.seq
825
- repositoryAttention.fold(event)
826
- if (
827
- filters.length
828
- ? filters.some((regex) => regex.test(event.type))
829
- : repositoryNeedsAttention(event)
830
- )
831
- emit(event, null)
832
- }
833
-
834
- /**
835
- * Register a build stream over the full event prefix. `resumeSeq` (a
836
- * cursor position) additionally emits every matching event after it —
837
- * the backlog that landed while no watch was running. A baseline (the
838
- * default) replays nothing: the position starts at the current maximum.
839
- */
840
- const trackBuild = async (slug: string, resumeSeq?: number): Promise<boolean> => {
841
- if (streams.has(slug)) return true
842
- const record = await store.getBuild(slug)
843
- if (record === null) return false
844
- const current = await readBuildStreamSeed(store, slug)
845
- const seed =
846
- resumeSeq === undefined
847
- ? current.value
848
- : await historicalBuildState(store, slug, resumeSeq, current)
849
- const stream: BuildStream = {
850
- kind: 'build',
851
- slug,
852
- named: slugs.includes(slug),
853
- seed,
854
- lastSeq: resumeSeq ?? current.cursor,
855
- status: buildReducer.finish(current.value.build).status,
812
+ const checkPersistence = (): void => {
813
+ if (filters.length || !attentionInitialized || stop) return
814
+ for (const { identity, observation } of repositoryAttention.pending(now())) {
815
+ emitObservation(observation, null, { repo }, identity)
816
+ if (stop) return
817
+ }
856
818
  }
857
- streams.set(slug, stream)
858
- positions[slug] = stream.lastSeq
859
- if (resumeSeq === undefined || resumedCursor?.deliveredAttention === undefined)
860
- baselineMerge(slug, seed)
861
- if (resumeSeq !== undefined) {
862
- for (const event of await store.getEvents(slug, resumeSeq)) {
863
- processBuildEvent(stream, event)
864
- if (stop) break
819
+ const baselineMerge = (slug: string, seed: BuildStreamSeed): void => {
820
+ for (const pr of seed.mergeAttentionPrs) deliveredAttention.add(mergeIdentity(slug, pr))
821
+ }
822
+
823
+ const checkLiveness = async (): Promise<void> => {
824
+ if (!followRepository || stop) return
825
+ if ((await store.getRepo(repo)) === null) return
826
+ livenessEvents = (await readDispatcherLiveness(store, repo, now())).events
827
+ // Sample metadata after the journal. Recheck both immediately before
828
+ // reporting: a failed read is infrastructure, never evidence of death.
829
+ const record = await store.getRepo(repo)
830
+ if (record?.lease) observedOwners.set(record.lease.holder, record)
831
+ let upgrade: Awaited<ReturnType<typeof readDispatchUpgrade>> | undefined
832
+ for (const [id, owner] of observedOwners) {
833
+ if (
834
+ stop ||
835
+ lostRuns.has(id) ||
836
+ !owner.lease ||
837
+ Date.parse(owner.lease.expiresAt) > now().getTime()
838
+ )
839
+ continue
840
+ livenessEvents = (await readDispatcherLiveness(store, repo, now())).events
841
+ const current = await store.getRepo(repo)
842
+ if (current?.lease?.holder === id) {
843
+ observedOwners.set(id, current)
844
+ if (Date.parse(current.lease.expiresAt) > now().getTime()) continue
845
+ }
846
+ const evidence = projectDispatcherLiveness(
847
+ current?.lease?.holder === id ? current : owner,
848
+ livenessEvents,
849
+ now(),
850
+ )
851
+ if (
852
+ livenessEvents.some(
853
+ (e) => e.type === 'dispatcher.run-stopped' && e.payload.run === id,
854
+ )
855
+ ) {
856
+ observedOwners.delete(id)
857
+ continue
858
+ }
859
+ // Only a validated takeover proves transfer; intent or release alone
860
+ // must still report a predecessor whose successor never arrives.
861
+ upgrade ??= await readDispatchUpgrade(store, repo)
862
+ if (upgrade.value.runs[id]?.takeover) {
863
+ observedOwners.delete(id)
864
+ continue
865
+ }
866
+ if (!(filters.length ? filters.some((f) => f.test('dispatcher.lost')) : true)) continue
867
+ if (stop) return
868
+ lostRuns.add(id)
869
+ const cursor = encodeCurrent()
870
+ const observation = {
871
+ ...evidence.expiredHolder,
872
+ type: 'dispatcher.lost',
873
+ run: id,
874
+ observedAt: now().toISOString(),
875
+ leaseExpiresAt: (current?.lease?.holder === id ? current : owner).lease!.expiresAt,
876
+ }
877
+ opts.stdout(
878
+ opts.json
879
+ ? JSON.stringify({ repo, build: null, state: null, observation, cursor })
880
+ : `dispatcher.lost ${id} — lease expired ${observation.leaseExpiresAt}`,
881
+ )
882
+ emitted += 1
883
+ if (opts.count !== undefined && emitted >= opts.count) {
884
+ countCursor = cursor
885
+ requestStop()
886
+ }
865
887
  }
866
888
  }
867
- checkConsent(stream)
868
- return true
869
- }
870
889
 
871
- /** Builds discovery read in full and found terminal; never re-read. */
872
- const retired = new Set<string>()
873
-
874
- /**
875
- * No-slug membership: every nonterminal build of this repository joins
876
- * the watch, baselined at its current maximum so no history replays. A
877
- * build discovered while nonterminal stays tracked even after it turns
878
- * terminal. Cursor-resumed and named streams are never re-baselined.
879
- *
880
- * Throws on a failed read — never swallows it: the poll loop's tick
881
- * catches and reports the failure once on stderr, and the initial scan
882
- * turns it into the friendly startup error. Streams discovered before
883
- * the throw stay tracked, so the retry neither duplicates nor skips.
884
- */
885
- const discoverBuilds = async (): Promise<void> => {
886
- const digests = await readBuildDigests(store, repo)
887
- for (const record of (await store.listBuilds()).filter(mine)) {
888
- if (streams.has(record.slug) || retired.has(record.slug)) continue
889
- const digest = digests.get(record.slug)
890
- if (digest !== undefined && digest.terminal !== undefined) continue
891
- const current = await readBuildStreamSeed(store, record.slug)
892
- const status = buildReducer.finish(current.value.build).status
893
- if (!NONTERMINAL_STATUSES.includes(status)) {
894
- // Terminal is permanent (reduceBuild never clears it): a legacy
895
- // record the digest cannot retire is read once, not every pass.
896
- retired.add(record.slug)
897
- continue
890
+ /** Record one event. `prefix` is the event prefix ENDING at `event` —
891
+ * the record's state is the reduction after THIS event, never a
892
+ * reduction over events that landed after it. The poll path passes the
893
+ * stream's just-extended array; the resume path replays the backlog
894
+ * into a scratch prefix so a resumed record never leaks state from
895
+ * events that landed after it. */
896
+ const processBuildEvent = (stream: BuildStream, event: AbEvent): void => {
897
+ if (stop) return
898
+ stream.lastSeq = event.seq
899
+ positions[stream.slug] = event.seq
900
+ stream.seed = buildStreamSeedReducer.advance(stream.seed, [event])
901
+ const state = buildReducer.finish(stream.seed.build)
902
+ stream.status = state.status
903
+ if (
904
+ matchesBuildFilter(event.type, filters) ||
905
+ (!filters.length && event.type === 'restack.replayed' && event.payload.conflicted)
906
+ )
907
+ emit(event, state)
908
+ checkConsent(stream)
909
+ if (!filters.length && !stop) {
910
+ const observation = mergeDecisionFromFacts(state, stream.seed.deferral, now())
911
+ if (observation)
912
+ emitObservation(
913
+ observation,
914
+ state,
915
+ { build: stream.slug },
916
+ mergeIdentity(stream.slug, observation.pr.number),
917
+ )
898
918
  }
919
+ }
920
+
921
+ const processRepositoryEvent = (stream: RepositoryStream, event: RepositoryEvent): void => {
922
+ if (stop) return
923
+ stream.lastSeq = event.seq
924
+ positions[REPO_STREAM_KEY] = event.seq
925
+ repositoryAttention.fold(event)
926
+ if (
927
+ filters.length
928
+ ? filters.some((regex) => regex.test(event.type))
929
+ : repositoryNeedsAttention(event)
930
+ )
931
+ emit(event, null)
932
+ }
933
+
934
+ /**
935
+ * Register a build stream over the full event prefix. `resumeSeq` (a
936
+ * cursor position) additionally emits every matching event after it —
937
+ * the backlog that landed while no watch was running. A baseline (the
938
+ * default) replays nothing: the position starts at the current maximum.
939
+ */
940
+ const trackBuild = async (slug: string, resumeSeq?: number): Promise<boolean> => {
941
+ if (streams.has(slug)) return true
942
+ const record = await store.getBuild(slug)
943
+ if (record === null) return false
944
+ const current = await readBuildStreamSeed(store, slug)
945
+ const seed =
946
+ resumeSeq === undefined
947
+ ? current.value
948
+ : await historicalBuildState(store, slug, resumeSeq, current)
899
949
  const stream: BuildStream = {
900
950
  kind: 'build',
901
- slug: record.slug,
902
- named: false,
903
- seed: current.value,
904
- lastSeq: current.cursor,
905
- status,
951
+ slug,
952
+ named: slugs.includes(slug),
953
+ seed,
954
+ lastSeq: resumeSeq ?? current.cursor,
955
+ status: buildReducer.finish(current.value.build).status,
906
956
  }
907
- streams.set(record.slug, stream)
908
- baselineMerge(record.slug, current.value)
909
- positions[record.slug] = stream.lastSeq
910
- checkConsent(stream)
911
- if (stop) break
912
- }
913
- }
914
-
915
- const trackRepository = async (): Promise<boolean> => {
916
- const resumeSeq = sinceStreams[REPO_STREAM_KEY]
917
- const stream: RepositoryStream = { kind: 'repo', lastSeq: resumeSeq ?? 0 }
918
- streams.set(REPO_STREAM_KEY, stream)
919
- positions[REPO_STREAM_KEY] = stream.lastSeq
920
- try {
921
- if ((await store.getRepo(repo)) !== null) {
922
- const current = await readRepositoryAttention(store, repo)
923
- const baseline = resumeSeq ?? current.cursor
924
- const seed =
925
- resumeSeq === undefined
926
- ? current.value
927
- : await historicalRepositoryAttention(store, repo, resumeSeq, current)
928
- repositoryAttention = new RepositoryAttention(seed)
929
- attentionInitialized = true
930
- stream.lastSeq = baseline
931
- positions[REPO_STREAM_KEY] = baseline
932
- if (resumeSeq !== undefined) {
933
- for (const event of await store.getRepoEvents(repo, baseline)) {
934
- if (stop) break
935
- processRepositoryEvent(stream, event)
936
- }
957
+ streams.set(slug, stream)
958
+ positions[slug] = stream.lastSeq
959
+ if (resumeSeq === undefined || resumedCursor?.deliveredAttention === undefined)
960
+ baselineMerge(slug, seed)
961
+ if (resumeSeq !== undefined) {
962
+ for (const event of await store.getEvents(slug, resumeSeq)) {
963
+ processBuildEvent(stream, event)
964
+ if (stop) break
937
965
  }
938
- if (!stop) checkPersistence()
939
- } else attentionInitialized = true
966
+ }
967
+ checkConsent(stream)
940
968
  return true
941
- } catch {
942
- return false
943
969
  }
944
- }
945
970
 
946
- const pollBuild = async (
947
- stream: BuildStream,
948
- readOpts?: RemotePollReadOpts,
949
- ): Promise<boolean> => {
950
- const fresh = await store.getEvents(stream.slug, stream.lastSeq, readOpts)
951
- for (const event of fresh) {
952
- if (stop) break
953
- processBuildEvent(stream, event)
954
- if (stop) break
955
- }
956
- if (fresh.length > 0 && !stop) {
957
- stream.status = buildReducer.finish(stream.seed.build).status
971
+ /** Builds discovery read in full and found terminal; never re-read. */
972
+ const retired = new Set<string>()
973
+
974
+ /**
975
+ * No-slug membership: every nonterminal build of this repository joins
976
+ * the watch, baselined at its current maximum so no history replays. A
977
+ * build discovered while nonterminal stays tracked even after it turns
978
+ * terminal. Cursor-resumed and named streams are never re-baselined.
979
+ *
980
+ * Throws on a failed read — never swallows it: the poll loop's tick
981
+ * catches and reports the failure once on stderr, and the initial scan
982
+ * turns it into the friendly startup error. Streams discovered before
983
+ * the throw stay tracked, so the retry neither duplicates nor skips.
984
+ */
985
+ const discoverBuilds = async (): Promise<void> => {
986
+ const digests = await readBuildDigests(store, repo)
987
+ for (const record of (await store.listBuilds()).filter(mine)) {
988
+ if (streams.has(record.slug) || retired.has(record.slug)) continue
989
+ const digest = digests.get(record.slug)
990
+ if (digest !== undefined && digest.terminal !== undefined) continue
991
+ const current = await readBuildStreamSeed(store, record.slug)
992
+ const status = buildReducer.finish(current.value.build).status
993
+ if (!NONTERMINAL_STATUSES.includes(status)) {
994
+ // Terminal is permanent (reduceBuild never clears it): a legacy
995
+ // record the digest cannot retire is read once, not every pass.
996
+ retired.add(record.slug)
997
+ continue
998
+ }
999
+ const stream: BuildStream = {
1000
+ kind: 'build',
1001
+ slug: record.slug,
1002
+ named: false,
1003
+ seed: current.value,
1004
+ lastSeq: current.cursor,
1005
+ status,
1006
+ }
1007
+ streams.set(record.slug, stream)
1008
+ baselineMerge(record.slug, current.value)
1009
+ positions[record.slug] = stream.lastSeq
1010
+ checkConsent(stream)
1011
+ if (stop) break
1012
+ }
958
1013
  }
959
- return true
960
- }
961
1014
 
962
- let repositoryQueue = Promise.resolve()
963
- let repositoryInitialization: Promise<void> | undefined
964
- const pollRepository = async (
965
- stream: RepositoryStream,
966
- readOpts?: RemotePollReadOpts,
967
- ): Promise<boolean> => {
968
- // A repository row may be created mid-watch by the first dispatch.
969
- if ((await store.getRepo(repo)) === null) return true
970
- if (!attentionInitialized) {
971
- repositoryInitialization ??= (async () => {
972
- const current = await readRepositoryAttention(store, repo)
973
- const resumeSeq = sinceStreams[REPO_STREAM_KEY]
974
- const baseline = resumeSeq ?? current.cursor
975
- const seed =
976
- resumeSeq === undefined
977
- ? current.value
978
- : await historicalRepositoryAttention(store, repo, resumeSeq, current)
979
- repositoryAttention = new RepositoryAttention(seed)
980
- stream.lastSeq = baseline
981
- positions[REPO_STREAM_KEY] = baseline
982
- attentionInitialized = true
983
- })()
1015
+ const trackRepository = async (): Promise<boolean> => {
1016
+ const resumeSeq = sinceStreams[REPO_STREAM_KEY]
1017
+ const stream: RepositoryStream = { kind: 'repo', lastSeq: resumeSeq ?? 0 }
1018
+ streams.set(REPO_STREAM_KEY, stream)
1019
+ positions[REPO_STREAM_KEY] = stream.lastSeq
984
1020
  try {
985
- await repositoryInitialization
986
- } catch (error) {
987
- repositoryInitialization = undefined
988
- throw error
1021
+ if ((await store.getRepo(repo)) !== null) {
1022
+ const current = await readRepositoryAttention(store, repo)
1023
+ const baseline = resumeSeq ?? current.cursor
1024
+ const seed =
1025
+ resumeSeq === undefined
1026
+ ? current.value
1027
+ : await historicalRepositoryAttention(store, repo, resumeSeq, current)
1028
+ repositoryAttention = new RepositoryAttention(seed)
1029
+ attentionInitialized = true
1030
+ stream.lastSeq = baseline
1031
+ positions[REPO_STREAM_KEY] = baseline
1032
+ if (resumeSeq !== undefined) {
1033
+ for (const event of await store.getRepoEvents(repo, baseline)) {
1034
+ if (stop) break
1035
+ processRepositoryEvent(stream, event)
1036
+ }
1037
+ }
1038
+ if (!stop) checkPersistence()
1039
+ } else attentionInitialized = true
1040
+ return true
1041
+ } catch {
1042
+ return false
989
1043
  }
990
1044
  }
991
- const fresh = await store.getRepoEvents(repo, stream.lastSeq, readOpts)
992
- const apply = repositoryQueue.then(() => {
1045
+
1046
+ const pollBuild = async (
1047
+ stream: BuildStream,
1048
+ readOpts?: RemotePollReadOpts,
1049
+ ): Promise<boolean> => {
1050
+ const fresh = await store.getEvents(stream.slug, stream.lastSeq, readOpts)
993
1051
  for (const event of fresh) {
994
1052
  if (stop) break
995
- if (event.seq <= stream.lastSeq) continue
996
- processRepositoryEvent(stream, event)
1053
+ processBuildEvent(stream, event)
1054
+ if (stop) break
997
1055
  }
998
- if (!stop) checkPersistence()
999
- })
1000
- repositoryQueue = apply.catch(() => {})
1001
- await apply
1002
- return true
1003
- }
1056
+ if (fresh.length > 0 && !stop) {
1057
+ stream.status = buildReducer.finish(stream.seed.build).status
1058
+ }
1059
+ return true
1060
+ }
1004
1061
 
1005
- const namedAllTerminal = (): boolean => {
1006
- if (slugs.length === 0) return false
1007
- for (const slug of slugs) {
1008
- const stream = streams.get(slug)
1009
- if (stream === undefined || stream.kind !== 'build') return false
1010
- if (!TERMINAL_STATUSES.includes(stream.status)) return false
1062
+ let repositoryQueue = Promise.resolve()
1063
+ let repositoryInitialization: Promise<void> | undefined
1064
+ const pollRepository = async (
1065
+ stream: RepositoryStream,
1066
+ readOpts?: RemotePollReadOpts,
1067
+ ): Promise<boolean> => {
1068
+ // A repository row may be created mid-watch by the first dispatch.
1069
+ if ((await store.getRepo(repo)) === null) return true
1070
+ if (!attentionInitialized) {
1071
+ repositoryInitialization ??= (async () => {
1072
+ const current = await readRepositoryAttention(store, repo)
1073
+ const resumeSeq = sinceStreams[REPO_STREAM_KEY]
1074
+ const baseline = resumeSeq ?? current.cursor
1075
+ const seed =
1076
+ resumeSeq === undefined
1077
+ ? current.value
1078
+ : await historicalRepositoryAttention(store, repo, resumeSeq, current)
1079
+ repositoryAttention = new RepositoryAttention(seed)
1080
+ stream.lastSeq = baseline
1081
+ positions[REPO_STREAM_KEY] = baseline
1082
+ attentionInitialized = true
1083
+ })()
1084
+ try {
1085
+ await repositoryInitialization
1086
+ } catch (error) {
1087
+ repositoryInitialization = undefined
1088
+ throw error
1089
+ }
1090
+ }
1091
+ const fresh = await store.getRepoEvents(repo, stream.lastSeq, readOpts)
1092
+ const apply = repositoryQueue.then(() => {
1093
+ for (const event of fresh) {
1094
+ if (stop) break
1095
+ if (event.seq <= stream.lastSeq) continue
1096
+ processRepositoryEvent(stream, event)
1097
+ }
1098
+ if (!stop) checkPersistence()
1099
+ })
1100
+ repositoryQueue = apply.catch(() => {})
1101
+ await apply
1102
+ return true
1011
1103
  }
1012
- return true
1013
- }
1014
1104
 
1015
- // One streak for the whole local loop — the same lifetime the shared
1016
- // reported flag had before per-source streaks: a persistent read
1017
- // failure is reported once, and a fully-successful cycle re-arms it.
1018
- const tickStreak = makeFailureStreak('watch', opts.stderr)
1105
+ const namedAllTerminal = (): boolean => {
1106
+ if (slugs.length === 0) return false
1107
+ for (const slug of slugs) {
1108
+ const stream = streams.get(slug)
1109
+ if (stream === undefined || stream.kind !== 'build') return false
1110
+ if (!TERMINAL_STATUSES.includes(stream.status)) return false
1111
+ }
1112
+ return true
1113
+ }
1019
1114
 
1020
- const tick = async (): Promise<void> => {
1021
- let allReadsOk = true
1022
- if (slugs.length === 0) {
1023
- try {
1024
- await discoverBuilds()
1025
- } catch (error) {
1026
- allReadsOk = false
1027
- tickStreak.onFailure(error)
1115
+ // One streak for the whole local loop — the same lifetime the shared
1116
+ // reported flag had before per-source streaks: a persistent read
1117
+ // failure is reported once, and a fully-successful cycle re-arms it.
1118
+ const tickStreak = makeFailureStreak('watch', opts.stderr)
1119
+
1120
+ const tick = async (): Promise<void> => {
1121
+ let allReadsOk = true
1122
+ if (slugs.length === 0) {
1123
+ try {
1124
+ await discoverBuilds()
1125
+ } catch (error) {
1126
+ allReadsOk = false
1127
+ tickStreak.onFailure(error)
1128
+ }
1129
+ }
1130
+ for (const stream of [...streams.values()]) {
1131
+ if (stop) return
1132
+ try {
1133
+ if (stream.kind === 'build') await pollBuild(stream)
1134
+ else await pollRepository(stream)
1135
+ } catch (error) {
1136
+ allReadsOk = false
1137
+ tickStreak.onFailure(error)
1138
+ }
1139
+ }
1140
+ if (allReadsOk) {
1141
+ try {
1142
+ await checkLiveness()
1143
+ tickStreak.onSuccess()
1144
+ } catch (error) {
1145
+ tickStreak.onFailure(error)
1146
+ }
1028
1147
  }
1029
1148
  }
1030
- for (const stream of [...streams.values()]) {
1031
- if (stop) return
1149
+
1150
+ // ── Initial scan ──
1151
+ // Named slugs are validated (and must belong to this repository) before
1152
+ // any record is emitted: an unknown slug is an error, full stop.
1153
+ for (const slug of slugs) {
1154
+ const record = await store.getBuild(slug)
1155
+ if (record === null) {
1156
+ throw new Error(
1157
+ `no build "${slug}" in this store — run 'ab builds --all' to list ` +
1158
+ "this repo's builds, or pass --store <ref> if it lives in another store",
1159
+ )
1160
+ }
1161
+ if (!(await buildInRepository(record, checkout, exec))) {
1162
+ throw new Error(`build "${slug}" belongs to repository "${record.repo}", not "${repo}"`)
1163
+ }
1164
+ }
1165
+ for (const slug of slugs) await trackBuild(slug, sinceStreams[slug])
1166
+ // Cursor streams that are no longer named resume anyway: finishing
1167
+ // their backlog is what makes a resumed watch lossless.
1168
+ for (const key of Object.keys(sinceStreams)) {
1169
+ if (key === REPO_STREAM_KEY) continue
1170
+ await trackBuild(key, sinceStreams[key])
1171
+ if (stop) break
1172
+ }
1173
+ if (followRepository) {
1174
+ if (!(await trackRepository())) {
1175
+ makeFailureStreak('watch', opts.stderr).onFailure(
1176
+ new Error(`could not read the repository journal for "${repo}"`),
1177
+ )
1178
+ }
1179
+ }
1180
+ if (!repository && slugs.length === 0) {
1181
+ // Membership discovery also baselines the default watch; a failed
1182
+ // discovery here is fatal — nothing has started yet.
1032
1183
  try {
1033
- if (stream.kind === 'build') await pollBuild(stream)
1034
- else await pollRepository(stream)
1184
+ await discoverBuilds()
1035
1185
  } catch (error) {
1036
- allReadsOk = false
1037
- tickStreak.onFailure(error)
1186
+ const message = error instanceof Error ? error.message : String(error)
1187
+ throw new Error(`could not list builds in this store (${message})`)
1038
1188
  }
1039
1189
  }
1040
- if (allReadsOk) {
1190
+
1191
+ if (followRepository && !stop) {
1041
1192
  try {
1042
1193
  await checkLiveness()
1043
- tickStreak.onSuccess()
1044
1194
  } catch (error) {
1045
1195
  tickStreak.onFailure(error)
1046
1196
  }
1047
1197
  }
1048
- }
1198
+ // ── The poll loop ──
1199
+ const deadline = timeoutMs === 0 ? Number.POSITIVE_INFINITY : now().getTime() + timeoutMs
1200
+ const aborted = (): boolean => opts.signal?.aborted === true
1201
+
1202
+ if (!isRemoteStoreRef(storeRef)) {
1203
+ // Local cadence: one sequential tick per interval.
1204
+ while (!stop) {
1205
+ if (aborted() || now().getTime() >= deadline || namedAllTerminal()) break
1206
+ await sleep(interval, opts.signal)
1207
+ if (aborted()) break
1208
+ await tick()
1209
+ }
1210
+ } else {
1211
+ // Remote cadence (AUT-334): one long-poll task per tracked stream,
1212
+ // running concurrently — a quiet stream keeps one held request in
1213
+ // flight, so an appended event arrives within about a second instead
1214
+ // of at the next interval tick. Gap-fill spaces each stream's request
1215
+ // starts at least `interval` apart (elapsed request time counts
1216
+ // toward the gap), so a server that answers immediately still sees
1217
+ // today's request rate. Discovery keeps its interval cadence.
1218
+ // Pre-launch guard mirrors the local loop's top-of-cycle checks: an
1219
+ // already-terminal named set, an elapsed deadline, or an abort ends
1220
+ // the watch before any request.
1221
+ // Every stop is prompt: an external abort, a tripped --count, an
1222
+ // all-terminal named set, or an elapsed --timeout cancels the
1223
+ // in-flight held reads (via `requestStop`) and wakes the gap sleeps
1224
+ // (via the runner's stop controller) instead of waiting out a full
1225
+ // hold. The held read's own bound is additionally capped at the
1226
+ // watch's remaining time budget, so a hold can never outlive the
1227
+ // deadline.
1228
+ const shouldStop = stop || aborted() || now().getTime() >= deadline || namedAllTerminal()
1229
+ const remoteRunner = createRemotePollRunner({
1230
+ command: 'watch',
1231
+ stderr: opts.stderr,
1232
+ now,
1233
+ sleep,
1234
+ intervalMs: interval,
1235
+ deadlineMs: deadline,
1236
+ aborted,
1237
+ shouldStop: () => aborted() || now().getTime() >= deadline || namedAllTerminal(),
1238
+ // A task's terminal endCheck stops the runner from the inside; the
1239
+ // command's `stop` flag must trip with it — pollBuild and
1240
+ // pollRepository gate their batch loops on that flag
1241
+ // (`if (stop) break`), so a sibling task whose held read has
1242
+ // already resolved stops delivering its batch instead of draining
1243
+ // it, exactly as the pre-extraction command-scoped `requestStop`
1244
+ // (which set `stop` on every path) made it do (f_42263f38).
1245
+ onStop: (): void => {
1246
+ stop = true
1247
+ },
1248
+ // Quiesce, not the runner's one-shot snapshot: a stream the
1249
+ // discovery task registers while drain is awaiting must have its
1250
+ // first held read awaited before the final cursor is encoded, or a
1251
+ // mid-discovery registration's emission lands after the cursor and
1252
+ // the next run replays it (the gap widened from a scheduling race
1253
+ // to a deterministic miss when discovery's digest read added one
1254
+ // await before the per-build reads — AUT-545). The snapshot
1255
+ // semantics the runner documents remain covered by its own tests.
1256
+ drain: 'quiesce',
1257
+ })
1258
+ runner = remoteRunner
1259
+
1260
+ const launch = (stream: Stream): void => {
1261
+ const key = stream.kind === 'build' ? stream.slug : REPO_STREAM_KEY
1262
+ remoteRunner.launch(
1263
+ key,
1264
+ (readOpts) =>
1265
+ stream.kind === 'build'
1266
+ ? pollBuild(stream, readOpts)
1267
+ : pollRepository(stream, readOpts),
1268
+ () => namedAllTerminal(),
1269
+ )
1270
+ }
1049
1271
 
1050
- // ── Initial scan ──
1051
- // Named slugs are validated (and must belong to this repository) before
1052
- // any record is emitted: an unknown slug is an error, full stop.
1053
- for (const slug of slugs) {
1054
- const record = await store.getBuild(slug)
1055
- if (record === null) {
1056
- throw new Error(
1057
- `no build "${slug}" in this store — run 'ab builds --all' to list ` +
1058
- "this repo's builds, or pass --store <ref> if it lives in another store",
1059
- )
1060
- }
1061
- if (!(await buildInRepository(record, checkout, exec))) {
1062
- throw new Error(`build "${slug}" belongs to repository "${record.repo}", not "${repo}"`)
1063
- }
1064
- }
1065
- for (const slug of slugs) await trackBuild(slug, sinceStreams[slug])
1066
- // Cursor streams that are no longer named resume anyway: finishing
1067
- // their backlog is what makes a resumed watch lossless.
1068
- for (const key of Object.keys(sinceStreams)) {
1069
- if (key === REPO_STREAM_KEY) continue
1070
- await trackBuild(key, sinceStreams[key])
1071
- if (stop) break
1072
- }
1073
- if (followRepository) {
1074
- if (!(await trackRepository())) {
1075
- makeFailureStreak('watch', opts.stderr).onFailure(
1076
- new Error(`could not read the repository journal for "${repo}"`),
1077
- )
1078
- }
1079
- }
1080
- if (!repository && slugs.length === 0) {
1081
- // Membership discovery also baselines the default watch; a failed
1082
- // discovery here is fatal — nothing has started yet.
1083
- try {
1084
- await discoverBuilds()
1085
- } catch (error) {
1086
- const message = error instanceof Error ? error.message : String(error)
1087
- throw new Error(`could not list builds in this store (${message})`)
1088
- }
1089
- }
1272
+ // An external abort (SIGINT) is a stop like any other: it cancels
1273
+ // the in-flight held reads and wakes the gap sleeps.
1274
+ opts.signal?.addEventListener('abort', requestStop, { once: true })
1275
+
1276
+ for (const stream of streams.values()) if (!shouldStop) launch(stream)
1277
+
1278
+ if ((slugs.length === 0 || followRepository) && !shouldStop) {
1279
+ void remoteRunner.runDiscovery({
1280
+ step: async (): Promise<void> => {
1281
+ if (slugs.length === 0) await discoverBuilds()
1282
+ const repositoryStream = streams.get(REPO_STREAM_KEY)
1283
+ if (repositoryStream?.kind === 'repo' && !stop)
1284
+ await pollRepository(repositoryStream)
1285
+ await checkLiveness()
1286
+ },
1287
+ // Unconditional, after the catch — exactly where the inline
1288
+ // launch loop ran: streams registered before a mid-discovery
1289
+ // throw still get tasks whose polls then run independently.
1290
+ launchPending: (): void => {
1291
+ for (const stream of streams.values()) launch(stream)
1292
+ },
1293
+ })
1294
+ }
1090
1295
 
1091
- if (followRepository && !stop) {
1092
- try {
1093
- await checkLiveness()
1094
- } catch (error) {
1095
- tickStreak.onFailure(error)
1096
- }
1097
- }
1098
- // ── The poll loop ──
1099
- const deadline = timeoutMs === 0 ? Number.POSITIVE_INFINITY : now().getTime() + timeoutMs
1100
- const aborted = (): boolean => opts.signal?.aborted === true
1101
-
1102
- if (!isRemoteStoreRef(storeRef)) {
1103
- // Local cadence: one sequential tick per interval.
1104
- while (!stop) {
1105
- if (aborted() || now().getTime() >= deadline || namedAllTerminal()) break
1106
- await sleep(interval, opts.signal)
1107
- if (aborted()) break
1108
- await tick()
1109
- }
1110
- } else {
1111
- // Remote cadence (AUT-334): one long-poll task per tracked stream,
1112
- // running concurrently — a quiet stream keeps one held request in
1113
- // flight, so an appended event arrives within about a second instead
1114
- // of at the next interval tick. Gap-fill spaces each stream's request
1115
- // starts at least `interval` apart (elapsed request time counts
1116
- // toward the gap), so a server that answers immediately still sees
1117
- // today's request rate. Discovery keeps its interval cadence.
1118
- // Pre-launch guard mirrors the local loop's top-of-cycle checks: an
1119
- // already-terminal named set, an elapsed deadline, or an abort ends
1120
- // the watch before any request.
1121
- // Every stop is prompt: an external abort, a tripped --count, an
1122
- // all-terminal named set, or an elapsed --timeout cancels the
1123
- // in-flight held reads (via `requestStop`) and wakes the gap sleeps
1124
- // (via the runner's stop controller) instead of waiting out a full
1125
- // hold. The held read's own bound is additionally capped at the
1126
- // watch's remaining time budget, so a hold can never outlive the
1127
- // deadline.
1128
- const shouldStop = stop || aborted() || now().getTime() >= deadline || namedAllTerminal()
1129
- const remoteRunner = createRemotePollRunner({
1130
- command: 'watch',
1131
- stderr: opts.stderr,
1132
- now,
1133
- sleep,
1134
- intervalMs: interval,
1135
- deadlineMs: deadline,
1136
- aborted,
1137
- shouldStop: () => aborted() || now().getTime() >= deadline || namedAllTerminal(),
1138
- // A task's terminal endCheck stops the runner from the inside; the
1139
- // command's `stop` flag must trip with it — pollBuild and
1140
- // pollRepository gate their batch loops on that flag
1141
- // (`if (stop) break`), so a sibling task whose held read has
1142
- // already resolved stops delivering its batch instead of draining
1143
- // it, exactly as the pre-extraction command-scoped `requestStop`
1144
- // (which set `stop` on every path) made it do (f_42263f38).
1145
- onStop: (): void => {
1146
- stop = true
1147
- },
1148
- // Quiesce, not the runner's one-shot snapshot: a stream the
1149
- // discovery task registers while drain is awaiting must have its
1150
- // first held read awaited before the final cursor is encoded, or a
1151
- // mid-discovery registration's emission lands after the cursor and
1152
- // the next run replays it (the gap widened from a scheduling race
1153
- // to a deterministic miss when discovery's digest read added one
1154
- // await before the per-build reads — AUT-545). The snapshot
1155
- // semantics the runner documents remain covered by its own tests.
1156
- drain: 'quiesce',
1157
- })
1158
- runner = remoteRunner
1159
-
1160
- const launch = (stream: Stream): void => {
1161
- const key = stream.kind === 'build' ? stream.slug : REPO_STREAM_KEY
1162
- remoteRunner.launch(
1163
- key,
1164
- (readOpts) =>
1165
- stream.kind === 'build'
1166
- ? pollBuild(stream, readOpts)
1167
- : pollRepository(stream, readOpts),
1168
- () => namedAllTerminal(),
1169
- )
1296
+ await remoteRunner.drain()
1297
+ opts.signal?.removeEventListener('abort', requestStop)
1170
1298
  }
1171
1299
 
1172
- // An external abort (SIGINT) is a stop like any other: it cancels
1173
- // the in-flight held reads and wakes the gap sleeps.
1174
- opts.signal?.addEventListener('abort', requestStop, { once: true })
1175
-
1176
- for (const stream of streams.values()) if (!shouldStop) launch(stream)
1177
-
1178
- if ((slugs.length === 0 || followRepository) && !shouldStop) {
1179
- void remoteRunner.runDiscovery({
1180
- step: async (): Promise<void> => {
1181
- if (slugs.length === 0) await discoverBuilds()
1182
- const repositoryStream = streams.get(REPO_STREAM_KEY)
1183
- if (repositoryStream?.kind === 'repo' && !stop) await pollRepository(repositoryStream)
1184
- await checkLiveness()
1185
- },
1186
- // Unconditional, after the catch — exactly where the inline
1187
- // launch loop ran: streams registered before a mid-discovery
1188
- // throw still get tasks whose polls then run independently.
1189
- launchPending: (): void => {
1190
- for (const stream of streams.values()) launch(stream)
1191
- },
1192
- })
1300
+ const finalCursor = countCursor ?? encodeCurrent()
1301
+ // SIGTERM/HUP previously used the process default and could not emit a
1302
+ // final cursor. SIGINT retains its existing orderly cursor output.
1303
+ const outputClosed =
1304
+ opts.signal?.aborted &&
1305
+ ['SIGTERM', 'SIGHUP', 'EPIPE'].includes(String(opts.signal.reason))
1306
+ if (opts.json === true && !outputClosed) {
1307
+ opts.stdout(JSON.stringify({ cursor: finalCursor }))
1193
1308
  }
1194
-
1195
- await remoteRunner.drain()
1196
- opts.signal?.removeEventListener('abort', requestStop)
1197
- }
1198
-
1199
- const finalCursor = countCursor ?? encodeCurrent()
1200
- if (opts.json === true) {
1201
- opts.stdout(JSON.stringify({ cursor: finalCursor }))
1309
+ await opts.flushStdout?.()
1310
+ } finally {
1311
+ heartbeatStop.abort()
1312
+ await lifetime.limit(heartbeatTask ?? Promise.resolve())
1313
+ if (operator && !lifetime.terminated) {
1314
+ try {
1315
+ await lifetime.renew()
1316
+ } catch (error) {
1317
+ if (!lifetime.terminated)
1318
+ opts.stderr(`ab watch: final operator heartbeat failed (${String(error)})`)
1319
+ }
1320
+ }
1321
+ await lifetime.finish()
1202
1322
  }
1203
- },
1204
- )
1323
+ }),
1324
+ ).finally(async () => {
1325
+ await lifetime.finish()
1326
+ lifetime.close()
1327
+ })
1205
1328
  }