@defrex/autobuild 1.8.0 → 1.9.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 (67) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +92 -11
  3. package/docs/architecture.md +38 -14
  4. package/docs/configuration.md +247 -4
  5. package/docs/dispatcher-hosting.md +4 -0
  6. package/docs/merge-policy.md +45 -5
  7. package/docs/operating.md +21 -0
  8. package/docs/operator-api.md +11 -2
  9. package/docs/plugin-authoring.md +4 -1
  10. package/docs/restacking.md +4 -0
  11. package/docs/setup.md +3 -1
  12. package/docs/verification.md +7 -6
  13. package/package.json +4 -3
  14. package/packages/core/src/cli/attention.ts +3 -0
  15. package/packages/core/src/cli/dashboard/landing-display.ts +9 -1
  16. package/packages/core/src/cli/dashboard/model.ts +25 -6
  17. package/packages/core/src/cli/dashboard/render.ts +2 -2
  18. package/packages/core/src/cli/dispatch.ts +120 -1
  19. package/packages/core/src/cli/help.ts +6 -2
  20. package/packages/core/src/cli/repository-status.ts +66 -1
  21. package/packages/core/src/cli/status.ts +2 -2
  22. package/packages/core/src/cli/watch.ts +1074 -627
  23. package/packages/core/src/config/live.ts +1 -0
  24. package/packages/core/src/config/load.ts +19 -0
  25. package/packages/core/src/config/schema.ts +114 -0
  26. package/packages/core/src/events/catalog.ts +2 -0
  27. package/packages/core/src/events/payloads.ts +22 -0
  28. package/packages/core/src/events/policy.ts +9 -0
  29. package/packages/core/src/events/repository.ts +43 -0
  30. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +31 -0
  31. package/packages/core/src/kernel/auto-merge.ts +33 -0
  32. package/packages/core/src/kernel/generators/repository-journals.ts +18 -0
  33. package/packages/core/src/kernel/landing-state.ts +56 -0
  34. package/packages/core/src/kernel/leaf-restack-base.ts +34 -0
  35. package/packages/core/src/kernel/leaf-restack-state.ts +1 -29
  36. package/packages/core/src/kernel/reducer.ts +1 -1
  37. package/packages/core/src/kernel/ticket-wait.ts +1 -1
  38. package/packages/core/src/plugin-sdk/index.ts +7 -1
  39. package/packages/core/src/ports/forge/fake.ts +128 -8
  40. package/packages/core/src/ports/forge/git-rewrite.ts +34 -3
  41. package/packages/core/src/ports/forge/github-squash-message.ts +89 -0
  42. package/packages/core/src/ports/forge/github-transport.ts +30 -0
  43. package/packages/core/src/ports/forge/github.ts +565 -164
  44. package/packages/core/src/ports/types.ts +47 -3
  45. package/packages/core/src/processes/build-execution-state.ts +4 -3
  46. package/packages/core/src/processes/dispatcher.ts +73 -4
  47. package/packages/core/src/processes/execution-no-progress.ts +2 -0
  48. package/packages/core/src/processes/hook-command.ts +125 -0
  49. package/packages/core/src/processes/hook-webhook.ts +144 -0
  50. package/packages/core/src/processes/hooks.ts +740 -0
  51. package/packages/core/src/store/contract.ts +28 -0
  52. package/packages/core/src/store/reducer-value-shapes.json +3729 -3297
  53. package/packages/core/src/store/remote/released-clients.json +22 -0
  54. package/packages/core/src/store/remote/released-reducer-values/1.9.0.json +29475 -0
  55. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  56. package/packages/core/src/store/repo-state-events.ts +3 -0
  57. package/packages/core/src/store/retention.ts +16 -2
  58. package/packages/core/src/testing/index.ts +1 -0
  59. package/packages/core/src/testing/reduced-read-budget.ts +476 -1
  60. package/skills/guide/SKILL.md +81 -6
  61. package/skills/guide/references/merge-policy.md +45 -5
  62. package/skills/guide/references/operator-api.md +11 -2
  63. package/skills/guide/references/plugin-authoring.md +4 -1
  64. package/skills/guide/references/restacking.md +4 -0
  65. package/skills/guide/references/setup.md +3 -1
  66. package/skills/operate/SKILL.md +24 -4
  67. package/templates/hosted-service/package.json +2 -2
@@ -13,7 +13,11 @@ import { buildStreamSeedReducer, type BuildStreamSeed } from '../kernel/read-fac
13
13
  import { historicalBuildState, historicalRepositoryAttention } from './historical-build-state'
14
14
  import { readDispatcherRunFacts } from '../store/reduced-reads'
15
15
  import { projectDispatcherLiveness } from '../kernel/dispatcher-liveness'
16
- import type { RepositoryRecord } from '../store/types'
16
+ import type { BuildDigest, BuildStore, RepositoryRecord } from '../store/types'
17
+ import { readRepositoryFacts, readPersistedBuildDigests } from '../store/reduced-reads'
18
+ import { isWorkDigest } from '../processes/repo-view'
19
+ import { creationBuildSlug } from '../kernel/build-creation'
20
+ import { landingFallbackReason } from '../kernel/landing-state'
17
21
  /**
18
22
  * `ab watch` — the sessionless streaming half of the status family
19
23
  * (§8.2, §7.2). It follows the event logs of one, several, or all active
@@ -165,9 +169,21 @@ interface CursorPayload {
165
169
  /** Per-stream watch position: build slug → seq, `#repo` → seq. */
166
170
  deliveredAttention?: string[]
167
171
  lostRuns?: string[]
172
+ /** Hook feeds only: build announcements still in preparation at this
173
+ * position, attempt → the slug and creation key `creation-selected` named. */
174
+ preparing?: Record<string, PreparingBuild>
168
175
  streams: Record<string, number>
169
176
  }
170
177
 
178
+ /** A selected build creation not yet resolved, as the hook feed tracks it. */
179
+ export interface PreparingBuild {
180
+ slug: string
181
+ creationKey?: string
182
+ }
183
+
184
+ /** The cursor fields a hook's status and skip report need; the format stays internal. */
185
+ export type WatchCursorPayload = CursorPayload
186
+
171
187
  function validAttentionIdentity(id: unknown): boolean {
172
188
  if (typeof id !== 'string') return false
173
189
  if (/^(source|tick):[1-9][0-9]*$/.test(id)) return true
@@ -176,7 +192,7 @@ function validAttentionIdentity(id: unknown): boolean {
176
192
  return (
177
193
  Array.isArray(value) &&
178
194
  ((value.length === 3 &&
179
- value[0] === 'consent' &&
195
+ (value[0] === 'consent' || value[0] === 'target.rewritten') &&
180
196
  typeof value[1] === 'string' &&
181
197
  value[1].length > 0 &&
182
198
  Number.isSafeInteger(value[2]) &&
@@ -225,10 +241,8 @@ export function decodeCursor(
225
241
  throw malformed()
226
242
  }
227
243
  if (typeof payload !== 'object' || payload === null) throw malformed()
228
- const { v, store, repo, streams, lostRuns, deliveredAttention, operator } = payload as Record<
229
- string,
230
- unknown
231
- >
244
+ const { v, store, repo, streams, lostRuns, deliveredAttention, operator, preparing } =
245
+ payload as Record<string, unknown>
232
246
  if (
233
247
  lostRuns !== undefined &&
234
248
  (!Array.isArray(lostRuns) ||
@@ -241,6 +255,22 @@ export function decodeCursor(
241
255
  deliveredAttention.some((id) => !validAttentionIdentity(id)))
242
256
  )
243
257
  throw malformed()
258
+ if (
259
+ preparing !== undefined &&
260
+ (typeof preparing !== 'object' ||
261
+ preparing === null ||
262
+ Array.isArray(preparing) ||
263
+ Object.values(preparing).some(
264
+ (entry: unknown) =>
265
+ typeof entry !== 'object' ||
266
+ entry === null ||
267
+ typeof (entry as PreparingBuild).slug !== 'string' ||
268
+ (entry as PreparingBuild).slug.trim().length === 0 ||
269
+ ((entry as PreparingBuild).creationKey !== undefined &&
270
+ typeof (entry as PreparingBuild).creationKey !== 'string'),
271
+ ))
272
+ )
273
+ throw malformed()
244
274
  if (operator !== undefined) {
245
275
  if (
246
276
  typeof operator !== 'object' ||
@@ -276,6 +306,7 @@ export function decodeCursor(
276
306
  ? {}
277
307
  : { deliveredAttention: deliveredAttention as string[] }),
278
308
  ...(lostRuns === undefined ? {} : { lostRuns: lostRuns as string[] }),
309
+ ...(preparing === undefined ? {} : { preparing: preparing as Record<string, PreparingBuild> }),
279
310
  }
280
311
  }
281
312
 
@@ -332,6 +363,7 @@ export interface WatchRecordState {
332
363
 
333
364
  /** Lease-expiry evidence is an observation, never a fabricated journal event. */
334
365
  export interface WatchObservationRecord {
366
+ id: string
335
367
  repo: string
336
368
  build: null
337
369
  state: null
@@ -419,6 +451,31 @@ function projectState(state: BuildState): WatchRecordState {
419
451
  }
420
452
  }
421
453
 
454
+ /** Every `ab watch --json` record line: the projection plus its stable `id`. */
455
+ export type WatchJsonRecord =
456
+ | (WatchRecord & { id: string })
457
+ | (AttentionObservationRecord & { id: string })
458
+ | WatchObservationRecord
459
+
460
+ /**
461
+ * The record identity `ab watch --json` and configured hooks carry. It is
462
+ * derived only from durable facts — a journal seq or an attention dedupe
463
+ * identity — so a regenerated or redelivered record has the same `id`.
464
+ */
465
+ export function watchRecordId(
466
+ source:
467
+ | { event: AbEvent | RepositoryEvent }
468
+ | { observation: string; identity: string }
469
+ | { lost: string },
470
+ ): string {
471
+ if ('event' in source)
472
+ return 'build' in source.event
473
+ ? `build:${source.event.build}:${source.event.seq}`
474
+ : `repo:${source.event.seq}`
475
+ if ('lost' in source) return `dispatcher.lost:${source.lost}`
476
+ return `${source.observation}:${source.identity}`
477
+ }
478
+
422
479
  /** `--json` form: exactly one object per matching event. */
423
480
  export function projectRecord(
424
481
  event: AbEvent | RepositoryEvent,
@@ -461,6 +518,20 @@ export function summarizeEvent(event: AbEvent | RepositoryEvent, state: BuildSta
461
518
  `Merge consent revoked for ${event.build}: reconcile edited files protected by merge[${p.rule.index}] (${p.paths.preview.join(', ')}${more > 0 ? `, +${more} more` : ''}); head ${p.previousHead} → ${p.head}; re-review and run ab merge ${event.build}`,
462
519
  )
463
520
  }
521
+ case 'landing.polling-selected':
522
+ return singleLine(
523
+ landingFallbackReason(
524
+ { mode: 'polling', seq: event.seq, ...event.payload },
525
+ state?.pr?.number,
526
+ ),
527
+ )
528
+ case 'landing.human-merge-required':
529
+ return singleLine(
530
+ landingFallbackReason(
531
+ { mode: 'human-merge', seq: event.seq, ...event.payload },
532
+ state?.pr?.number,
533
+ ),
534
+ )
464
535
  case 'target.rewritten':
465
536
  return `Upstream rewrite on ${event.payload.branch}: ${event.payload.previousSha} → ${event.payload.sha}; automatic adoption withheld`
466
537
  case 'verify.cancelled':
@@ -495,6 +566,16 @@ export function summarizeEvent(event: AbEvent | RepositoryEvent, state: BuildSta
495
566
  return `Kernel Git unavailable (${event.payload.executable}): ${singleLine(event.payload.detail)}`
496
567
  case 'dispatcher.kernel-git-recovered':
497
568
  return `Kernel Git recovered (${event.payload.executable})`
569
+ case 'hook.failing':
570
+ return singleLine(
571
+ `hook ${event.payload.hook} failing since ${event.payload.since} (${event.payload.attempts} attempts): ${event.payload.error}`,
572
+ )
573
+ case 'hook.recovered':
574
+ return `hook ${event.payload.hook} recovered`
575
+ case 'hook.skipped':
576
+ return singleLine(
577
+ `hook ${event.payload.hook} skipped ${event.payload.ranges.length} unavailable range(s): ${event.payload.reason}`,
578
+ )
498
579
  case 'phase.deferral-escalated':
499
580
  case 'build.janitor-escalated':
500
581
  case 'escalation.raised':
@@ -683,6 +764,168 @@ export interface AbWatchOpts {
683
764
  delay?: (ms: number, signal?: AbortSignal) => Promise<void>
684
765
  /** Termination signal from SIGINT/TERM/HUP or stdout EPIPE; ordinary completion does not abort it. */
685
766
  signal?: AbortSignal
767
+ /** In-process consumer (configured hooks); never set by the CLI route. */
768
+ feed?: WatchFeed
769
+ }
770
+
771
+ /**
772
+ * The in-process form of `ab watch` that configured hooks run: the same
773
+ * records, filters, identities and cursors, delivered to a structured sink.
774
+ * A feed never lists the build population on a pass: builds join through
775
+ * their announcement in the repository journal (`ticket-preparation`
776
+ * `creation-selected` then `resolved` `owned`, which brackets every
777
+ * `createBuild`), and settled terminal builds retire from the cursor, so
778
+ * each changed pass and each resume costs the active builds' new rows.
779
+ */
780
+ export interface WatchFeed {
781
+ /** Already-open store; abWatch neither resolves, scopes, nor closes it. */
782
+ context: { store: BuildStore; repo: string; storeRef: string; checkout: string }
783
+ /** Structured sink replacing stdout; no trailing {"cursor"} line is emitted. */
784
+ record: (record: WatchJsonRecord) => void
785
+ /** First-ever initialization only (no `since`): the pre-emission baseline
786
+ * cursor. Awaited before anything is tracked or emitted; a rejection fails
787
+ * initialization with nothing emitted. */
788
+ baseline?: (cursor: string) => Promise<void>
789
+ /** The position after each pass. A candidate only: every record emitted
790
+ * before it must succeed before the consumer may persist it. */
791
+ position?: (cursor: string) => void
792
+ /** Local-tick gate: false runs only in-memory timer checks this interval. */
793
+ changed: () => Promise<boolean>
794
+ /** Backpressure: true stops processing further events this pass. */
795
+ saturated: () => boolean
796
+ /** A build announcement that resolves to no single build. Awaited before
797
+ * the repository stream advances past the announcement. */
798
+ unresolved: (reason: string) => Promise<void>
799
+ }
800
+
801
+ /** Repository attention identities a feed cursor retains (build-scoped ones
802
+ * leave with their build's retirement). */
803
+ const FEED_REPOSITORY_IDENTITY_CAP = 256
804
+
805
+ /**
806
+ * The pre-emission baseline of a brand-new feed: the cursor a resume would
807
+ * start from if the feed had been running since this moment. Reads, in this
808
+ * fixed order — reordering them reopens a gap:
809
+ *
810
+ * 1. repository facts `P0` (open preparations) at cursor `Cf0`;
811
+ * 2. the repository's build digests `D` — the one population read, once per
812
+ * feed lifetime;
813
+ * 3. the stream seed `S` of every work build in `D`, whose cursor is that
814
+ * build's position;
815
+ * 4. the journal high-water `J0`, the load boundary (`Cf0 <= J0`, since
816
+ * values are served at the tail and the journal only grows). Every
817
+ * existing build's position was sampled before it, so no event appended
818
+ * to an existing build after the boundary is taken as history;
819
+ * 5. repository attention `A` at cursor `B`, the `#repo` baseline;
820
+ * 6. the journal window `(Cf0, B]`, walked in order so the open-attempt map
821
+ * is exact before every resolution.
822
+ *
823
+ * Builds resolved `owned` in the window after `J0`, or absent from `D`
824
+ * (created after the population read), form set `R` and start at seq 0;
825
+ * other sampled builds start at their seed; preparations still open at `B`
826
+ * are carried in `preparing` for the journal rule.
827
+ */
828
+ async function feedBaselineCursor(context: WatchFeed['context'], feed: WatchFeed): Promise<string> {
829
+ const { store, repo, storeRef } = context
830
+ for (;;) {
831
+ const facts = await readRepositoryFacts(store, repo)
832
+ const cf0 = facts.cursor
833
+ const digests = await readBuildDigests(store, repo)
834
+ const sampled = new Map<string, { cursor: number; merges: string[] }>()
835
+ for (const [slug, digest] of digests) {
836
+ if (!hasWork(digest)) continue
837
+ const seed = await readBuildStreamSeed(store, slug)
838
+ sampled.set(slug, {
839
+ cursor: seed.cursor,
840
+ merges: seed.value.mergeAttentionPrs.map((pr) => mergeIdentity(slug, pr)),
841
+ })
842
+ }
843
+ const j0 = (await store.getRepo(repo)) === null ? 0 : await store.getRepoHighWater(repo)
844
+ if (cf0 > j0) continue
845
+ const attention =
846
+ (await store.getRepo(repo)) === null
847
+ ? { cursor: 0 }
848
+ : await readRepositoryAttention(store, repo)
849
+ const b = attention.cursor
850
+ if (b < j0) continue
851
+ const preparing = new Map<string, PreparingBuild>()
852
+ for (const [attempt, held] of Object.entries(facts.value.preparation))
853
+ if (held.slug !== undefined)
854
+ preparing.set(attempt, {
855
+ slug: held.slug,
856
+ ...(held.creationKey !== undefined ? { creationKey: held.creationKey } : {}),
857
+ })
858
+ const announced = new Set<string>()
859
+ const window = b > cf0 ? await store.getRepoEvents(repo, cf0) : []
860
+ for (const event of window) {
861
+ if (event.seq > b) break
862
+ if (event.type === 'ticket-preparation.creation-selected') {
863
+ preparing.set(event.payload.attempt, {
864
+ slug: event.payload.slug,
865
+ ...(event.payload.creationKey !== undefined
866
+ ? { creationKey: event.payload.creationKey }
867
+ : {}),
868
+ })
869
+ } else if (event.type === 'ticket-preparation.resolved') {
870
+ const entry = preparing.get(event.payload.attempt)
871
+ if (event.payload.outcome === 'owned') {
872
+ const slug =
873
+ entry === undefined ? undefined : await resolveAnnouncedBuild(store, repo, entry)
874
+ if (slug === undefined)
875
+ await feed.unresolved(unresolvedAnnouncement(event.payload.attempt))
876
+ // After the boundary, or created after the population read and so
877
+ // never sampled: replayed from its first event.
878
+ else if (event.seq > j0 || !digests.has(slug)) announced.add(slug)
879
+ }
880
+ preparing.delete(event.payload.attempt)
881
+ }
882
+ }
883
+ const streams: Record<string, number> = { [REPO_STREAM_KEY]: b }
884
+ const deliveredAttention: string[] = []
885
+ for (const [slug, { cursor, merges }] of sampled) {
886
+ if (announced.has(slug)) continue
887
+ streams[slug] = cursor
888
+ deliveredAttention.push(...merges)
889
+ }
890
+ for (const slug of announced) streams[slug] = 0
891
+ return encodeCursor({
892
+ v: 1,
893
+ store: storeRef,
894
+ repo,
895
+ streams,
896
+ lostRuns: [],
897
+ deliveredAttention,
898
+ preparing: Object.fromEntries(preparing),
899
+ })
900
+ }
901
+ }
902
+
903
+ /** A build with work left — the dispatcher's own rule: nonterminal, aborted
904
+ * awaiting cleanup, unreclaimed, an open execution, or a pending integration
905
+ * audit. A feed tracks these; a settled terminal build retires. */
906
+ function hasWork(digest: Omit<BuildDigest, 'slug'>): boolean {
907
+ return isWorkDigest(digest) || digest.integrationAuditPending === true
908
+ }
909
+
910
+ function unresolvedAnnouncement(attempt: string): string {
911
+ return `build announced by attempt ${attempt} could not be resolved to one build`
912
+ }
913
+
914
+ /** The canonical slug of an announced build, resolved exactly as preparation
915
+ * recovery does: the selected slug, or the slug a recorded creation key
916
+ * derives — at most two point reads, never a listing. */
917
+ async function resolveAnnouncedBuild(
918
+ store: BuildStore,
919
+ repo: string,
920
+ entry: PreparingBuild,
921
+ ): Promise<string | undefined> {
922
+ const candidates =
923
+ entry.creationKey === undefined
924
+ ? [entry.slug]
925
+ : [entry.slug, creationBuildSlug(repo, entry.slug, entry.creationKey)]
926
+ const found: string[] = []
927
+ for (const slug of candidates) if ((await store.getBuild(slug)) !== null) found.push(slug)
928
+ return found.length === 1 ? found[0] : undefined
686
929
  }
687
930
 
688
931
  interface BuildStream {
@@ -693,11 +936,16 @@ interface BuildStream {
693
936
  seed: BuildStreamSeed
694
937
  lastSeq: number
695
938
  status: BuildStatus
939
+ /** Feed only: events read but not yet processed when backpressure ended a pass. */
940
+ backlog: AbEvent[]
941
+ /** The record read at tracking time, for the feed's one-build retirement read. */
942
+ record?: BuildRecord
696
943
  }
697
944
 
698
945
  interface RepositoryStream {
699
946
  kind: 'repo'
700
947
  lastSeq: number
948
+ backlog: RepositoryEvent[]
701
949
  }
702
950
 
703
951
  type Stream = BuildStream | RepositoryStream
@@ -708,6 +956,18 @@ type Stream = BuildStream | RepositoryStream
708
956
  * watch. Unflagged watches are read-only; --operator adds advisory liveness.
709
957
  */
710
958
  export async function abWatch(opts: AbWatchOpts): Promise<void> {
959
+ const feed = opts.feed
960
+ if (feed !== undefined) {
961
+ if (opts.since === undefined) {
962
+ // First-ever initialization persists its baseline before anything is
963
+ // emitted, then shares the resume path: a crash or failed first
964
+ // delivery regenerates the same records from the same saved cursor.
965
+ const cursor = await feedBaselineCursor(feed.context, feed)
966
+ await feed.baseline?.(cursor)
967
+ return abWatch({ ...opts, since: cursor })
968
+ }
969
+ opts = { ...opts, operator: false, json: true, slugs: [], repository: false, count: undefined }
970
+ }
711
971
  const now = opts.now ?? (() => new Date())
712
972
  const sleep = opts.delay ?? defaultDelay
713
973
  const slugs = [...(opts.slugs ?? [])]
@@ -737,8 +997,9 @@ export async function abWatch(opts: AbWatchOpts): Promise<void> {
737
997
  if (opts.count !== undefined && (!Number.isSafeInteger(opts.count) || opts.count <= 0))
738
998
  throw new Error(`--count requires a positive integer — ${WATCH_USAGE}`)
739
999
 
740
- // Ambient scope, before any store access.
741
- assertReadScope(slugs, { repository: followRepository, env: opts.env })
1000
+ // Ambient scope, before any store access. A feed runs on the dispatcher's
1001
+ // own already-scoped store.
1002
+ if (feed === undefined) assertReadScope(slugs, { repository: followRepository, env: opts.env })
742
1003
 
743
1004
  // Glob validation needs only the catalogs — before any store access.
744
1005
  const filters = compileEventGlobs(opts.events ?? [], {
@@ -748,700 +1009,886 @@ export async function abWatch(opts: AbWatchOpts): Promise<void> {
748
1009
  })
749
1010
 
750
1011
  const lifetime = new WatchLifetime(opts.signal, opts.stderr)
751
- await withAmbientReadStore(
752
- {
753
- closeDeadline: lifetime.deadline.signal,
754
- targetRepo: opts.targetRepo,
755
- env: opts.env,
756
- exec: opts.exec,
757
- ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
758
- ...(opts.openStore !== undefined ? { openStore: opts.openStore } : {}),
759
- },
760
- lifetime.limitCallback(async (context: OpenedStoreContext) => {
761
- const { store, repo, storeRef, checkout } = context
762
- const { exec } = opts
763
- const interval = intervalMs ?? watchSelection(storeRef).intervalMs
764
-
765
- // Decode --since before any read: a foreign cursor is rejected outright.
766
- const sinceStreams =
767
- opts.since !== undefined ? decodeCursor(opts.since, { store: storeRef, repo }).streams : {}
768
-
769
- // Verified (AUT-574): this is the full normalized-identity rule of
770
- // AUT-567 — the same `mine` predicate as status.ts and wait.ts, with
771
- // buildInRepository's semantics. `identity` is resolveRepoState's
772
- // `origin ?? resolved checkout`, already normalized (re-normalizing is
773
- // a no-op); the first arm is the whole test for new records, whose
774
- // `record.repo` IS the normalized origin, and the second arm forgives
775
- // legacy path-keyed records via their normalized `repoOrigin`. A
776
- // foreign origin, or an origin-less legacy record, is excluded.
777
- const identity = normalizeGitRemoteUrl(repo)
778
- const mine = (record: BuildRecord): boolean =>
779
- record.repo === identity ||
780
- (record.repoOrigin !== undefined && normalizeGitRemoteUrl(record.repoOrigin) === identity)
781
-
782
- const lostRuns = new Set(
783
- opts.since ? (decodeCursor(opts.since, { store: storeRef, repo }).lostRuns ?? []) : [],
784
- )
785
- const resumedCursor = opts.since
786
- ? decodeCursor(opts.since, { store: storeRef, repo })
787
- : undefined
788
- const operator = opts.operator
789
- ? operatorIdentitySchema.parse({
790
- id: resumedCursor?.operator?.id ?? (opts.operatorIdentity?.newId ?? randomUUID)(),
791
- startedAt: resumedCursor?.operator?.startedAt ?? now().toISOString(),
792
- host: opts.operatorIdentity?.host ?? hostname(),
793
- pid: opts.operatorIdentity?.pid ?? process.pid,
794
- })
795
- : undefined
796
- const heartbeatStop = new AbortController()
797
- let heartbeatTask: Promise<void> | undefined
798
- if (operator) {
799
- try {
800
- await lifetime.register(store, repo, operator)
801
- } catch (error) {
802
- if (isTerminalEventReadError(error)) throw error
803
- if (!lifetime.terminated) throw error
804
- }
805
- heartbeatTask = (async () => {
806
- let reported = false
807
- let nextHeartbeatAt = now().getTime() + OPERATOR_HEARTBEAT_MS
808
- while (!heartbeatStop.signal.aborted && !lifetime.terminated) {
809
- await (opts.heartbeatDelay ?? defaultDelay)(
810
- Math.max(0, nextHeartbeatAt - now().getTime()),
811
- AbortSignal.any([heartbeatStop.signal, lifetime.writes.signal]),
812
- )
813
- if (heartbeatStop.signal.aborted || lifetime.terminated) break
814
- nextHeartbeatAt = now().getTime() + OPERATOR_HEARTBEAT_MS
815
- try {
816
- await lifetime.renew()
817
- reported = false
818
- } catch (error) {
819
- if (isTerminalEventReadError(error)) throw error
820
- if (!reported && !lifetime.terminated)
821
- opts.stderr(
822
- `ab watch: operator heartbeat failed (${String(error)}); retrying at next heartbeat`,
823
- )
824
- reported = true
825
- }
826
- }
827
- })()
828
- }
1012
+ const body = async (context: WatchFeed['context']): Promise<void> => {
1013
+ const { store, repo, storeRef, checkout } = context
1014
+ const { exec } = opts
1015
+ const interval = intervalMs ?? watchSelection(storeRef).intervalMs
1016
+
1017
+ // Decode --since before any read: a foreign cursor is rejected outright.
1018
+ const sinceStreams =
1019
+ opts.since !== undefined ? decodeCursor(opts.since, { store: storeRef, repo }).streams : {}
1020
+
1021
+ // Verified (AUT-574): this is the full normalized-identity rule of
1022
+ // AUT-567 — the same `mine` predicate as status.ts and wait.ts, with
1023
+ // buildInRepository's semantics. `identity` is resolveRepoState's
1024
+ // `origin ?? resolved checkout`, already normalized (re-normalizing is
1025
+ // a no-op); the first arm is the whole test for new records, whose
1026
+ // `record.repo` IS the normalized origin, and the second arm forgives
1027
+ // legacy path-keyed records via their normalized `repoOrigin`. A
1028
+ // foreign origin, or an origin-less legacy record, is excluded.
1029
+ const identity = normalizeGitRemoteUrl(repo)
1030
+ const mine = (record: BuildRecord): boolean =>
1031
+ record.repo === identity ||
1032
+ (record.repoOrigin !== undefined && normalizeGitRemoteUrl(record.repoOrigin) === identity)
1033
+
1034
+ const lostRuns = new Set(
1035
+ opts.since ? (decodeCursor(opts.since, { store: storeRef, repo }).lostRuns ?? []) : [],
1036
+ )
1037
+ const resumedCursor = opts.since
1038
+ ? decodeCursor(opts.since, { store: storeRef, repo })
1039
+ : undefined
1040
+ const operator = opts.operator
1041
+ ? operatorIdentitySchema.parse({
1042
+ id: resumedCursor?.operator?.id ?? (opts.operatorIdentity?.newId ?? randomUUID)(),
1043
+ startedAt: resumedCursor?.operator?.startedAt ?? now().toISOString(),
1044
+ host: opts.operatorIdentity?.host ?? hostname(),
1045
+ pid: opts.operatorIdentity?.pid ?? process.pid,
1046
+ })
1047
+ : undefined
1048
+ const heartbeatStop = new AbortController()
1049
+ let heartbeatTask: Promise<void> | undefined
1050
+ if (operator) {
829
1051
  try {
830
- const deliveredAttention = new Set(resumedCursor?.deliveredAttention ?? [])
831
- let repositoryAttention = new RepositoryAttention()
832
- let attentionInitialized = false
833
- const observedOwners = new Map<string, RepositoryRecord>()
834
- const streams = new Map<string, Stream>()
835
- // Every stream's position — matching or not, delivered or baselined —
836
- // lives here, so a resume never rescans or redelivers a filtered event.
837
- const positions: Record<string, number> = { ...sinceStreams }
838
- let emitted = 0
839
- let countCursor: string | undefined
840
- let stop = false
841
- // On the remote path this is the shared long-poll runner (the held
842
- // reads, their cancellation, and the gap sleeps it owns); on the local
843
- // path it stays undefined and a stop trips the `stop` flag alone.
844
- let runner: RemotePollRunner | undefined
845
- const requestStop = (): void => {
846
- stop = true
847
- runner?.requestStop()
1052
+ await lifetime.register(store, repo, operator)
1053
+ } catch (error) {
1054
+ if (isTerminalEventReadError(error)) throw error
1055
+ if (!lifetime.terminated) throw error
1056
+ }
1057
+ heartbeatTask = (async () => {
1058
+ let reported = false
1059
+ let nextHeartbeatAt = now().getTime() + OPERATOR_HEARTBEAT_MS
1060
+ while (!heartbeatStop.signal.aborted && !lifetime.terminated) {
1061
+ await (opts.heartbeatDelay ?? defaultDelay)(
1062
+ Math.max(0, nextHeartbeatAt - now().getTime()),
1063
+ AbortSignal.any([heartbeatStop.signal, lifetime.writes.signal]),
1064
+ )
1065
+ if (heartbeatStop.signal.aborted || lifetime.terminated) break
1066
+ nextHeartbeatAt = now().getTime() + OPERATOR_HEARTBEAT_MS
1067
+ try {
1068
+ await lifetime.renew()
1069
+ reported = false
1070
+ } catch (error) {
1071
+ if (isTerminalEventReadError(error)) throw error
1072
+ if (!reported && !lifetime.terminated)
1073
+ opts.stderr(
1074
+ `ab watch: operator heartbeat failed (${String(error)}); retrying at next heartbeat`,
1075
+ )
1076
+ reported = true
1077
+ }
848
1078
  }
1079
+ })()
1080
+ }
1081
+ try {
1082
+ const deliveredAttention = new Set(resumedCursor?.deliveredAttention ?? [])
1083
+ let repositoryAttention = new RepositoryAttention()
1084
+ let attentionInitialized = false
1085
+ const observedOwners = new Map<string, RepositoryRecord>()
1086
+ const streams = new Map<string, Stream>()
1087
+ // Every stream's position — matching or not, delivered or baselined —
1088
+ // lives here, so a resume never rescans or redelivers a filtered event.
1089
+ const positions: Record<string, number> = { ...sinceStreams }
1090
+ let emitted = 0
1091
+ let countCursor: string | undefined
1092
+ let stop = false
1093
+ // On the remote path this is the shared long-poll runner (the held
1094
+ // reads, their cancellation, and the gap sleeps it owns); on the local
1095
+ // path it stays undefined and a stop trips the `stop` flag alone.
1096
+ let runner: RemotePollRunner | undefined
1097
+ const requestStop = (): void => {
1098
+ stop = true
1099
+ runner?.requestStop()
1100
+ }
849
1101
 
850
- const encodeCurrent = (): string =>
851
- encodeCursor({
852
- v: 1,
853
- store: storeRef,
854
- repo,
855
- streams: { ...positions },
856
- ...(operator ? { operator: { id: operator.id, startedAt: operator.startedAt } } : {}),
857
- lostRuns: [...lostRuns],
858
- deliveredAttention: [...deliveredAttention],
859
- })
1102
+ // Feed only: selected creations not yet resolved, so an announcement
1103
+ // whose selection lies behind a resumed position still resolves.
1104
+ const preparing = new Map<string, PreparingBuild>(
1105
+ Object.entries(resumedCursor?.preparing ?? {}),
1106
+ )
1107
+ const encodeCurrent = (): string =>
1108
+ encodeCursor({
1109
+ v: 1,
1110
+ store: storeRef,
1111
+ repo,
1112
+ streams: { ...positions },
1113
+ ...(operator ? { operator: { id: operator.id, startedAt: operator.startedAt } } : {}),
1114
+ lostRuns: [...lostRuns],
1115
+ deliveredAttention: [...deliveredAttention],
1116
+ ...(feed !== undefined ? { preparing: Object.fromEntries(preparing) } : {}),
1117
+ })
1118
+ /** Feed backpressure: a full consumer queue ends this pass early; the
1119
+ * unprocessed events stay in their stream's backlog for the next one. */
1120
+ let yieldedLastPass = false
1121
+ const halted = (): boolean => {
1122
+ if (stop) return true
1123
+ if (feed?.saturated() !== true) return false
1124
+ yieldedLastPass = true
1125
+ return true
1126
+ }
860
1127
 
861
- /** One record, flushed the moment it is projected. `cursor` is the watch
862
- * position AFTER this event. */
863
- const emit = (event: AbEvent | RepositoryEvent, state: BuildState | null): void => {
864
- const cursor = encodeCurrent()
865
- if (opts.json === true) {
866
- opts.stdout(JSON.stringify(projectRecord(event, state, cursor)))
867
- } else {
868
- opts.stdout(renderWatchLine(event, state))
869
- }
870
- emitted += 1
871
- if (opts.count !== undefined && emitted >= opts.count) {
872
- // Events read but not delivered because the count tripped stay
873
- // unprocessed: the next run resumes from THIS record's cursor.
874
- countCursor = cursor
875
- requestStop()
876
- }
1128
+ /** One record, flushed the moment it is projected. `cursor` is the watch
1129
+ * position AFTER this event. */
1130
+ const emit = (event: AbEvent | RepositoryEvent, state: BuildState | null): void => {
1131
+ const cursor = encodeCurrent()
1132
+ if (feed !== undefined) {
1133
+ feed.record({ id: watchRecordId({ event }), ...projectRecord(event, state, cursor) })
1134
+ } else if (opts.json === true) {
1135
+ opts.stdout(
1136
+ JSON.stringify({
1137
+ id: watchRecordId({ event }),
1138
+ ...projectRecord(event, state, cursor),
1139
+ }),
1140
+ )
1141
+ } else {
1142
+ opts.stdout(renderWatchLine(event, state))
1143
+ }
1144
+ emitted += 1
1145
+ if (opts.count !== undefined && emitted >= opts.count) {
1146
+ // Events read but not delivered because the count tripped stay
1147
+ // unprocessed: the next run resumes from THIS record's cursor.
1148
+ countCursor = cursor
1149
+ requestStop()
877
1150
  }
1151
+ }
878
1152
 
879
- const emitObservation = (
880
- observation: MergeDecision | PersistenceObservation | ConsentReady,
881
- state: BuildState | null,
882
- scope: { build: string } | { repo: string },
883
- identity: string,
884
- ): void => {
885
- if (stop || deliveredAttention.has(identity)) return
886
- deliveredAttention.add(identity)
887
- const cursor = encodeCurrent()
1153
+ const emitObservation = (
1154
+ observation: MergeDecision | PersistenceObservation | ConsentReady,
1155
+ state: BuildState | null,
1156
+ scope: { build: string } | { repo: string },
1157
+ identity: string,
1158
+ ): void => {
1159
+ if (stop || deliveredAttention.has(identity)) return
1160
+ deliveredAttention.add(identity)
1161
+ const cursor = encodeCurrent()
1162
+ const record = {
1163
+ id: watchRecordId({ observation: observation.type, identity }),
1164
+ ...projectAttentionRecord(observation, state, cursor, scope),
1165
+ }
1166
+ if (feed !== undefined) feed.record(record)
1167
+ else
888
1168
  opts.stdout(
889
1169
  opts.json
890
- ? JSON.stringify(projectAttentionRecord(observation, state, cursor, scope))
1170
+ ? JSON.stringify(record)
891
1171
  : renderAttentionLine(observation, 'build' in scope ? scope.build : '(repository)'),
892
1172
  )
893
- emitted += 1
894
- if (opts.count !== undefined && emitted >= opts.count) {
895
- countCursor = cursor
896
- requestStop()
897
- }
1173
+ emitted += 1
1174
+ if (opts.count !== undefined && emitted >= opts.count) {
1175
+ countCursor = cursor
1176
+ requestStop()
898
1177
  }
899
- const checkConsent = (stream: BuildStream): void => {
900
- if (filters.length || stop) return
901
- const currentState = buildReducer.finish(stream.seed.build)
902
- const rewrite = currentState.targetRewrite
903
- if (rewrite) {
904
- const identity = JSON.stringify(['target.rewritten', stream.slug, rewrite.seq])
905
- if (!deliveredAttention.has(identity)) {
906
- deliveredAttention.add(identity)
907
- emit(rewrite, currentState)
908
- if (stop) return
909
- }
910
- }
911
- const observation = consentReady(stream.seed, now())
912
- if (observation)
913
- emitObservation(
914
- observation,
915
- buildReducer.finish(stream.seed.build),
916
- { build: stream.slug },
917
- consentIdentity(stream.slug, observation.position),
918
- )
919
- }
920
- const checkPersistence = (): void => {
921
- if (filters.length || !attentionInitialized || stop) return
922
- for (const { identity, observation } of repositoryAttention.pending(now())) {
923
- emitObservation(observation, null, { repo }, identity)
1178
+ }
1179
+ const checkConsent = (stream: BuildStream): void => {
1180
+ if (filters.length || stop) return
1181
+ const currentState = buildReducer.finish(stream.seed.build)
1182
+ const rewrite = currentState.targetRewrite
1183
+ if (rewrite) {
1184
+ const identity = JSON.stringify(['target.rewritten', stream.slug, rewrite.seq])
1185
+ if (!deliveredAttention.has(identity)) {
1186
+ deliveredAttention.add(identity)
1187
+ emit(rewrite, currentState)
924
1188
  if (stop) return
925
1189
  }
926
1190
  }
927
- const baselineMerge = (slug: string, seed: BuildStreamSeed): void => {
928
- for (const pr of seed.mergeAttentionPrs) deliveredAttention.add(mergeIdentity(slug, pr))
1191
+ const observation = consentReady(stream.seed, now())
1192
+ if (observation)
1193
+ emitObservation(
1194
+ observation,
1195
+ buildReducer.finish(stream.seed.build),
1196
+ { build: stream.slug },
1197
+ consentIdentity(stream.slug, observation.position),
1198
+ )
1199
+ }
1200
+ const checkPersistence = (): void => {
1201
+ if (filters.length || !attentionInitialized || stop) return
1202
+ for (const { identity, observation } of repositoryAttention.pending(now())) {
1203
+ emitObservation(observation, null, { repo }, identity)
1204
+ if (stop) return
929
1205
  }
1206
+ }
1207
+ const checkMergeDecision = (stream: BuildStream, state: BuildState): void => {
1208
+ if (filters.length || stop) return
1209
+ const observation = mergeDecisionFromFacts(state, stream.seed.deferral, now())
1210
+ if (observation)
1211
+ emitObservation(
1212
+ observation,
1213
+ state,
1214
+ { build: stream.slug },
1215
+ mergeIdentity(stream.slug, observation.pr.number),
1216
+ )
1217
+ }
1218
+ const baselineMerge = (slug: string, seed: BuildStreamSeed): void => {
1219
+ for (const pr of seed.mergeAttentionPrs) deliveredAttention.add(mergeIdentity(slug, pr))
1220
+ }
930
1221
 
931
- const checkLiveness = async (): Promise<void> => {
932
- if (!followRepository || stop) return
933
- if ((await store.getRepo(repo)) === null) return
934
- // Sample metadata after the journal. Recheck both immediately before
935
- // reporting: a failed read is infrastructure, never evidence of death.
936
- const record = await store.getRepo(repo)
937
- if (record?.lease) observedOwners.set(record.lease.holder, record)
938
- let upgrade: Awaited<ReturnType<typeof readDispatchUpgrade>> | undefined
939
- for (const [id, owner] of observedOwners) {
940
- if (
941
- stop ||
942
- lostRuns.has(id) ||
943
- !owner.lease ||
944
- Date.parse(owner.lease.expiresAt) > now().getTime()
945
- )
946
- continue
947
- const current = await store.getRepo(repo)
948
- if (current?.lease?.holder === id) {
949
- observedOwners.set(id, current)
950
- if (Date.parse(current.lease.expiresAt) > now().getTime()) continue
951
- }
952
- const facts = (await readDispatcherRunFacts(store, repo, id)).value
953
- if (facts.stop) {
954
- observedOwners.delete(id)
955
- continue
956
- }
957
- const evidence = projectDispatcherLiveness(
958
- current?.lease?.holder === id ? current : owner,
959
- [facts.start, facts.latestStart, facts.stop, facts.tick, facts.runtime].filter(
960
- (event): event is RepositoryEvent => event !== undefined,
961
- ),
962
- now(),
963
- )
964
- // Only a validated takeover proves transfer; intent or release alone
965
- // must still report a predecessor whose successor never arrives.
966
- upgrade ??= await readDispatchUpgrade(store, repo)
967
- if (upgrade.value.runs[id]?.takeover) {
968
- observedOwners.delete(id)
969
- continue
970
- }
971
- if (!(filters.length ? filters.some((f) => f.test('dispatcher.lost')) : true)) continue
972
- if (stop) return
973
- lostRuns.add(id)
974
- const cursor = encodeCurrent()
975
- const observation = {
976
- ...evidence.expiredHolder,
977
- type: 'dispatcher.lost',
978
- run: id,
979
- observedAt: now().toISOString(),
980
- leaseExpiresAt: (current?.lease?.holder === id ? current : owner).lease!.expiresAt,
981
- }
1222
+ const checkLiveness = async (): Promise<void> => {
1223
+ if (!followRepository || stop) return
1224
+ if ((await store.getRepo(repo)) === null) return
1225
+ // Sample metadata after the journal. Recheck both immediately before
1226
+ // reporting: a failed read is infrastructure, never evidence of death.
1227
+ const record = await store.getRepo(repo)
1228
+ if (record?.lease) observedOwners.set(record.lease.holder, record)
1229
+ let upgrade: Awaited<ReturnType<typeof readDispatchUpgrade>> | undefined
1230
+ for (const [id, owner] of observedOwners) {
1231
+ if (
1232
+ stop ||
1233
+ lostRuns.has(id) ||
1234
+ !owner.lease ||
1235
+ Date.parse(owner.lease.expiresAt) > now().getTime()
1236
+ )
1237
+ continue
1238
+ const current = await store.getRepo(repo)
1239
+ if (current?.lease?.holder === id) {
1240
+ observedOwners.set(id, current)
1241
+ if (Date.parse(current.lease.expiresAt) > now().getTime()) continue
1242
+ }
1243
+ const facts = (await readDispatcherRunFacts(store, repo, id)).value
1244
+ if (facts.stop) {
1245
+ observedOwners.delete(id)
1246
+ continue
1247
+ }
1248
+ const evidence = projectDispatcherLiveness(
1249
+ current?.lease?.holder === id ? current : owner,
1250
+ [facts.start, facts.latestStart, facts.stop, facts.tick, facts.runtime].filter(
1251
+ (event): event is RepositoryEvent => event !== undefined,
1252
+ ),
1253
+ now(),
1254
+ )
1255
+ // Only a validated takeover proves transfer; intent or release alone
1256
+ // must still report a predecessor whose successor never arrives.
1257
+ upgrade ??= await readDispatchUpgrade(store, repo)
1258
+ if (upgrade.value.runs[id]?.takeover) {
1259
+ observedOwners.delete(id)
1260
+ continue
1261
+ }
1262
+ if (!(filters.length ? filters.some((f) => f.test('dispatcher.lost')) : true)) continue
1263
+ if (stop) return
1264
+ lostRuns.add(id)
1265
+ const cursor = encodeCurrent()
1266
+ const observation = {
1267
+ ...evidence.expiredHolder,
1268
+ type: 'dispatcher.lost' as const,
1269
+ run: id,
1270
+ observedAt: now().toISOString(),
1271
+ leaseExpiresAt: (current?.lease?.holder === id ? current : owner).lease!.expiresAt,
1272
+ }
1273
+ const record = {
1274
+ id: watchRecordId({ lost: id }),
1275
+ repo,
1276
+ build: null,
1277
+ state: null,
1278
+ observation,
1279
+ cursor,
1280
+ }
1281
+ if (feed !== undefined) feed.record(record)
1282
+ else
982
1283
  opts.stdout(
983
1284
  opts.json
984
- ? JSON.stringify({ repo, build: null, state: null, observation, cursor })
1285
+ ? JSON.stringify(record)
985
1286
  : `dispatcher.lost ${id} — lease expired ${observation.leaseExpiresAt}`,
986
1287
  )
987
- emitted += 1
988
- if (opts.count !== undefined && emitted >= opts.count) {
989
- countCursor = cursor
990
- requestStop()
991
- }
1288
+ emitted += 1
1289
+ if (opts.count !== undefined && emitted >= opts.count) {
1290
+ countCursor = cursor
1291
+ requestStop()
992
1292
  }
993
1293
  }
1294
+ }
994
1295
 
995
- /** Record one event. `prefix` is the event prefix ENDING at `event` —
996
- * the record's state is the reduction after THIS event, never a
997
- * reduction over events that landed after it. The poll path passes the
998
- * stream's just-extended array; the resume path replays the backlog
999
- * into a scratch prefix so a resumed record never leaks state from
1000
- * events that landed after it. */
1001
- const processBuildEvent = (stream: BuildStream, event: AbEvent): void => {
1002
- if (stop) return
1003
- stream.lastSeq = event.seq
1004
- positions[stream.slug] = event.seq
1005
- stream.seed = buildStreamSeedReducer.advance(stream.seed, [event])
1006
- const state = buildReducer.finish(stream.seed.build)
1007
- stream.status = state.status
1008
- if (
1009
- matchesBuildFilter(event.type, filters) ||
1010
- (!filters.length && event.type === 'restack.replayed' && event.payload.conflicted)
1011
- )
1012
- emit(event, state)
1013
- if (event.type === 'target.rewritten')
1014
- deliveredAttention.add(JSON.stringify(['target.rewritten', stream.slug, event.seq]))
1015
- checkConsent(stream)
1016
- if (!filters.length && !stop) {
1017
- const observation = mergeDecisionFromFacts(state, stream.seed.deferral, now())
1018
- if (observation)
1019
- emitObservation(
1020
- observation,
1021
- state,
1022
- { build: stream.slug },
1023
- mergeIdentity(stream.slug, observation.pr.number),
1024
- )
1025
- }
1026
- }
1296
+ /** Record one event. `prefix` is the event prefix ENDING at `event` —
1297
+ * the record's state is the reduction after THIS event, never a
1298
+ * reduction over events that landed after it. The poll path passes the
1299
+ * stream's just-extended array; the resume path replays the backlog
1300
+ * into a scratch prefix so a resumed record never leaks state from
1301
+ * events that landed after it. */
1302
+ const processBuildEvent = (stream: BuildStream, event: AbEvent): void => {
1303
+ if (stop) return
1304
+ stream.lastSeq = event.seq
1305
+ positions[stream.slug] = event.seq
1306
+ stream.seed = buildStreamSeedReducer.advance(stream.seed, [event])
1307
+ const state = buildReducer.finish(stream.seed.build)
1308
+ stream.status = state.status
1309
+ if (
1310
+ matchesBuildFilter(event.type, filters) ||
1311
+ (!filters.length && event.type === 'restack.replayed' && event.payload.conflicted)
1312
+ )
1313
+ emit(event, state)
1314
+ if (event.type === 'target.rewritten')
1315
+ deliveredAttention.add(JSON.stringify(['target.rewritten', stream.slug, event.seq]))
1316
+ checkConsent(stream)
1317
+ checkMergeDecision(stream, state)
1318
+ }
1027
1319
 
1028
- const processRepositoryEvent = (stream: RepositoryStream, event: RepositoryEvent): void => {
1029
- if (stop) return
1030
- stream.lastSeq = event.seq
1031
- positions[REPO_STREAM_KEY] = event.seq
1032
- repositoryAttention.fold(event)
1033
- if (
1034
- filters.length
1035
- ? filters.some((regex) => regex.test(event.type))
1036
- : repositoryNeedsAttention(event)
1037
- )
1038
- emit(event, null)
1320
+ const processRepositoryEvent = (stream: RepositoryStream, event: RepositoryEvent): void => {
1321
+ if (stop) return
1322
+ stream.lastSeq = event.seq
1323
+ positions[REPO_STREAM_KEY] = event.seq
1324
+ repositoryAttention.fold(event)
1325
+ if (
1326
+ filters.length
1327
+ ? filters.some((regex) => regex.test(event.type))
1328
+ : repositoryNeedsAttention(event)
1329
+ )
1330
+ emit(event, null)
1331
+ }
1332
+
1333
+ /**
1334
+ * Register a build stream over the full event prefix. `resumeSeq` (a
1335
+ * cursor position) additionally emits every matching event after it —
1336
+ * the backlog that landed while no watch was running. A baseline (the
1337
+ * default) replays nothing: the position starts at the current maximum.
1338
+ */
1339
+ const trackBuild = async (slug: string, resumeSeq?: number): Promise<boolean> => {
1340
+ if (streams.has(slug)) return true
1341
+ const record = await store.getBuild(slug)
1342
+ if (record === null) return false
1343
+ if (resumeSeq !== undefined && store.getStreamSeed)
1344
+ await store.getStreamSeed({ kind: 'build', slug }, resumeSeq)
1345
+ const current = await readBuildStreamSeed(store, slug)
1346
+ const seed =
1347
+ resumeSeq === undefined
1348
+ ? current.value
1349
+ : await historicalBuildState(store, slug, resumeSeq, current)
1350
+ const stream: BuildStream = {
1351
+ kind: 'build',
1352
+ slug,
1353
+ named: slugs.includes(slug),
1354
+ seed,
1355
+ lastSeq: resumeSeq ?? current.cursor,
1356
+ status: buildReducer.finish(current.value.build).status,
1357
+ backlog: [],
1358
+ record,
1359
+ }
1360
+ streams.set(slug, stream)
1361
+ positions[slug] = stream.lastSeq
1362
+ if (resumeSeq === undefined || resumedCursor?.deliveredAttention === undefined)
1363
+ baselineMerge(slug, seed)
1364
+ if (resumeSeq !== undefined) {
1365
+ const backlog = await readBuildRange(store, slug, resumeSeq)
1366
+ for (const [index, event] of backlog.entries()) {
1367
+ if (halted()) {
1368
+ if (!stop) stream.backlog = backlog.slice(index)
1369
+ break
1370
+ }
1371
+ processBuildEvent(stream, event)
1372
+ }
1039
1373
  }
1374
+ checkConsent(stream)
1375
+ // A restart between an event record and its merge-gate observation
1376
+ // must not lose the observation; the identity deduplicates it.
1377
+ if (feed !== undefined && resumeSeq !== undefined)
1378
+ checkMergeDecision(stream, buildReducer.finish(stream.seed.build))
1379
+ return true
1380
+ }
1040
1381
 
1041
- /**
1042
- * Register a build stream over the full event prefix. `resumeSeq` (a
1043
- * cursor position) additionally emits every matching event after it —
1044
- * the backlog that landed while no watch was running. A baseline (the
1045
- * default) replays nothing: the position starts at the current maximum.
1046
- */
1047
- const trackBuild = async (slug: string, resumeSeq?: number): Promise<boolean> => {
1048
- if (streams.has(slug)) return true
1049
- const record = await store.getBuild(slug)
1050
- if (record === null) return false
1051
- if (resumeSeq !== undefined && store.getStreamSeed)
1052
- await store.getStreamSeed({ kind: 'build', slug }, resumeSeq)
1053
- const current = await readBuildStreamSeed(store, slug)
1054
- const seed =
1055
- resumeSeq === undefined
1056
- ? current.value
1057
- : await historicalBuildState(store, slug, resumeSeq, current)
1382
+ /** Builds discovery read in full and found terminal; never re-read. */
1383
+ const retired = new Set<string>()
1384
+
1385
+ /**
1386
+ * No-slug membership: every nonterminal build of this repository joins
1387
+ * the watch, baselined at its current maximum so no history replays. A
1388
+ * build discovered while nonterminal stays tracked even after it turns
1389
+ * terminal. Cursor-resumed and named streams are never re-baselined.
1390
+ *
1391
+ * Throws on a failed read — never swallows it: the poll loop's tick
1392
+ * catches and reports the failure once on stderr, and the initial scan
1393
+ * turns it into the friendly startup error. Streams discovered before
1394
+ * the throw stay tracked, so the retry neither duplicates nor skips.
1395
+ */
1396
+ const discoverBuilds = async (): Promise<void> => {
1397
+ const digests = await readBuildDigests(store, repo)
1398
+ for (const record of (await store.listBuilds()).filter(mine)) {
1399
+ if (streams.has(record.slug) || retired.has(record.slug)) continue
1400
+ const digest = digests.get(record.slug)
1401
+ if (digest !== undefined && digest.terminal !== undefined) continue
1402
+ const current = await readBuildStreamSeed(store, record.slug)
1403
+ const status = buildReducer.finish(current.value.build).status
1404
+ if (!NONTERMINAL_STATUSES.includes(status)) {
1405
+ // Terminal is permanent (reduceBuild never clears it): a legacy
1406
+ // record the digest cannot retire is read once, not every pass.
1407
+ retired.add(record.slug)
1408
+ continue
1409
+ }
1058
1410
  const stream: BuildStream = {
1059
1411
  kind: 'build',
1060
- slug,
1061
- named: slugs.includes(slug),
1062
- seed,
1063
- lastSeq: resumeSeq ?? current.cursor,
1064
- status: buildReducer.finish(current.value.build).status,
1065
- }
1066
- streams.set(slug, stream)
1067
- positions[slug] = stream.lastSeq
1068
- if (resumeSeq === undefined || resumedCursor?.deliveredAttention === undefined)
1069
- baselineMerge(slug, seed)
1070
- if (resumeSeq !== undefined) {
1071
- for (const event of await readBuildRange(store, slug, resumeSeq)) {
1072
- processBuildEvent(stream, event)
1073
- if (stop) break
1074
- }
1412
+ slug: record.slug,
1413
+ named: false,
1414
+ seed: current.value,
1415
+ lastSeq: current.cursor,
1416
+ status,
1417
+ backlog: [],
1075
1418
  }
1419
+ streams.set(record.slug, stream)
1420
+ baselineMerge(record.slug, current.value)
1421
+ positions[record.slug] = stream.lastSeq
1076
1422
  checkConsent(stream)
1077
- return true
1423
+ if (stop) break
1078
1424
  }
1425
+ }
1079
1426
 
1080
- /** Builds discovery read in full and found terminal; never re-read. */
1081
- const retired = new Set<string>()
1082
-
1083
- /**
1084
- * No-slug membership: every nonterminal build of this repository joins
1085
- * the watch, baselined at its current maximum so no history replays. A
1086
- * build discovered while nonterminal stays tracked even after it turns
1087
- * terminal. Cursor-resumed and named streams are never re-baselined.
1088
- *
1089
- * Throws on a failed read — never swallows it: the poll loop's tick
1090
- * catches and reports the failure once on stderr, and the initial scan
1091
- * turns it into the friendly startup error. Streams discovered before
1092
- * the throw stay tracked, so the retry neither duplicates nor skips.
1093
- */
1094
- const discoverBuilds = async (): Promise<void> => {
1095
- const digests = await readBuildDigests(store, repo)
1096
- for (const record of (await store.listBuilds()).filter(mine)) {
1097
- if (streams.has(record.slug) || retired.has(record.slug)) continue
1098
- const digest = digests.get(record.slug)
1099
- if (digest !== undefined && digest.terminal !== undefined) continue
1100
- const current = await readBuildStreamSeed(store, record.slug)
1101
- const status = buildReducer.finish(current.value.build).status
1102
- if (!NONTERMINAL_STATUSES.includes(status)) {
1103
- // Terminal is permanent (reduceBuild never clears it): a legacy
1104
- // record the digest cannot retire is read once, not every pass.
1105
- retired.add(record.slug)
1106
- continue
1107
- }
1108
- const stream: BuildStream = {
1109
- kind: 'build',
1110
- slug: record.slug,
1111
- named: false,
1112
- seed: current.value,
1113
- lastSeq: current.cursor,
1114
- status,
1115
- }
1116
- streams.set(record.slug, stream)
1117
- baselineMerge(record.slug, current.value)
1118
- positions[record.slug] = stream.lastSeq
1119
- checkConsent(stream)
1120
- if (stop) break
1121
- }
1427
+ /**
1428
+ * Feed discovery, run for every repository event before it is
1429
+ * processed, so the journal position passes an announcement only once
1430
+ * its build is tracked. A build resolved `owned` after this feed's
1431
+ * position replays from seq 0 whatever its status now; one announced
1432
+ * before it is in the cursor already or was drained and retired.
1433
+ * Depends on ticket preparation journaling around every createBuild.
1434
+ */
1435
+ const announce = async (event: RepositoryEvent): Promise<void> => {
1436
+ if (feed === undefined) return
1437
+ if (event.type === 'ticket-preparation.creation-selected') {
1438
+ preparing.set(event.payload.attempt, {
1439
+ slug: event.payload.slug,
1440
+ ...(event.payload.creationKey !== undefined
1441
+ ? { creationKey: event.payload.creationKey }
1442
+ : {}),
1443
+ })
1444
+ return
1122
1445
  }
1123
-
1124
- const trackRepository = async (): Promise<boolean> => {
1125
- const resumeSeq = sinceStreams[REPO_STREAM_KEY]
1126
- const stream: RepositoryStream = { kind: 'repo', lastSeq: resumeSeq ?? 0 }
1127
- streams.set(REPO_STREAM_KEY, stream)
1128
- positions[REPO_STREAM_KEY] = stream.lastSeq
1129
- try {
1130
- if ((await store.getRepo(repo)) !== null) {
1131
- if (resumeSeq !== undefined && store.getStreamSeed)
1132
- await store.getStreamSeed({ kind: 'repo', repo }, resumeSeq)
1133
- const current = await readRepositoryAttention(store, repo)
1134
- const baseline = resumeSeq ?? current.cursor
1135
- const seed =
1136
- resumeSeq === undefined
1137
- ? current.value
1138
- : await historicalRepositoryAttention(store, repo, resumeSeq, current)
1139
- repositoryAttention = new RepositoryAttention(seed)
1140
- attentionInitialized = true
1141
- stream.lastSeq = baseline
1142
- positions[REPO_STREAM_KEY] = baseline
1143
- if (resumeSeq !== undefined) {
1144
- for (const event of await store.getRepoEvents(repo, baseline)) {
1145
- if (stop) break
1146
- processRepositoryEvent(stream, event)
1147
- }
1148
- }
1149
- if (!stop) checkPersistence()
1150
- } else attentionInitialized = true
1151
- return true
1152
- } catch (error) {
1153
- if (isTerminalEventReadError(error)) throw error
1154
- if (error instanceof ReducerValueIncompatibilityError) throw error
1155
- return false
1446
+ if (event.type !== 'ticket-preparation.resolved') return
1447
+ const { attempt } = event.payload
1448
+ if (event.payload.outcome === 'owned') {
1449
+ const entry = preparing.get(attempt)
1450
+ const slug =
1451
+ entry === undefined ? undefined : await resolveAnnouncedBuild(store, repo, entry)
1452
+ if (slug === undefined) await feed.unresolved(unresolvedAnnouncement(attempt))
1453
+ else if (!streams.has(slug) && !retired.has(slug)) {
1454
+ if (!(await trackBuild(slug, 0))) await feed.unresolved(unresolvedAnnouncement(attempt))
1156
1455
  }
1157
1456
  }
1457
+ preparing.delete(attempt)
1458
+ }
1158
1459
 
1159
- const pollBuild = async (
1160
- stream: BuildStream,
1161
- readOpts?: RemotePollReadOpts,
1162
- ): Promise<boolean> => {
1163
- const fresh = await readBuildRange(store, stream.slug, stream.lastSeq, readOpts)
1164
- for (const event of fresh) {
1165
- if (stop) break
1166
- processBuildEvent(stream, event)
1167
- if (stop) break
1168
- }
1169
- if (fresh.length > 0 && !stop) {
1170
- stream.status = buildReducer.finish(stream.seed.build).status
1460
+ /** The build a build-scoped attention identity belongs to, if any. */
1461
+ const identityBuild = (identity: string): string | undefined => {
1462
+ if (!identity.startsWith('[')) return undefined
1463
+ const value = JSON.parse(identity) as unknown[]
1464
+ return value.length === 2 ? String(value[0]) : String(value[1])
1465
+ }
1466
+
1467
+ /** Feed only: a terminal build whose execution has settled leaves the
1468
+ * cursor, so cursor size and pass cost follow active builds. */
1469
+ const retireSettled = async (): Promise<void> => {
1470
+ for (const stream of [...streams.values()]) {
1471
+ if (stop) return
1472
+ if (stream.kind !== 'build' || stream.named || stream.backlog.length > 0) continue
1473
+ if (!TERMINAL_STATUSES.includes(stream.status)) continue
1474
+ const record = stream.record ?? (await store.getBuild(stream.slug))
1475
+ if (record !== null) {
1476
+ const digest = (
1477
+ await readPersistedBuildDigests(store, repo, [{ ...record, repo }])
1478
+ ).get(stream.slug)
1479
+ if (digest === undefined || hasWork(digest)) continue
1171
1480
  }
1172
- return true
1481
+ streams.delete(stream.slug)
1482
+ delete positions[stream.slug]
1483
+ retired.add(stream.slug)
1484
+ for (const identity of [...deliveredAttention])
1485
+ if (identityBuild(identity) === stream.slug) deliveredAttention.delete(identity)
1173
1486
  }
1487
+ const repositoryIdentities = [...deliveredAttention].filter(
1488
+ (identity) => identityBuild(identity) === undefined,
1489
+ )
1490
+ for (const identity of repositoryIdentities.slice(
1491
+ 0,
1492
+ Math.max(0, repositoryIdentities.length - FEED_REPOSITORY_IDENTITY_CAP),
1493
+ ))
1494
+ deliveredAttention.delete(identity)
1495
+ for (const run of [...lostRuns].slice(
1496
+ 0,
1497
+ Math.max(0, lostRuns.size - FEED_REPOSITORY_IDENTITY_CAP),
1498
+ ))
1499
+ lostRuns.delete(run)
1500
+ }
1174
1501
 
1175
- let repositoryQueue = Promise.resolve()
1176
- let repositoryInitialization: Promise<void> | undefined
1177
- const pollRepository = async (
1178
- stream: RepositoryStream,
1179
- readOpts?: RemotePollReadOpts,
1180
- ): Promise<boolean> => {
1181
- // A repository row may be created mid-watch by the first dispatch.
1182
- if ((await store.getRepo(repo)) === null) return true
1183
- if (!attentionInitialized) {
1184
- repositoryInitialization ??= (async () => {
1185
- const resumeSeq = sinceStreams[REPO_STREAM_KEY]
1186
- if (resumeSeq !== undefined && store.getStreamSeed)
1187
- await store.getStreamSeed({ kind: 'repo', repo }, resumeSeq)
1188
- const current = await readRepositoryAttention(store, repo)
1189
- const baseline = resumeSeq ?? current.cursor
1190
- const seed =
1191
- resumeSeq === undefined
1192
- ? current.value
1193
- : await historicalRepositoryAttention(store, repo, resumeSeq, current)
1194
- repositoryAttention = new RepositoryAttention(seed)
1195
- stream.lastSeq = baseline
1196
- positions[REPO_STREAM_KEY] = baseline
1197
- attentionInitialized = true
1198
- })()
1199
- try {
1200
- await repositoryInitialization
1201
- } catch (error) {
1202
- if (isTerminalEventReadError(error)) throw error
1203
- repositoryInitialization = undefined
1204
- throw error
1205
- }
1206
- }
1207
- const fresh = await store.getRepoEvents(repo, stream.lastSeq, readOpts)
1208
- const apply = repositoryQueue.then(() => {
1209
- for (const event of fresh) {
1210
- if (stop) break
1211
- if (event.seq <= stream.lastSeq) continue
1212
- processRepositoryEvent(stream, event)
1502
+ const trackRepository = async (): Promise<boolean> => {
1503
+ const resumeSeq = sinceStreams[REPO_STREAM_KEY]
1504
+ const stream: RepositoryStream = { kind: 'repo', lastSeq: resumeSeq ?? 0, backlog: [] }
1505
+ streams.set(REPO_STREAM_KEY, stream)
1506
+ positions[REPO_STREAM_KEY] = stream.lastSeq
1507
+ try {
1508
+ if ((await store.getRepo(repo)) !== null) {
1509
+ if (resumeSeq !== undefined && store.getStreamSeed)
1510
+ await store.getStreamSeed({ kind: 'repo', repo }, resumeSeq)
1511
+ const current = await readRepositoryAttention(store, repo)
1512
+ const baseline = resumeSeq ?? current.cursor
1513
+ const seed =
1514
+ resumeSeq === undefined
1515
+ ? current.value
1516
+ : await historicalRepositoryAttention(store, repo, resumeSeq, current)
1517
+ repositoryAttention = new RepositoryAttention(seed)
1518
+ attentionInitialized = true
1519
+ stream.lastSeq = baseline
1520
+ positions[REPO_STREAM_KEY] = baseline
1521
+ if (resumeSeq !== undefined) {
1522
+ const backlog = await store.getRepoEvents(repo, baseline)
1523
+ for (const [index, event] of backlog.entries()) {
1524
+ if (halted()) {
1525
+ if (!stop) stream.backlog = backlog.slice(index)
1526
+ break
1527
+ }
1528
+ if (feed !== undefined) await announce(event)
1529
+ processRepositoryEvent(stream, event)
1530
+ }
1213
1531
  }
1214
1532
  if (!stop) checkPersistence()
1215
- })
1216
- repositoryQueue = apply.catch(() => {})
1217
- await apply
1533
+ } else attentionInitialized = true
1218
1534
  return true
1535
+ } catch (error) {
1536
+ if (isTerminalEventReadError(error)) throw error
1537
+ if (error instanceof ReducerValueIncompatibilityError) throw error
1538
+ return false
1219
1539
  }
1540
+ }
1220
1541
 
1221
- const namedAllTerminal = (): boolean => {
1222
- if (slugs.length === 0) return false
1223
- for (const slug of slugs) {
1224
- const stream = streams.get(slug)
1225
- if (stream === undefined || stream.kind !== 'build') return false
1226
- if (!TERMINAL_STATUSES.includes(stream.status)) return false
1542
+ const pollBuild = async (
1543
+ stream: BuildStream,
1544
+ readOpts?: RemotePollReadOpts,
1545
+ ): Promise<boolean> => {
1546
+ const fresh =
1547
+ stream.backlog.length > 0
1548
+ ? stream.backlog
1549
+ : await readBuildRange(store, stream.slug, stream.lastSeq, readOpts)
1550
+ stream.backlog = []
1551
+ for (const [index, event] of fresh.entries()) {
1552
+ if (halted()) {
1553
+ if (!stop) stream.backlog = fresh.slice(index)
1554
+ break
1227
1555
  }
1228
- return true
1556
+ processBuildEvent(stream, event)
1557
+ if (stop) break
1558
+ }
1559
+ if (fresh.length > 0 && !stop) {
1560
+ stream.status = buildReducer.finish(stream.seed.build).status
1229
1561
  }
1562
+ return true
1563
+ }
1230
1564
 
1231
- // One streak for the whole local loop — the same lifetime the shared
1232
- // reported flag had before per-source streaks: a persistent read
1233
- // failure is reported once, and a fully-successful cycle re-arms it.
1234
- const tickStreak = makeFailureStreak('watch', opts.stderr)
1235
-
1236
- const tick = async (): Promise<void> => {
1237
- let allReadsOk = true
1238
- if (slugs.length === 0) {
1239
- try {
1240
- await discoverBuilds()
1241
- } catch (error) {
1242
- if (isTerminalEventReadError(error)) throw error
1243
- allReadsOk = false
1244
- tickStreak.onFailure(error)
1245
- }
1246
- }
1247
- for (const stream of [...streams.values()]) {
1248
- if (stop) return
1249
- try {
1250
- if (stream.kind === 'build') await pollBuild(stream)
1251
- else await pollRepository(stream)
1252
- } catch (error) {
1253
- if (isTerminalEventReadError(error)) throw error
1254
- allReadsOk = false
1255
- tickStreak.onFailure(error)
1256
- }
1565
+ let repositoryQueue = Promise.resolve()
1566
+ let repositoryInitialization: Promise<void> | undefined
1567
+ const pollRepository = async (
1568
+ stream: RepositoryStream,
1569
+ readOpts?: RemotePollReadOpts,
1570
+ ): Promise<boolean> => {
1571
+ // A repository row may be created mid-watch by the first dispatch.
1572
+ if ((await store.getRepo(repo)) === null) return true
1573
+ if (!attentionInitialized) {
1574
+ repositoryInitialization ??= (async () => {
1575
+ const resumeSeq = sinceStreams[REPO_STREAM_KEY]
1576
+ if (resumeSeq !== undefined && store.getStreamSeed)
1577
+ await store.getStreamSeed({ kind: 'repo', repo }, resumeSeq)
1578
+ const current = await readRepositoryAttention(store, repo)
1579
+ const baseline = resumeSeq ?? current.cursor
1580
+ const seed =
1581
+ resumeSeq === undefined
1582
+ ? current.value
1583
+ : await historicalRepositoryAttention(store, repo, resumeSeq, current)
1584
+ repositoryAttention = new RepositoryAttention(seed)
1585
+ stream.lastSeq = baseline
1586
+ positions[REPO_STREAM_KEY] = baseline
1587
+ attentionInitialized = true
1588
+ })()
1589
+ try {
1590
+ await repositoryInitialization
1591
+ } catch (error) {
1592
+ if (isTerminalEventReadError(error)) throw error
1593
+ repositoryInitialization = undefined
1594
+ throw error
1257
1595
  }
1258
- if (allReadsOk) {
1259
- try {
1260
- await checkLiveness()
1261
- tickStreak.onSuccess()
1262
- } catch (error) {
1263
- if (isTerminalEventReadError(error)) throw error
1264
- tickStreak.onFailure(error)
1596
+ }
1597
+ const fresh =
1598
+ stream.backlog.length > 0
1599
+ ? stream.backlog
1600
+ : await store.getRepoEvents(repo, stream.lastSeq, readOpts)
1601
+ stream.backlog = []
1602
+ const apply = repositoryQueue.then(async () => {
1603
+ for (const [index, event] of fresh.entries()) {
1604
+ if (halted()) {
1605
+ if (!stop) stream.backlog = fresh.slice(index)
1606
+ break
1265
1607
  }
1608
+ if (event.seq <= stream.lastSeq) continue
1609
+ if (feed !== undefined) await announce(event)
1610
+ processRepositoryEvent(stream, event)
1266
1611
  }
1267
- }
1612
+ if (!stop) checkPersistence()
1613
+ })
1614
+ repositoryQueue = apply.catch(() => {})
1615
+ await apply
1616
+ return true
1617
+ }
1268
1618
 
1269
- // ── Initial scan ──
1270
- // Named slugs are validated (and must belong to this repository) before
1271
- // any record is emitted: an unknown slug is an error, full stop.
1619
+ const namedAllTerminal = (): boolean => {
1620
+ if (slugs.length === 0) return false
1272
1621
  for (const slug of slugs) {
1273
- const record = await store.getBuild(slug)
1274
- if (record === null) {
1275
- throw new Error(
1276
- `no build "${slug}" in this store — run 'ab builds --all' to list ` +
1277
- "this repo's builds, or pass --store <ref> if it lives in another store",
1278
- )
1279
- }
1280
- if (!(await buildInRepository(record, checkout, exec))) {
1281
- throw new Error(`build "${slug}" belongs to repository "${record.repo}", not "${repo}"`)
1282
- }
1622
+ const stream = streams.get(slug)
1623
+ if (stream === undefined || stream.kind !== 'build') return false
1624
+ if (!TERMINAL_STATUSES.includes(stream.status)) return false
1283
1625
  }
1284
- for (const slug of slugs) await trackBuild(slug, sinceStreams[slug])
1285
- // Cursor streams that are no longer named resume anyway: finishing
1286
- // their backlog is what makes a resumed watch lossless.
1287
- for (const key of Object.keys(sinceStreams)) {
1288
- if (key === REPO_STREAM_KEY) continue
1289
- await trackBuild(key, sinceStreams[key])
1290
- if (stop) break
1626
+ return true
1627
+ }
1628
+
1629
+ // One streak for the whole local loop — the same lifetime the shared
1630
+ // reported flag had before per-source streaks: a persistent read
1631
+ // failure is reported once, and a fully-successful cycle re-arms it.
1632
+ const tickStreak = makeFailureStreak('watch', opts.stderr)
1633
+
1634
+ const tick = async (): Promise<boolean> => {
1635
+ let allReadsOk = true
1636
+ if (slugs.length === 0 && feed === undefined) {
1637
+ try {
1638
+ await discoverBuilds()
1639
+ } catch (error) {
1640
+ if (isTerminalEventReadError(error)) throw error
1641
+ allReadsOk = false
1642
+ tickStreak.onFailure(error)
1643
+ }
1291
1644
  }
1292
- if (followRepository) {
1293
- if (!(await trackRepository())) {
1294
- makeFailureStreak('watch', opts.stderr).onFailure(
1295
- new Error(`could not read the repository journal for "${repo}"`),
1296
- )
1645
+ for (const stream of [...streams.values()]) {
1646
+ if (stop) return allReadsOk
1647
+ if (feed !== undefined && halted()) break
1648
+ try {
1649
+ if (stream.kind === 'build') await pollBuild(stream)
1650
+ else await pollRepository(stream)
1651
+ } catch (error) {
1652
+ if (isTerminalEventReadError(error)) throw error
1653
+ allReadsOk = false
1654
+ tickStreak.onFailure(error)
1297
1655
  }
1298
1656
  }
1299
- if (!repository && slugs.length === 0) {
1300
- // Membership discovery also baselines the default watch; a failed
1301
- // discovery here is fatal — nothing has started yet.
1657
+ if (feed !== undefined && allReadsOk) {
1302
1658
  try {
1303
- await discoverBuilds()
1659
+ await retireSettled()
1304
1660
  } catch (error) {
1305
1661
  if (isTerminalEventReadError(error)) throw error
1306
- const message = error instanceof Error ? error.message : String(error)
1307
- throw new Error(`could not list builds in this store (${message})`)
1662
+ allReadsOk = false
1663
+ tickStreak.onFailure(error)
1308
1664
  }
1309
1665
  }
1310
-
1311
- if (followRepository && !stop) {
1666
+ if (allReadsOk) {
1312
1667
  try {
1313
1668
  await checkLiveness()
1669
+ tickStreak.onSuccess()
1314
1670
  } catch (error) {
1315
1671
  if (isTerminalEventReadError(error)) throw error
1672
+ allReadsOk = false
1316
1673
  tickStreak.onFailure(error)
1317
1674
  }
1318
1675
  }
1319
- // ── The poll loop ──
1320
- const deadline = timeoutMs === 0 ? Number.POSITIVE_INFINITY : now().getTime() + timeoutMs
1321
- const aborted = (): boolean => opts.signal?.aborted === true
1322
-
1323
- if (!isRemoteStoreRef(storeRef)) {
1324
- // Local cadence: one sequential tick per interval.
1325
- while (!stop) {
1326
- if (aborted() || now().getTime() >= deadline || namedAllTerminal()) break
1327
- await sleep(interval, opts.signal)
1328
- if (aborted()) break
1329
- await tick()
1330
- }
1331
- } else {
1332
- // Remote cadence (AUT-334): one long-poll task per tracked stream,
1333
- // running concurrently — a quiet stream keeps one held request in
1334
- // flight, so an appended event arrives within about a second instead
1335
- // of at the next interval tick. Gap-fill spaces each stream's request
1336
- // starts at least `interval` apart (elapsed request time counts
1337
- // toward the gap), so a server that answers immediately still sees
1338
- // today's request rate. Discovery keeps its interval cadence.
1339
- // Pre-launch guard mirrors the local loop's top-of-cycle checks: an
1340
- // already-terminal named set, an elapsed deadline, or an abort ends
1341
- // the watch before any request.
1342
- // Every stop is prompt: an external abort, a tripped --count, an
1343
- // all-terminal named set, or an elapsed --timeout cancels the
1344
- // in-flight held reads (via `requestStop`) and wakes the gap sleeps
1345
- // (via the runner's stop controller) instead of waiting out a full
1346
- // hold. The held read's own bound is additionally capped at the
1347
- // watch's remaining time budget, so a hold can never outlive the
1348
- // deadline.
1349
- const shouldStop = stop || aborted() || now().getTime() >= deadline || namedAllTerminal()
1350
- const remoteRunner = createRemotePollRunner({
1351
- command: 'watch',
1352
- stderr: opts.stderr,
1353
- now,
1354
- sleep,
1355
- intervalMs: interval,
1356
- deadlineMs: deadline,
1357
- aborted,
1358
- shouldStop: () => aborted() || now().getTime() >= deadline || namedAllTerminal(),
1359
- // A task's terminal endCheck stops the runner from the inside; the
1360
- // command's `stop` flag must trip with it — pollBuild and
1361
- // pollRepository gate their batch loops on that flag
1362
- // (`if (stop) break`), so a sibling task whose held read has
1363
- // already resolved stops delivering its batch instead of draining
1364
- // it, exactly as the pre-extraction command-scoped `requestStop`
1365
- // (which set `stop` on every path) made it do (f_42263f38).
1366
- onStop: (): void => {
1367
- stop = true
1368
- },
1369
- // Quiesce, not the runner's one-shot snapshot: a stream the
1370
- // discovery task registers while drain is awaiting must have its
1371
- // first held read awaited before the final cursor is encoded, or a
1372
- // mid-discovery registration's emission lands after the cursor and
1373
- // the next run replays it (the gap widened from a scheduling race
1374
- // to a deterministic miss when discovery's digest read added one
1375
- // await before the per-build reads — AUT-545). The snapshot
1376
- // semantics the runner documents remain covered by its own tests.
1377
- drain: 'quiesce',
1378
- })
1379
- runner = remoteRunner
1380
-
1381
- const launch = (stream: Stream): void => {
1382
- const key = stream.kind === 'build' ? stream.slug : REPO_STREAM_KEY
1383
- remoteRunner.launch(
1384
- key,
1385
- (readOpts) =>
1386
- stream.kind === 'build'
1387
- ? pollBuild(stream, readOpts)
1388
- : pollRepository(stream, readOpts),
1389
- () => namedAllTerminal(),
1390
- )
1391
- }
1676
+ return allReadsOk
1677
+ }
1392
1678
 
1393
- // An external abort (SIGINT) is a stop like any other: it cancels
1394
- // the in-flight held reads and wakes the gap sleeps.
1395
- opts.signal?.addEventListener('abort', requestStop, { once: true })
1396
-
1397
- for (const stream of streams.values()) if (!shouldStop) launch(stream)
1398
-
1399
- if ((slugs.length === 0 || followRepository) && !shouldStop) {
1400
- void remoteRunner.runDiscovery({
1401
- step: async (): Promise<void> => {
1402
- if (slugs.length === 0) await discoverBuilds()
1403
- const repositoryStream = streams.get(REPO_STREAM_KEY)
1404
- if (repositoryStream?.kind === 'repo' && !stop)
1405
- await pollRepository(repositoryStream)
1406
- await checkLiveness()
1407
- },
1408
- // Unconditional, after the catch — exactly where the inline
1409
- // launch loop ran: streams registered before a mid-discovery
1410
- // throw still get tasks whose polls then run independently.
1411
- launchPending: (): void => {
1412
- for (const stream of streams.values()) launch(stream)
1413
- },
1414
- })
1415
- }
1679
+ // ── Initial scan ──
1680
+ // Named slugs are validated (and must belong to this repository) before
1681
+ // any record is emitted: an unknown slug is an error, full stop.
1682
+ for (const slug of slugs) {
1683
+ const record = await store.getBuild(slug)
1684
+ if (record === null) {
1685
+ throw new Error(
1686
+ `no build "${slug}" in this store — run 'ab builds --all' to list ` +
1687
+ "this repo's builds, or pass --store <ref> if it lives in another store",
1688
+ )
1689
+ }
1690
+ if (!(await buildInRepository(record, checkout, exec))) {
1691
+ throw new Error(`build "${slug}" belongs to repository "${record.repo}", not "${repo}"`)
1692
+ }
1693
+ }
1694
+ for (const slug of slugs) await trackBuild(slug, sinceStreams[slug])
1695
+ // Cursor streams that are no longer named resume anyway: finishing
1696
+ // their backlog is what makes a resumed watch lossless.
1697
+ // A feed retries a failed read on the next pass even when nothing
1698
+ // moved the change position.
1699
+ let retryFull = false
1700
+ for (const key of Object.keys(sinceStreams)) {
1701
+ if (key === REPO_STREAM_KEY) continue
1702
+ if (!(await trackBuild(key, sinceStreams[key])) && feed !== undefined) delete positions[key]
1703
+ if (stop) break
1704
+ }
1705
+ if (followRepository) {
1706
+ if (!(await trackRepository())) {
1707
+ retryFull = true
1708
+ makeFailureStreak('watch', opts.stderr).onFailure(
1709
+ new Error(`could not read the repository journal for "${repo}"`),
1710
+ )
1711
+ }
1712
+ }
1713
+ if (!repository && slugs.length === 0 && feed === undefined) {
1714
+ // Membership discovery also baselines the default watch; a failed
1715
+ // discovery here is fatal — nothing has started yet.
1716
+ try {
1717
+ await discoverBuilds()
1718
+ } catch (error) {
1719
+ if (isTerminalEventReadError(error)) throw error
1720
+ const message = error instanceof Error ? error.message : String(error)
1721
+ throw new Error(`could not list builds in this store (${message})`)
1722
+ }
1723
+ }
1416
1724
 
1417
- await remoteRunner.drain()
1418
- opts.signal?.removeEventListener('abort', requestStop)
1725
+ if (followRepository && !stop) {
1726
+ try {
1727
+ await checkLiveness()
1728
+ } catch (error) {
1729
+ if (isTerminalEventReadError(error)) throw error
1730
+ tickStreak.onFailure(error)
1731
+ }
1732
+ }
1733
+ // ── The poll loop ──
1734
+ const deadline = timeoutMs === 0 ? Number.POSITIVE_INFINITY : now().getTime() + timeoutMs
1735
+ const aborted = (): boolean => opts.signal?.aborted === true
1736
+
1737
+ if (feed !== undefined) {
1738
+ // Feed cadence: a full pass only when the shared change gate moved,
1739
+ // the last pass yielded to backpressure, or a read failed; otherwise
1740
+ // only the in-memory repository timers run. Zero reads while idle.
1741
+ if (!stop) feed.position?.(encodeCurrent())
1742
+ while (!stop) {
1743
+ if (aborted() || now().getTime() >= deadline) break
1744
+ await sleep(interval, opts.signal)
1745
+ if (aborted()) break
1746
+ const full = yieldedLastPass || retryFull || (await feed.changed())
1747
+ yieldedLastPass = false
1748
+ retryFull = false
1749
+ if (full) retryFull = !(await tick())
1750
+ else checkPersistence()
1751
+ if (!stop) feed.position?.(encodeCurrent())
1419
1752
  }
1753
+ } else if (!isRemoteStoreRef(storeRef)) {
1754
+ // Local cadence: one sequential tick per interval.
1755
+ while (!stop) {
1756
+ if (aborted() || now().getTime() >= deadline || namedAllTerminal()) break
1757
+ await sleep(interval, opts.signal)
1758
+ if (aborted()) break
1759
+ await tick()
1760
+ }
1761
+ } else {
1762
+ // Remote cadence (AUT-334): one long-poll task per tracked stream,
1763
+ // running concurrently — a quiet stream keeps one held request in
1764
+ // flight, so an appended event arrives within about a second instead
1765
+ // of at the next interval tick. Gap-fill spaces each stream's request
1766
+ // starts at least `interval` apart (elapsed request time counts
1767
+ // toward the gap), so a server that answers immediately still sees
1768
+ // today's request rate. Discovery keeps its interval cadence.
1769
+ // Pre-launch guard mirrors the local loop's top-of-cycle checks: an
1770
+ // already-terminal named set, an elapsed deadline, or an abort ends
1771
+ // the watch before any request.
1772
+ // Every stop is prompt: an external abort, a tripped --count, an
1773
+ // all-terminal named set, or an elapsed --timeout cancels the
1774
+ // in-flight held reads (via `requestStop`) and wakes the gap sleeps
1775
+ // (via the runner's stop controller) instead of waiting out a full
1776
+ // hold. The held read's own bound is additionally capped at the
1777
+ // watch's remaining time budget, so a hold can never outlive the
1778
+ // deadline.
1779
+ const shouldStop = stop || aborted() || now().getTime() >= deadline || namedAllTerminal()
1780
+ const remoteRunner = createRemotePollRunner({
1781
+ command: 'watch',
1782
+ stderr: opts.stderr,
1783
+ now,
1784
+ sleep,
1785
+ intervalMs: interval,
1786
+ deadlineMs: deadline,
1787
+ aborted,
1788
+ shouldStop: () => aborted() || now().getTime() >= deadline || namedAllTerminal(),
1789
+ // A task's terminal endCheck stops the runner from the inside; the
1790
+ // command's `stop` flag must trip with it — pollBuild and
1791
+ // pollRepository gate their batch loops on that flag
1792
+ // (`if (stop) break`), so a sibling task whose held read has
1793
+ // already resolved stops delivering its batch instead of draining
1794
+ // it, exactly as the pre-extraction command-scoped `requestStop`
1795
+ // (which set `stop` on every path) made it do (f_42263f38).
1796
+ onStop: (): void => {
1797
+ stop = true
1798
+ },
1799
+ // Quiesce, not the runner's one-shot snapshot: a stream the
1800
+ // discovery task registers while drain is awaiting must have its
1801
+ // first held read awaited before the final cursor is encoded, or a
1802
+ // mid-discovery registration's emission lands after the cursor and
1803
+ // the next run replays it (the gap widened from a scheduling race
1804
+ // to a deterministic miss when discovery's digest read added one
1805
+ // await before the per-build reads — AUT-545). The snapshot
1806
+ // semantics the runner documents remain covered by its own tests.
1807
+ drain: 'quiesce',
1808
+ })
1809
+ runner = remoteRunner
1810
+
1811
+ const launch = (stream: Stream): void => {
1812
+ const key = stream.kind === 'build' ? stream.slug : REPO_STREAM_KEY
1813
+ remoteRunner.launch(
1814
+ key,
1815
+ (readOpts) =>
1816
+ stream.kind === 'build'
1817
+ ? pollBuild(stream, readOpts)
1818
+ : pollRepository(stream, readOpts),
1819
+ () => namedAllTerminal(),
1820
+ )
1821
+ }
1822
+
1823
+ // An external abort (SIGINT) is a stop like any other: it cancels
1824
+ // the in-flight held reads and wakes the gap sleeps.
1825
+ opts.signal?.addEventListener('abort', requestStop, { once: true })
1826
+
1827
+ for (const stream of streams.values()) if (!shouldStop) launch(stream)
1420
1828
 
1421
- const finalCursor = countCursor ?? encodeCurrent()
1422
- // SIGTERM/HUP previously used the process default and could not emit a
1423
- // final cursor. SIGINT retains its existing orderly cursor output.
1424
- const outputClosed =
1425
- opts.signal?.aborted &&
1426
- ['SIGTERM', 'SIGHUP', 'EPIPE'].includes(String(opts.signal.reason))
1427
- if (opts.json === true && !outputClosed) {
1428
- opts.stdout(JSON.stringify({ cursor: finalCursor }))
1829
+ if ((slugs.length === 0 || followRepository) && !shouldStop) {
1830
+ void remoteRunner.runDiscovery({
1831
+ step: async (): Promise<void> => {
1832
+ if (slugs.length === 0) await discoverBuilds()
1833
+ const repositoryStream = streams.get(REPO_STREAM_KEY)
1834
+ if (repositoryStream?.kind === 'repo' && !stop) await pollRepository(repositoryStream)
1835
+ await checkLiveness()
1836
+ },
1837
+ // Unconditional, after the catch — exactly where the inline
1838
+ // launch loop ran: streams registered before a mid-discovery
1839
+ // throw still get tasks whose polls then run independently.
1840
+ launchPending: (): void => {
1841
+ for (const stream of streams.values()) launch(stream)
1842
+ },
1843
+ })
1429
1844
  }
1430
- await opts.flushStdout?.()
1431
- } finally {
1432
- heartbeatStop.abort()
1433
- await lifetime.limit(heartbeatTask ?? Promise.resolve())
1434
- if (operator && !lifetime.terminated) {
1435
- try {
1436
- await lifetime.renew()
1437
- } catch (error) {
1438
- if (!lifetime.terminated)
1439
- opts.stderr(`ab watch: final operator heartbeat failed (${String(error)})`)
1440
- }
1845
+
1846
+ await remoteRunner.drain()
1847
+ opts.signal?.removeEventListener('abort', requestStop)
1848
+ }
1849
+
1850
+ const finalCursor = countCursor ?? encodeCurrent()
1851
+ // SIGTERM/HUP previously used the process default and could not emit a
1852
+ // final cursor. SIGINT retains its existing orderly cursor output.
1853
+ const outputClosed =
1854
+ opts.signal?.aborted && ['SIGTERM', 'SIGHUP', 'EPIPE'].includes(String(opts.signal.reason))
1855
+ if (opts.json === true && !outputClosed && feed === undefined) {
1856
+ opts.stdout(JSON.stringify({ cursor: finalCursor }))
1857
+ }
1858
+ await opts.flushStdout?.()
1859
+ } finally {
1860
+ heartbeatStop.abort()
1861
+ await lifetime.limit(heartbeatTask ?? Promise.resolve())
1862
+ if (operator && !lifetime.terminated) {
1863
+ try {
1864
+ await lifetime.renew()
1865
+ } catch (error) {
1866
+ if (!lifetime.terminated)
1867
+ opts.stderr(`ab watch: final operator heartbeat failed (${String(error)})`)
1441
1868
  }
1442
- await lifetime.finish()
1443
1869
  }
1444
- }),
1870
+ await lifetime.finish()
1871
+ }
1872
+ }
1873
+ if (feed !== undefined) {
1874
+ try {
1875
+ await body(feed.context)
1876
+ } finally {
1877
+ await lifetime.finish()
1878
+ lifetime.close()
1879
+ }
1880
+ return
1881
+ }
1882
+ await withAmbientReadStore(
1883
+ {
1884
+ closeDeadline: lifetime.deadline.signal,
1885
+ targetRepo: opts.targetRepo,
1886
+ env: opts.env,
1887
+ exec: opts.exec,
1888
+ ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
1889
+ ...(opts.openStore !== undefined ? { openStore: opts.openStore } : {}),
1890
+ },
1891
+ lifetime.limitCallback((context: OpenedStoreContext) => body(context)),
1445
1892
  ).finally(async () => {
1446
1893
  await lifetime.finish()
1447
1894
  lifetime.close()