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