@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.
- package/README.md +6 -6
- package/SPEC.md +360 -229
- package/docs/answering-blocked-builds.md +2 -2
- package/docs/architecture.md +155 -45
- package/docs/assets/headline-wide.png +0 -0
- package/docs/builds.md +4 -4
- package/docs/cli.md +4 -4
- package/docs/configuration-overview.md +4 -4
- package/docs/configuration.md +245 -210
- package/docs/dispatcher-hosting.md +2 -2
- package/docs/dispatcher.md +1 -1
- package/docs/forges.md +5 -5
- package/docs/getting-started.md +2 -2
- package/docs/glossary.md +6 -6
- package/docs/hosted-dispatcher.md +6 -3
- package/docs/hosted-service.md +16 -5
- package/docs/integration-overview.md +15 -15
- package/docs/integration-tree.md +45 -38
- package/docs/integration.md +6 -6
- package/docs/mcp.md +16 -15
- package/docs/{landing-policy.md → merge-policy.md} +42 -24
- package/docs/migration-1.0.md +17 -13
- package/docs/operating.md +41 -18
- package/docs/operator-api.md +91 -15
- package/docs/operator-surfaces.md +8 -4
- package/docs/overview.md +3 -3
- package/docs/remote-store-protocol.md +76 -11
- package/docs/remote-ticket-protocol.md +1 -1
- package/docs/restacking.md +54 -15
- package/docs/setup.md +41 -6
- package/docs/skills.md +1 -1
- package/docs/spec-standard.md +6 -6
- package/docs/ticket-dependencies.md +7 -7
- package/docs/tickets.md +8 -2
- package/docs/troubleshooting.md +2 -2
- package/docs/upgrading.md +8 -3
- package/docs/verification.md +60 -14
- package/package.json +7 -5
- package/packages/core/src/cli/binary-direct.ts +13 -1
- package/packages/core/src/cli/binary-lifecycle.ts +65 -2
- package/packages/core/src/cli/build-control.ts +83 -28
- package/packages/core/src/cli/context.ts +81 -38
- package/packages/core/src/cli/dashboard/facts.ts +2 -1
- package/packages/core/src/cli/dashboard/integration-detail.ts +8 -8
- package/packages/core/src/cli/dashboard/integration-row.ts +40 -13
- package/packages/core/src/cli/dashboard/landing-display.ts +25 -0
- package/packages/core/src/cli/dashboard/model.ts +56 -33
- package/packages/core/src/cli/dashboard/poll.ts +9 -3
- package/packages/core/src/cli/dashboard/render.ts +59 -37
- package/packages/core/src/cli/dashboard/target-distance.ts +14 -0
- package/packages/core/src/cli/dashboard/tree.ts +3 -2
- package/packages/core/src/cli/dispatch-args.ts +1 -1
- package/packages/core/src/cli/dispatch-frontend.ts +6 -3
- package/packages/core/src/cli/dispatch.ts +35 -9
- package/packages/core/src/cli/env.ts +4 -0
- package/packages/core/src/cli/help.ts +30 -23
- package/packages/core/src/cli/main.ts +24 -8
- package/packages/core/src/cli/node-verification-provenance.ts +1 -97
- package/packages/core/src/cli/publication-settlement.ts +43 -20
- package/packages/core/src/cli/repository-status.ts +20 -9
- package/packages/core/src/cli/status.ts +42 -5
- package/packages/core/src/cli/store-opening.ts +6 -1
- package/packages/core/src/cli/terminal.ts +22 -1
- package/packages/core/src/cli/terminals.ts +14 -10
- package/packages/core/src/cli/upgrade-landing.ts +70 -30
- package/packages/core/src/cli/upgrade.ts +3 -1
- package/packages/core/src/cli/wait.ts +15 -7
- package/packages/core/src/cli/watch-lifetime.ts +111 -0
- package/packages/core/src/cli/watch.ts +634 -511
- package/packages/core/src/config/effective-artifact.fixture.ts +27 -0
- package/packages/core/src/config/effective-artifact.ts +13 -0
- package/packages/core/src/config/landing.ts +1 -1
- package/packages/core/src/config/load.ts +21 -1
- package/packages/core/src/config/pipeline-source.ts +28 -0
- package/packages/core/src/config/reference-metadata.ts +2 -0
- package/packages/core/src/config/reference.ts +22 -7
- package/packages/core/src/config/schema.ts +86 -162
- package/packages/core/src/context-directory.ts +26 -0
- package/packages/core/src/distribution-packaging.ts +26 -5
- package/packages/core/src/events/catalog.ts +10 -2
- package/packages/core/src/events/globs.ts +1 -1
- package/packages/core/src/events/payloads.ts +70 -1
- package/packages/core/src/events/policy.ts +7 -0
- package/packages/core/src/events/repository.ts +2 -4
- package/packages/core/src/events/sessions.ts +6 -6
- package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +571 -0
- package/packages/core/src/kernel/auto-merge.ts +2 -2
- package/packages/core/src/kernel/engine.ts +255 -26
- package/packages/core/src/kernel/generators/leaf-restack-log.ts +10 -0
- package/packages/core/src/kernel/integration-landing.ts +3 -3
- package/packages/core/src/kernel/integration-state.ts +27 -4
- package/packages/core/src/kernel/leaf-restack-state.ts +28 -3
- package/packages/core/src/kernel/log-index.ts +13 -1
- package/packages/core/src/kernel/node-landing.ts +8 -8
- package/packages/core/src/kernel/node-parent.ts +2 -2
- package/packages/core/src/kernel/node-restack-transaction.ts +1 -1
- package/packages/core/src/kernel/node-verification-context.ts +216 -0
- package/packages/core/src/kernel/phases.ts +1 -1
- package/packages/core/src/kernel/plan-verify-selection.ts +16 -0
- package/packages/core/src/kernel/publication-retry.ts +168 -0
- package/packages/core/src/kernel/reconcile-restack.ts +29 -1
- package/packages/core/src/kernel/reducer.ts +82 -5
- package/packages/core/src/kernel/target-distance.ts +45 -0
- package/packages/core/src/kernel/terminal-guard.ts +10 -1
- package/packages/core/src/kernel/verify-stage-state.ts +123 -0
- package/packages/core/src/kernel/verify-stages.ts +39 -0
- package/packages/core/src/ontology.ts +1 -0
- package/packages/core/src/operator/annotations.ts +6 -0
- package/packages/core/src/operator/control.ts +1 -1
- package/packages/core/src/operator/index.ts +1 -7
- package/packages/core/src/operator/landings.ts +5 -1
- package/packages/core/src/operator/presentation.ts +6 -1
- package/packages/core/src/operator/query.ts +14 -18
- package/packages/core/src/operator/registry.ts +17 -6
- package/packages/core/src/operator/sandbox-host.ts +64 -40
- package/packages/core/src/operator/sandbox.ts +3 -0
- package/packages/core/src/operator/ticket-source-backend.ts +3 -12
- package/packages/core/src/ports/forge/contract.ts +2 -2
- package/packages/core/src/ports/forge/git-rewrite.ts +25 -2
- package/packages/core/src/ports/forge/github-readiness.ts +2 -2
- package/packages/core/src/ports/forge/github.ts +26 -7
- package/packages/core/src/ports/forge/local-git.ts +4 -4
- package/packages/core/src/ports/forge/readiness.ts +1 -1
- package/packages/core/src/ports/forge-failure.ts +24 -0
- package/packages/core/src/ports/workspace/build-execution.ts +3 -1
- package/packages/core/src/ports/workspace/phase-scratch.ts +4 -3
- package/packages/core/src/ports/workspace/vercel-sandbox.ts +59 -39
- package/packages/core/src/processes/build-child.ts +6 -8
- package/packages/core/src/processes/build-execution-state.ts +8 -5
- package/packages/core/src/processes/build-runner.ts +522 -98
- package/packages/core/src/processes/dispatcher.ts +186 -101
- package/packages/core/src/processes/execution-no-progress.ts +8 -1
- package/packages/core/src/processes/phase-failure-budget.ts +1 -0
- package/packages/core/src/processes/publication-loss.ts +8 -2
- package/packages/core/src/processes/publication-state.ts +42 -4
- package/packages/core/src/processes/repo-view.ts +14 -0
- package/packages/core/src/processes/verify-cycle-config.ts +96 -0
- package/packages/core/src/{integration → scenarios}/harness.ts +330 -317
- package/packages/core/src/store/adapter.ts +1 -0
- package/packages/core/src/store/build-scope.ts +9 -0
- package/packages/core/src/store/contract.ts +113 -1
- package/packages/core/src/store/local/schema.ts +13 -0
- package/packages/core/src/store/local/store.ts +42 -0
- package/packages/core/src/store/memory.ts +47 -0
- package/packages/core/src/store/operator-presence.ts +21 -0
- package/packages/core/src/store/phase-session.ts +10 -0
- package/packages/core/src/store/reducer-value-shapes.json +5081 -4160
- package/packages/core/src/store/remote/client.ts +47 -1
- package/packages/core/src/store/remote/compatibility.ts +2 -0
- package/packages/core/src/store/remote/protocol.ts +4 -0
- package/packages/core/src/store/remote/version.ts +3 -1
- package/packages/core/src/store/retention.ts +2 -3
- package/packages/core/src/store/session-handle.ts +9 -0
- package/packages/core/src/store/streams/session-writer.ts +1 -1
- package/packages/core/src/store/types.ts +12 -2
- package/packages/core/src/testing/index.ts +11 -1
- package/packages/core/src/testing/temp-directories.ts +58 -0
- package/skills/code-review/SKILL.md +23 -9
- package/skills/finalize/SKILL.md +15 -7
- package/skills/guide/SKILL.md +253 -118
- package/skills/guide/references/integration-tree.md +45 -38
- package/skills/guide/references/{landing-policy.md → merge-policy.md} +42 -24
- package/skills/guide/references/migration-1.0.md +17 -13
- package/skills/guide/references/operator-api.md +91 -15
- package/skills/guide/references/remote-store-protocol.md +76 -11
- package/skills/guide/references/remote-ticket-protocol.md +1 -1
- package/skills/guide/references/restacking.md +54 -15
- package/skills/guide/references/setup.md +41 -6
- package/skills/guide/references/spec-standard.md +6 -6
- package/skills/guide/references/ticket-dependencies.md +7 -7
- package/skills/implement/SKILL.md +43 -17
- package/skills/operate/SKILL.md +117 -116
- package/skills/plan/SKILL.md +39 -13
- package/skills/plan-review/SKILL.md +15 -10
- package/skills/reconcile/SKILL.md +22 -3
- package/skills/spec/SKILL.md +19 -19
- package/skills/tickets/SKILL.md +9 -7
- package/templates/autobuild.toml +1 -1
- package/templates/hosted-service/package.json +2 -2
- package/packages/core/src/orchestrator/approvals.ts +0 -115
- package/packages/core/src/orchestrator/conversation.ts +0 -167
- package/packages/core/src/orchestrator/model.ts +0 -86
- package/packages/core/src/orchestrator/prompt.ts +0 -63
- package/packages/core/src/orchestrator/tools.ts +0 -117
- package/packages/core/src/orchestrator/turn-runner.ts +0 -457
- 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
|
|
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
|
|
21
|
-
*
|
|
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
|
-
*
|
|
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
|
-
/**
|
|
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.
|
|
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
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
const
|
|
651
|
-
let
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
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
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
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
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
)
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
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
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
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
|
-
|
|
767
|
-
|
|
768
|
-
|
|
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(
|
|
780
|
-
:
|
|
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
|
-
|
|
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
|
-
|
|
807
|
+
buildReducer.finish(stream.seed.build),
|
|
815
808
|
{ build: stream.slug },
|
|
816
|
-
|
|
809
|
+
consentIdentity(stream.slug, observation.position),
|
|
817
810
|
)
|
|
818
811
|
}
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
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
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
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
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
if (
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
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
|
|
902
|
-
named:
|
|
903
|
-
seed
|
|
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(
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
if (
|
|
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
|
-
|
|
939
|
-
|
|
966
|
+
}
|
|
967
|
+
checkConsent(stream)
|
|
940
968
|
return true
|
|
941
|
-
} catch {
|
|
942
|
-
return false
|
|
943
969
|
}
|
|
944
|
-
}
|
|
945
970
|
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
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
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
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
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
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
|
-
|
|
992
|
-
const
|
|
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
|
-
|
|
996
|
-
|
|
1053
|
+
processBuildEvent(stream, event)
|
|
1054
|
+
if (stop) break
|
|
997
1055
|
}
|
|
998
|
-
if (!stop)
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
}
|
|
1056
|
+
if (fresh.length > 0 && !stop) {
|
|
1057
|
+
stream.status = buildReducer.finish(stream.seed.build).status
|
|
1058
|
+
}
|
|
1059
|
+
return true
|
|
1060
|
+
}
|
|
1004
1061
|
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
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
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
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
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
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
|
-
|
|
1031
|
-
|
|
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
|
-
|
|
1034
|
-
else await pollRepository(stream)
|
|
1184
|
+
await discoverBuilds()
|
|
1035
1185
|
} catch (error) {
|
|
1036
|
-
|
|
1037
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
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
|
-
|
|
1092
|
-
|
|
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
|
-
|
|
1173
|
-
// the
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
if (
|
|
1179
|
-
|
|
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
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
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
|
}
|