@defrex/autobuild 1.4.0 → 1.4.2

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 CHANGED
@@ -26,7 +26,7 @@ From the repository you want built, install Autobuild as a development dependenc
26
26
  <!-- release-install:start -->
27
27
 
28
28
  ```sh
29
- bun add -d --exact @defrex/autobuild@1.4.0
29
+ bun add -d --exact @defrex/autobuild@1.4.2
30
30
  ```
31
31
 
32
32
  <!-- release-install:end -->
package/SPEC.md CHANGED
@@ -2874,7 +2874,11 @@ Repository tick telemetry is bounded mutable operational metadata, like leases.
2874
2874
  `beginRepoTick` persists the open boundary before unsafe work; `finishRepoTick`
2875
2875
  atomically replaces it with actual completion time and outcome and appends any
2876
2876
  validated tick boundaries. Both are fenced by the unexpired repository lease,
2877
- and neither renews it. Quiet completions advance telemetry without advancing the
2877
+ and neither renews it. Unchanged standing ticket counts and diagnostics do not publish
2878
+ tick pairs. Changes to those counts or diagnostics, per-tick activity, recovery from a
2879
+ failed tick, and due attention retries still publish. The last published diagnostics
2880
+ remain visible while lease-fenced completion telemetry advances independently of the
2881
+ journal cursor. Quiet completions advance telemetry without advancing the
2878
2882
  journal. Readers refresh telemetry independently of event cursors, correlate it
2879
2883
  by run, and merge with historical completions by actual time; heartbeat never
2880
2884
  stands in for tick completion. Telemetry survives lease release. Safe shutdown
@@ -3370,10 +3374,15 @@ It preserves unpublished branch commits and distinct detached producer candidate
3370
3374
  under immutable `refs/autobuild/archive/<build>/<sha>` refs, verifies their exact
3371
3375
  readback, and records `workspace.commits-preserved` before cleanup. Replacement
3372
3376
  provisioning restores those exact refs before starting an agent. Preservation
3373
- never advances the public build branch. A confirmed absent environment records
3374
- `workspace.commits-lost`, naming known candidates and explicitly noting that any
3375
- additional unpublished SHAs could not be inspected. Unknown fencing, inspection,
3376
- transport, or receipt-write outcomes leave the workspace and snapshots intact.
3377
+ never advances the public build branch. A confirmed absent environment, or one
3378
+ that exists without a provisioned checkout, records `workspace.commits-lost`,
3379
+ naming known candidates and explicitly noting that any additional unpublished
3380
+ SHAs could not be inspected. Unknown fencing, inspection, transport, or
3381
+ receipt-write outcomes leave the workspace and snapshots intact. A workspace
3382
+ flagged by `workspace.cleanup-required` is never launched into: the dispatcher
3383
+ releases it and provisions the next generation. A preservation or release
3384
+ failure is recorded against its build, as an infrastructure failure or janitor
3385
+ attention, and never stops the dispatcher from advancing other builds.
3377
3386
  Fencing is revalidated after restart; a saved receipt alone never authorizes
3378
3387
  cleanup of a newer execution. Current recovery notes are linked by the session
3379
3388
  manifest's `workspaceRecovery` field. Recovery notes apply to the next session
@@ -56,9 +56,10 @@ projection, plugin SDK, and reusable contract suites. The optional
56
56
  `packages/hosted-store-service` workspace composes the public remote-server
57
57
  surface with `packages/postgres-store`; the separate optional
58
58
  `packages/hosted-dispatcher` workspace owns the cron-driven hosted dispatcher
59
- (the `/api/dispatch` route driver, the deploy-time `pack-distribution` command,
60
- and the packed-distribution trace helper) and peers on both the core and the
61
- store service. The optional `packages/vercel-sandbox` workspace publishes the
59
+ (the `/api/dispatch` route driver, and the deploy-time `pack-distribution` and
60
+ `ship-deployment` commands that pack the guest archive and ship it, its
61
+ manifest and the selected provider plugins into the dispatch function) and
62
+ peers on both the core and the store service. The optional `packages/vercel-sandbox` workspace publishes the
62
63
  `@defrex/autobuild-vercel-sandbox` provider plugin (AUT-517): while the
63
64
  builtin hosts the implementation, its manifest re-registers the provider name
64
65
  over the shared capability object and the loader skips it with a notice.
@@ -80,7 +81,7 @@ remote-store protocol requires matching client and server versions.
80
81
  | `packages/core/src/store/` | BuildStore contract spanning builds, the repository journal, and operator sessions; interface-enforced build, operator-session, and local ambient-session scope wrappers; memory, SQLite/blob, and remote HTTP adapters | §7 |
81
82
  | `packages/core/src/store/streams/` | The stream primitive's shared core (§7.6): record/chunk types and the `ai-ui-message-stream/v1` constants, SDK-backed close-time `UIMessage[]` assembly, and the uniform bounded-wait read loop | §7.6 |
82
83
  | `packages/hosted-store-service/` | Environment-only hosted Fetch handler, lazy PostgreSQL/blob composition, offline token binary, the Next.js operator web app (`app/`, `server.ts`, `next.config.ts`, `vercel.json`), tests, and deployment guide | §7.2, §18 |
83
- | `packages/hosted-dispatcher/` | The optional cron-driven hosted dispatcher: endpoint driver, deploy-time `pack-distribution` binary, packed-distribution trace helper, tests, and operator guide | §7.2, §12, §18 |
84
+ | `packages/hosted-dispatcher/` | The optional cron-driven hosted dispatcher: endpoint driver, deploy-time `pack-distribution` and `ship-deployment` binary, packed-distribution trace helper, provider plugin shipper, tests, and operator guide | §7.2, §12, §18 |
84
85
  | `packages/vercel-sandbox/` | Published `@defrex/autobuild-vercel-sandbox` provider plugin: transitional manifest over the shared capability object with a guarded factory (implementation stays builtin-hosted until AUT-505) | §3.2.1 |
85
86
  | `packages/hosted-store-service/server.ts`, `packages/hosted-store-service/vercel.json` | One host-neutral Bun listener used locally and by Vercel's Bun preset | §7.2 |
86
87
  | `packages/core/src/kernel/` | Phase table, build reducer, engine; pure harvest, dispatcher-settings, dispatcher-status, and PR-attachment selectors; converge, stall detection, verify gating | §5, §7.5, §10, §12, §14, §15.4–15.5 |
@@ -558,8 +559,12 @@ kernel child is reaped, after which a non-SIGINT terminating signal is replayed
558
559
  in the frontend. A parent-liveness watch remains the detached-kernel fallback.
559
560
  The repository record carries constant-size, lease-holder-fenced tick telemetry:
560
561
  `beginRepoTick` opens the unsafe boundary, and `finishRepoTick` atomically closes
561
- it and appends selected tick facts. Successful unchanged ticks append nothing;
562
- queue transitions, counters, diagnostics, attention resets/retries, and failures
562
+ it and appends selected tick facts. Unchanged standing ticket counts and diagnostics do
563
+ not publish tick pairs. Changes to those counts or diagnostics, per-tick activity,
564
+ recovery from a failed tick, and due attention retries still publish. The last published
565
+ diagnostics remain visible while lease-fenced completion telemetry advances
566
+ independently of the journal cursor. Successful unchanged ticks append nothing;
567
+ queue transitions, activity counters, changed diagnostics, attention resets/retries, and failures
563
568
  retain their journal evidence. Buffered starts preserve actual `startedAt` for
564
569
  attention cooldowns; old starts use their envelope time. Liveness reads refresh
565
570
  the repository record even with an unchanged event cursor, merging matching-run
@@ -625,10 +630,15 @@ It preserves unpublished branch commits and distinct detached producer candidate
625
630
  under immutable `refs/autobuild/archive/<build>/<sha>` refs, verifies their exact
626
631
  readback, and records `workspace.commits-preserved` before cleanup. Replacement
627
632
  provisioning restores those exact refs before starting an agent. Preservation
628
- never advances the public build branch. A confirmed absent environment records
629
- `workspace.commits-lost`, naming known candidates and explicitly noting that any
630
- additional unpublished SHAs could not be inspected. Unknown fencing, inspection,
631
- transport, or receipt-write outcomes leave the workspace and snapshots intact.
633
+ never advances the public build branch. A confirmed absent environment, or one
634
+ that exists without a provisioned checkout, records `workspace.commits-lost`,
635
+ naming known candidates and explicitly noting that any additional unpublished
636
+ SHAs could not be inspected. Unknown fencing, inspection, transport, or
637
+ receipt-write outcomes leave the workspace and snapshots intact. A workspace
638
+ flagged by `workspace.cleanup-required` is never launched into: the dispatcher
639
+ releases it and provisions the next generation. A preservation or release
640
+ failure is recorded against its build, as an infrastructure failure or janitor
641
+ attention, and never stops the dispatcher from advancing other builds.
632
642
  Fencing is revalidated after restart; a saved receipt alone never authorizes
633
643
  cleanup of a newer execution. Current recovery notes are linked by the session
634
644
  manifest's `workspaceRecovery` field. Recovery notes apply to the next session
@@ -1372,7 +1372,11 @@ status` and both dashboards, consumes `maxInfrastructureAttempts`, and raises
1372
1372
  one setup-targeted escalation when exhausted. If cleanup also fails, both the
1373
1373
  step output and cleanup uncertainty remain durable instead of hiding the root
1374
1374
  cause. A marked sandbox does not repeat provisioning; every replacement/new
1375
- generation does.
1375
+ generation does. A named sandbox left without the completion marker, for example
1376
+ after a provision timeout, is flagged `cleanup-required` and never launched into.
1377
+ The dispatcher releases it automatically, recording an empty
1378
+ `workspace.commits-lost` when no checkout exists, and provisions the next
1379
+ generation.
1376
1380
 
1377
1381
  The representative actual-provider check is opt-in and must point at an
1378
1382
  independent consuming repository whose `autobuild.toml` selects the universal
@@ -1556,6 +1556,10 @@ is `{outcome:"completed", counters}` or `{outcome:"failed", error}`; events is
1556
1556
  empty for a quiet success or a matching dispatcher start/terminal pair for that
1557
1557
  holder. The validated batch and finished telemetry commit atomically. The reply
1558
1558
  is `{observation, events}` with assigned envelopes, or null on fencing failure.
1559
+ Unchanged standing ticket counts and diagnostics do not publish tick pairs. Changes to
1560
+ those counts or diagnostics, per-tick activity, recovery from a failed tick, and due
1561
+ attention retries still publish. The last published diagnostics remain visible while
1562
+ lease-fenced completion telemetry advances independently of the journal cursor.
1559
1563
  These operations never renew the lease. Repository records optionally expose
1560
1564
  `tick: {run, open?: {startedAt}, finished?: {run, startedAt, completedAt, ...completion}}`.
1561
1565
  They retain the previous completion while a new tick is open and after lease
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defrex/autobuild",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
4
4
  "description": "Agent-driven software delivery from groomed ticket to merged PR",
5
5
  "repository": {
6
6
  "type": "git",
@@ -135,7 +135,7 @@
135
135
  "release": "bun tools/release.ts",
136
136
  "postgres:migrate": "bun packages/postgres-store/src/bin.ts migrate",
137
137
  "docs:configuration": "bun tools/configuration-reference.ts --write",
138
- "check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/reducer-value-shapes.ts --check && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/package-boundary-check.ts",
138
+ "check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/reducer-value-shapes.ts --check && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/package-boundary-check.ts && bun tools/publish-dependencies-check.ts",
139
139
  "check:build": "bun tools/workspace-manifest-check.ts && bun tools/bin-mode-check.ts && bun tools/publish-contents-check.ts && bun tools/publish-imports-check.ts",
140
140
  "format:staged": "git-format-staged --formatter './node_modules/.bin/biome format --stdin-file-path {}' '*.js' '*.jsx' '*.ts' '*.tsx' '*.json' '*.jsonc' '*.css' '*.graphql' '*.gql'",
141
141
  "prepare": "husky",
@@ -156,8 +156,8 @@
156
156
  },
157
157
  "devDependencies": {
158
158
  "@biomejs/biome": "2.5.5",
159
- "@defrex/autobuild-postgres-store": "1.4.0",
160
- "@defrex/autobuild-vercel-sandbox": "1.4.0",
159
+ "@defrex/autobuild-postgres-store": "1.4.2",
160
+ "@defrex/autobuild-vercel-sandbox": "1.4.2",
161
161
  "@resvg/resvg-js": "2.6.2",
162
162
  "@types/bun": "^1.3.14",
163
163
  "@types/node": "^24.0.0",
@@ -163,6 +163,8 @@ export class DispatchFrontend {
163
163
  private accepting = false
164
164
  private cleanupInput: (() => void) | undefined
165
165
  private refresh: DashboardRefresh | undefined
166
+ /** Set once a failure streak is journaled; cleared by the next good frame. */
167
+ private renderFailureReported = false
166
168
  private suspension: ReturnType<typeof installPresentationSuspension> | undefined
167
169
  private readonly reader: BuildStore
168
170
  private paintTimer: ReturnType<typeof setInterval> | undefined
@@ -1078,12 +1080,18 @@ export class DispatchFrontend {
1078
1080
  async () => {
1079
1081
  try {
1080
1082
  await this.readFrame()
1083
+ this.renderFailureReported = false
1081
1084
  } catch (error) {
1082
- if (this.refresh?.admitted)
1085
+ // One durable warning per failure streak, not per poll: a poll that
1086
+ // fails on every tick would otherwise grow the journal it reads.
1087
+ // Messages carry moving cursors, so they cannot serve as the dedup key.
1088
+ if (this.refresh?.admitted && !this.renderFailureReported) {
1089
+ this.renderFailureReported = true
1083
1090
  await this.report(
1084
1091
  `dashboard render failed: ${error instanceof Error ? error.message : String(error)}`,
1085
1092
  'warning',
1086
1093
  )
1094
+ }
1087
1095
  throw error
1088
1096
  }
1089
1097
  },
@@ -338,8 +338,10 @@ export interface WorkspacePublication {
338
338
  replayPack?: string
339
339
  }): Promise<boolean>
340
340
 
341
- /** Dispatcher-only, after a durable non-destructive fence. Errors never
342
- * constitute proof that an environment or its unpublished work is absent. */
341
+ /** Dispatcher-only, after a durable non-destructive fence. `absent` means
342
+ * the environment is gone or exists without a provisioned checkout. Errors
343
+ * never constitute proof that an environment or its unpublished work is
344
+ * absent. */
343
345
  preserve?(input: {
344
346
  ref: string
345
347
  slug: string
@@ -40,7 +40,7 @@ import { cachedRuntime, resolveCachedGuestArchive } from '../../cli/dispatch-run
40
40
  * bytes installed and resolution never adds a second pack per tick.
41
41
  */
42
42
  import { createHash } from 'node:crypto'
43
- import { access, mkdir, readdir, readFile, writeFile } from 'node:fs/promises'
43
+ import { access, mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises'
44
44
  import { join, resolve } from 'node:path'
45
45
  import { distributionRoot, distributionPath } from '../../distribution'
46
46
  import { REMOTE_STORE_PROTOCOL_VERSION } from '../../store/remote/version'
@@ -247,16 +247,26 @@ export async function packageAutobuildDistribution(): Promise<Uint8Array> {
247
247
 
248
248
  /** Pack the running distribution into `<root>/.autobuild-dist/autobuild-<version>.tgz`
249
249
  * (the same bytes `bun pm pack` produces) and return the archive path. Meant
250
- * for a deployment's build step, where `bun` and the source tree exist. */
250
+ * for a deployment's build step, where `bun` and the source tree exist. Any
251
+ * other `autobuild-*.tgz` there is removed: a cached build folder from an
252
+ * earlier version would otherwise hold two archives, which the deployment
253
+ * refuses to ship. */
251
254
  export async function writePrebuiltDistributionArchive(
252
255
  root: string = distributionRoot(),
256
+ pack: () => Promise<Uint8Array> = packageAutobuildDistribution,
253
257
  ): Promise<string> {
254
258
  const version = await readDistributionIdentity()
255
- const archive = await packageAutobuildDistribution()
259
+ const archive = await pack()
256
260
  const dir = join(root, PREBUILT_DISTRIBUTION_DIR)
257
261
  await mkdir(dir, { recursive: true })
258
- const path = join(dir, distributionAssetName(version))
262
+ const name = distributionAssetName(version)
263
+ const path = join(dir, name)
259
264
  await writeFile(path, archive)
265
+ for (const entry of await readdir(dir)) {
266
+ if (entry !== name && entry.startsWith('autobuild-') && entry.endsWith('.tgz')) {
267
+ await rm(join(dir, entry), { force: true })
268
+ }
269
+ }
260
270
  return path
261
271
  }
262
272
 
@@ -1365,6 +1365,19 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1365
1365
  const sandbox = await this.facade.get(input.ref, this.operationSignal())
1366
1366
  if (sandbox === null) return { outcome: 'absent' }
1367
1367
  const heads = await this.withTrustedGit(sandbox, input.ref, async (exec) => {
1368
+ // A VM whose provisioning stopped before the checkout was moved
1369
+ // into place has nothing to preserve. The probe runs without the
1370
+ // checkout as cwd, and only a definite "missing" proves absence.
1371
+ const checkout = await sandbox.runCommand({
1372
+ cmd: 'test',
1373
+ args: ['-e', `${VERCEL_WORKSPACE_PATH}/.git`],
1374
+ signal: this.operationSignal(),
1375
+ })
1376
+ if (checkout.exitCode === 1) return null
1377
+ if (checkout.exitCode !== 0)
1378
+ throw new Error(
1379
+ `preservation could not confirm the checkout at ${VERCEL_WORKSPACE_PATH} (exit ${checkout.exitCode})`,
1380
+ )
1368
1381
  const capability = gitRewrite(exec, false)
1369
1382
  const remote = await this.remoteBranchHead(input.branch, 'preservation branch')
1370
1383
  const base =
@@ -1383,6 +1396,7 @@ export class VercelSandboxProvider implements WorkspaceProvider {
1383
1396
  archive: capability.archive,
1384
1397
  })
1385
1398
  })
1399
+ if (heads === null) return { outcome: 'absent' }
1386
1400
  return { outcome: 'preserved', heads }
1387
1401
  }),
1388
1402
  rewrite: (input: Parameters<NonNullable<WorkspacePublication['rewrite']>>[0]) =>
@@ -7,7 +7,7 @@ import {
7
7
  type MissingAccountCredential,
8
8
  } from '../accounts/availability'
9
9
 
10
- import { WorkspaceFenceUnknown, preserveWorkspaceBeforeRelease } from './workspace-preservation'
10
+ import { preserveWorkspaceBeforeRelease } from './workspace-preservation'
11
11
  import { WorkspaceCleanupRequired } from '../ports/types'
12
12
  import { ArtifactMetaUnsupportedError } from '../store/artifact-meta'
13
13
  import type { TicketPreparation } from '../kernel/ticket-preparation'
@@ -683,6 +683,12 @@ function openWorkspace(events: CurrentBuildFacts): OpenBuildWorkspace | null {
683
683
  return events.workspace
684
684
  }
685
685
 
686
+ /** The open workspace is the one a provider flagged `cleanup-required`: it
687
+ * must be reaped and replaced, never launched into. */
688
+ function cleanupRequiredWorkspace(events: CurrentBuildFacts): boolean {
689
+ return events.workspace !== null && events.latestWorkspace?.type === 'workspace.cleanup-required'
690
+ }
691
+
686
692
  /** The build's base branch, from its own `build.created` fact (§15.3);
687
693
  * falls back to the repo config for logs missing one. */
688
694
  function baseBranchOf(events: CurrentBuildFacts, config: Config): string {
@@ -1519,6 +1525,14 @@ export class Dispatcher {
1519
1525
  if (launched.has(slug)) return 'already-active'
1520
1526
  launched.add(slug)
1521
1527
  const facts = (await readBuildFacts(this.store, slug)).value
1528
+ // Callers reap and reprovision a flagged workspace; an agent never starts
1529
+ // in an environment a provider flagged `cleanup-required`.
1530
+ if (
1531
+ facts.workspace !== null &&
1532
+ cleanupRequiredWorkspace(facts) &&
1533
+ this.workspaceOwner(facts.workspace)?.recovery !== undefined
1534
+ )
1535
+ return 'already-active'
1522
1536
  if (facts.log.restack.target === undefined && facts.lastCreated !== undefined) {
1523
1537
  const branch = facts.lastCreated.payload.baseBranch
1524
1538
  await this.observeTarget(slug, branch, undefined, report)
@@ -4045,9 +4059,9 @@ export class Dispatcher {
4045
4059
  const recovery = this.workspaceOwner(open)?.recovery
4046
4060
  if (recovery === undefined) return false
4047
4061
  // Last-chance settlement boundary (AUT-328): record the pending
4048
- // publication's fate BEFORE the destructive reap. The guard's append
4049
- // failure propagates — a stale workspace with an unrecorded pending
4050
- // request is never reaped (the next tick retries).
4062
+ // publication's fate BEFORE the destructive reap. A guard failure is
4063
+ // recorded against the build — a stale workspace with an unrecorded
4064
+ // pending request is never reaped (the next tick retries).
4051
4065
  try {
4052
4066
  await preserveWorkspaceBeforeRelease({
4053
4067
  store: this.store,
@@ -4069,7 +4083,12 @@ export class Dispatcher {
4069
4083
  // Keep this generation and its pending work until forge recovery,
4070
4084
  // while allowing the sweep to supervise the remaining builds.
4071
4085
  if (error instanceof ForgeRequestDeferred) return false
4072
- if (!(error instanceof WorkspaceFenceUnknown)) throw error
4086
+ // A repository-wide forge cooldown or version deferral is not this
4087
+ // build's failure; the tick-level handlers own it.
4088
+ if (error instanceof ForgeCooldown || error instanceof MixedVersionDeferral) throw error
4089
+ // Any other preservation or settlement failure (an unknown fence, a
4090
+ // checkout that could not be inspected) retains the workspace and its
4091
+ // pending work and is attributed to this build, never to the tick.
4073
4092
  await this.recordInfrastructureFailure(slug, events, {
4074
4093
  provider: open.provider,
4075
4094
  workspaceRef: open.ref,
@@ -4353,6 +4372,23 @@ export class Dispatcher {
4353
4372
  return this.completeDispatchBoundaries(record, seed, report, launched)
4354
4373
 
4355
4374
  stage = 'workspace'
4375
+ const flagged = openWorkspace(events)
4376
+ if (
4377
+ flagged !== null &&
4378
+ cleanupRequiredWorkspace(events) &&
4379
+ this.workspaceOwner(flagged)?.recovery !== undefined
4380
+ ) {
4381
+ // A retry never launches into a flagged environment: release it, then
4382
+ // provision the next generation below. A live lease means a foreign
4383
+ // continuation still owns the build.
4384
+ if (this.hasLiveExecutionLease(record)) return 'parked'
4385
+ if (!(await this.reapStaleWorkspace(record.slug, events, 'replacement'))) {
4386
+ // The failure is already durable against this build.
4387
+ launched.add(record.slug)
4388
+ return 'parked'
4389
+ }
4390
+ events = (await readBuildFacts(store, record.slug)).value
4391
+ }
4356
4392
  if (openWorkspace(events) === null) {
4357
4393
  if (this.deps.workspaces.recovery !== undefined) {
4358
4394
  // Recovery-capable provider: durable marker + tracked background
@@ -4704,209 +4740,236 @@ export class Dispatcher {
4704
4740
  if (launched.has(record.slug)) continue
4705
4741
  // Budget gate: the sweep re-attaches runners per expired build.
4706
4742
  if (this.outOfBudget(opts)) break
4707
- if (record.lease) {
4708
- if (new Date(record.lease.expiresAt).getTime() > now) continue // healthy
4709
- }
4710
- const facts = await this.store.buildFacts(record.slug)
4711
- const state = facts.state
4712
- if (mixedVersionDeferred(state)) {
4713
- await deferMixedVersion(this.store, record.slug)
4714
- continue
4715
- }
4716
- if (
4717
- (state.status === 'queued' && state.discardRequest !== undefined) ||
4718
- heldByRepositoryPause(state, paused)
4719
- ) {
4720
- continue
4721
- }
4722
- if (
4723
- state.status === 'queued' &&
4724
- !state.pendingCommands.some((command) => command.command === 'abort') &&
4725
- !(await this.dispatchBudget(record.slug))
4726
- )
4727
- continue
4728
- const pendingRewrite = facts.publication.latestUncompletedRequest()?.payload
4729
- const retryIntent =
4730
- pendingRewrite?.operation === 'reconcile' && pendingRewrite.rewrite
4731
- ? { operation: 'reconcile' as const, id: pendingRewrite.rewrite.id }
4732
- : facts.log.restack.intent
4733
- ? { operation: 'restack' as const, id: facts.log.restack.intent.id }
4734
- : undefined
4735
- // Publication waits must not prevent a replacement runner from
4736
- // acknowledging controls, including abort on an exhausted episode.
4737
- if (retryIntent && state.pendingCommands.length === 0) {
4738
- try {
4739
- await publicationRetryGate(
4740
- { store: this.store, slug: record.slug, clock: this.deps.clock, actor: DISPATCHER },
4741
- retryIntent.operation,
4742
- retryIntent.id,
4743
- )
4744
- } catch (error) {
4745
- if (error instanceof ForgeRequestDeferred) continue
4746
- throw error
4747
- }
4743
+ try {
4744
+ await this.sweepBuild(record, report, launched, paused, now)
4745
+ } catch (error) {
4746
+ // Per-build containment: one build's failure never stops the sweep
4747
+ // from advancing the others. Workspace failures are already durable
4748
+ // against the build; a repository-wide cooldown still ends the tick.
4749
+ if (error instanceof ForgeRequestDeferred || error instanceof MixedVersionDeferral) continue
4750
+ if (error instanceof ForgeCooldown) throw error
4751
+ const message =
4752
+ error instanceof Error || isForgeFailure(error) ? error.message : String(error)
4753
+ report.janitorFailed += 1
4754
+ report.janitorDiagnostics.push(`build ${record.slug}: lease sweep failed — ${message}`)
4748
4755
  }
4749
- const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
4750
- if (decision === undefined) continue
4751
- if (state.status === 'done' || state.status === 'aborted') continue
4752
- const orphanEligible = (state: BuildState) =>
4753
- !paused &&
4754
- state.status === 'running' &&
4755
- (state.kind !== 'node' || integrationCurrent(state)) &&
4756
- state.sessions.open.some((session) => session.suspensionCause === undefined)
4757
- const provedEnded =
4758
- facts.open === null &&
4759
- (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch')
4760
- const cleanup = state.verifyStage.cleanupExecutionSeq
4761
- if (
4762
- !record.lease &&
4763
- now - new Date(record.updatedAt).getTime() < this.leaseTtlMs &&
4764
- facts.lastExecution !== 'relaunch' &&
4765
- !(cleanup !== undefined && state.verifyStage.executionSeq <= cleanup) &&
4766
- !(provedEnded && (decision.kind !== 'wait' || orphanEligible(state)))
4767
- )
4768
- continue // preserve first-claim grace, but never postpone proved-ended work
4756
+ }
4757
+ }
4769
4758
 
4770
- if (
4771
- state.kind === 'node' &&
4772
- (!integrationCurrent(state) || facts.workspace === null) &&
4773
- decision.kind !== 'wait'
4774
- )
4775
- continue // cascade owns node runner admission
4776
- // Raw history, read at most once and only by a branch that acts on it.
4777
- let loaded: CurrentBuildFacts | undefined
4778
- const history = async (): Promise<CurrentBuildFacts> => {
4779
- loaded ??= (await readBuildFacts(this.store, record.slug)).value
4780
- return loaded
4781
- }
4782
- // Liveness gate (durable supervision): a recorded execution the provider
4783
- // observes as RUNNING is left completely alone — no settle, no reap, no
4784
- // replacement, no re-attach. This is the change that stops a supervisor
4785
- // restart from replacing a healthy environment generation. A provider-
4786
- // proved end settles first (completion facts, lease release, publication)
4787
- // and then falls through to the normal decision; a provider-proved loss
4788
- // falls through to the existing stale path below.
4789
- let orphanRecoveryDue = orphanEligible(state) && facts.open === null
4790
- const foreignExecution = facts.open
4791
- // A provider- or log-proved end in the same generation re-attaches in
4792
- // place: the guest finished its work, the workspace is still the
4793
- // build's, and replacing the environment would discard a healthy
4794
- // generation. Only an unproven stale lease or a proved loss reaps.
4795
- // A start that later found the open workspace missing is a proved loss
4796
- // too: the recorded end no longer vouches for an environment that is
4797
- // gone, and re-attaching would fail against the same ref forever.
4798
- const failure = state.infrastructureFailure
4799
- const workspaceMissing =
4800
- failure?.cause === 'missing' &&
4801
- failure.operation === 'start' &&
4802
- failure.workspaceRef === facts.workspace?.ref
4803
- let endedInPlace =
4804
- (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch') &&
4805
- !workspaceMissing
4806
- if (
4807
- foreignExecution !== null &&
4808
- foreignExecution.commandId !== undefined &&
4809
- !launched.has(record.slug)
4810
- ) {
4811
- const owner = this.executionOwner(foreignExecution.provider)
4812
- const execution = owner?.buildExecution
4813
- if (execution?.observe !== undefined) {
4814
- const settlement = await settleOpenExecution(
4815
- {
4816
- store: this.store,
4817
- execution,
4818
- ...(this.settlePublication !== undefined
4819
- ? { settlePublication: this.settlePublication }
4820
- : {}),
4821
- },
4822
- record.slug,
4823
- foreignExecution,
4824
- )
4825
- if (settlement === 'running') continue
4826
- // Unknown liveness is never proof that an open execution is dead.
4827
- // Settlement may itself raise provider attention. Revalidate cleanup
4828
- // eligibility from the advanced canonical state before admission.
4829
- orphanRecoveryDue = orphanEligible((await this.store.buildFacts(record.slug)).state)
4830
- if (settlement === 'settled') {
4831
- report.settled += 1
4832
- endedInPlace = true
4833
- }
4834
- }
4759
+ /** One build's lease-sweep pass; `leaseSweep` contains its failures. */
4760
+ private async sweepBuild(
4761
+ record: BuildRecord,
4762
+ report: TickReport,
4763
+ launched: Set<string>,
4764
+ paused: boolean,
4765
+ now: number,
4766
+ ): Promise<void> {
4767
+ if (record.lease) {
4768
+ if (new Date(record.lease.expiresAt).getTime() > now) return // healthy
4769
+ }
4770
+ const facts = await this.store.buildFacts(record.slug)
4771
+ const state = facts.state
4772
+ if (mixedVersionDeferred(state)) {
4773
+ await deferMixedVersion(this.store, record.slug)
4774
+ return
4775
+ }
4776
+ if (
4777
+ (state.status === 'queued' && state.discardRequest !== undefined) ||
4778
+ heldByRepositoryPause(state, paused)
4779
+ ) {
4780
+ return
4781
+ }
4782
+ if (
4783
+ state.status === 'queued' &&
4784
+ !state.pendingCommands.some((command) => command.command === 'abort') &&
4785
+ !(await this.dispatchBudget(record.slug))
4786
+ )
4787
+ return
4788
+ const pendingRewrite = facts.publication.latestUncompletedRequest()?.payload
4789
+ const retryIntent =
4790
+ pendingRewrite?.operation === 'reconcile' && pendingRewrite.rewrite
4791
+ ? { operation: 'reconcile' as const, id: pendingRewrite.rewrite.id }
4792
+ : facts.log.restack.intent
4793
+ ? { operation: 'restack' as const, id: facts.log.restack.intent.id }
4794
+ : undefined
4795
+ // Publication waits must not prevent a replacement runner from
4796
+ // acknowledging controls, including abort on an exhausted episode.
4797
+ if (retryIntent && state.pendingCommands.length === 0) {
4798
+ try {
4799
+ await publicationRetryGate(
4800
+ { store: this.store, slug: record.slug, clock: this.deps.clock, actor: DISPATCHER },
4801
+ retryIntent.operation,
4802
+ retryIntent.id,
4803
+ )
4804
+ } catch (error) {
4805
+ if (error instanceof ForgeRequestDeferred) return
4806
+ throw error
4835
4807
  }
4836
- const publicationRecoveryDue =
4837
- state.status !== 'paused' &&
4838
- state.status !== 'blocked' &&
4839
- (facts.publication.pending() || facts.publication.abandonedPending())
4840
- const open = facts.workspace
4841
- // A provider- or log-proved END in the same generation re-attaches in
4842
- // place: the guest finished its work, the workspace is still the
4843
- // build's, and replacing the environment would discard a healthy
4844
- // generation. Only an unproven stale lease or a proved loss reaps.
4845
- if (open !== null && this.workspaceOwner(open)?.recovery !== undefined && !endedInPlace) {
4846
- const parked = decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue
4847
- const reason =
4848
- state.status === 'paused'
4849
- ? ('pause' as const)
4850
- : state.status === 'blocked'
4851
- ? ('blocked' as const)
4852
- : ('replacement' as const)
4853
- const reaped = await this.reapStaleWorkspace(record.slug, await history(), reason)
4854
- if (!reaped) continue
4855
- if (!parked) {
4856
- // Recovery-capable provider: reap inline (bounded), then kick the
4857
- // same background continuation — it provisions and launches without
4858
- // blocking this tick. Local providers never enter this branch.
4859
- const kicked = await this.ensureProvisionContinuation(record, await history(), 'launch')
4860
- if (kicked === 'kicked') {
4861
- report.provisioning += 1
4862
- report.swept += 1
4863
- }
4864
- continue
4808
+ }
4809
+ const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
4810
+ if (decision === undefined) return
4811
+ if (state.status === 'done' || state.status === 'aborted') return
4812
+ const orphanEligible = (state: BuildState) =>
4813
+ !paused &&
4814
+ state.status === 'running' &&
4815
+ (state.kind !== 'node' || integrationCurrent(state)) &&
4816
+ state.sessions.open.some((session) => session.suspensionCause === undefined)
4817
+ const provedEnded =
4818
+ facts.open === null &&
4819
+ (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch')
4820
+ const cleanup = state.verifyStage.cleanupExecutionSeq
4821
+ if (
4822
+ !record.lease &&
4823
+ now - new Date(record.updatedAt).getTime() < this.leaseTtlMs &&
4824
+ facts.lastExecution !== 'relaunch' &&
4825
+ !(cleanup !== undefined && state.verifyStage.executionSeq <= cleanup) &&
4826
+ !(provedEnded && (decision.kind !== 'wait' || orphanEligible(state)))
4827
+ )
4828
+ return // preserve first-claim grace, but never postpone proved-ended work
4829
+
4830
+ if (
4831
+ state.kind === 'node' &&
4832
+ (!integrationCurrent(state) || facts.workspace === null) &&
4833
+ decision.kind !== 'wait'
4834
+ )
4835
+ return // cascade owns node runner admission
4836
+ // Raw history, read at most once and only by a branch that acts on it.
4837
+ let loaded: CurrentBuildFacts | undefined
4838
+ const history = async (): Promise<CurrentBuildFacts> => {
4839
+ loaded ??= (await readBuildFacts(this.store, record.slug)).value
4840
+ return loaded
4841
+ }
4842
+ // Liveness gate (durable supervision): a recorded execution the provider
4843
+ // observes as RUNNING is left completely alone — no settle, no reap, no
4844
+ // replacement, no re-attach. This is the change that stops a supervisor
4845
+ // restart from replacing a healthy environment generation. A provider-
4846
+ // proved end settles first (completion facts, lease release, publication)
4847
+ // and then falls through to the normal decision; a provider-proved loss
4848
+ // falls through to the existing stale path below.
4849
+ let orphanRecoveryDue = orphanEligible(state) && facts.open === null
4850
+ const foreignExecution = facts.open
4851
+ // A provider- or log-proved end in the same generation re-attaches in
4852
+ // place: the guest finished its work, the workspace is still the
4853
+ // build's, and replacing the environment would discard a healthy
4854
+ // generation. Only an unproven stale lease or a proved loss reaps.
4855
+ // A start that later found the open workspace missing is a proved loss
4856
+ // too: the recorded end no longer vouches for an environment that is
4857
+ // gone, and re-attaching would fail against the same ref forever.
4858
+ const failure = state.infrastructureFailure
4859
+ const workspaceMissing =
4860
+ failure?.cause === 'missing' &&
4861
+ failure.operation === 'start' &&
4862
+ failure.workspaceRef === facts.workspace?.ref
4863
+ let endedInPlace =
4864
+ (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch') &&
4865
+ !workspaceMissing
4866
+ if (
4867
+ foreignExecution !== null &&
4868
+ foreignExecution.commandId !== undefined &&
4869
+ !launched.has(record.slug)
4870
+ ) {
4871
+ const owner = this.executionOwner(foreignExecution.provider)
4872
+ const execution = owner?.buildExecution
4873
+ if (execution?.observe !== undefined) {
4874
+ const settlement = await settleOpenExecution(
4875
+ {
4876
+ store: this.store,
4877
+ execution,
4878
+ ...(this.settlePublication !== undefined
4879
+ ? { settlePublication: this.settlePublication }
4880
+ : {}),
4881
+ },
4882
+ record.slug,
4883
+ foreignExecution,
4884
+ )
4885
+ if (settlement === 'running') return
4886
+ // Unknown liveness is never proof that an open execution is dead.
4887
+ // Settlement may itself raise provider attention. Revalidate cleanup
4888
+ // eligibility from the advanced canonical state before admission.
4889
+ orphanRecoveryDue = orphanEligible((await this.store.buildFacts(record.slug)).state)
4890
+ if (settlement === 'settled') {
4891
+ report.settled += 1
4892
+ endedInPlace = true
4865
4893
  }
4866
4894
  }
4867
- // Reachable via the reap block above: when the wait decision is parked
4868
- // (no publication recovery due) the `if (!parked)` arm continues, but the
4869
- // parked arm falls through here after a successful reap. Without this
4870
- // guard the tick would reach the unconditional `launch` below and start a
4871
- // fresh runner for a paused or blocked build whose workspace was just
4872
- // reaped. Every other path that reaches this line with a wait decision
4873
- // already continued earlier.
4874
- if (decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue) continue
4875
- if (
4876
- facts.workspace === null &&
4877
- this.deps.workspaces.recovery !== undefined &&
4878
- (await history()).workspaceGenerations > 0
4879
- ) {
4895
+ }
4896
+ const publicationRecoveryDue =
4897
+ state.status !== 'paused' &&
4898
+ state.status !== 'blocked' &&
4899
+ (facts.publication.pending() || facts.publication.abandonedPending())
4900
+ const open = facts.workspace
4901
+ // A flagged `cleanup-required` workspace never re-attaches in place: it
4902
+ // is reaped and replaced by the next generation.
4903
+ if (endedInPlace && open !== null && cleanupRequiredWorkspace(await history()))
4904
+ endedInPlace = false
4905
+ // A provider- or log-proved END in the same generation re-attaches in
4906
+ // place: the guest finished its work, the workspace is still the
4907
+ // build's, and replacing the environment would discard a healthy
4908
+ // generation. Only an unproven stale lease or a proved loss reaps.
4909
+ if (open !== null && this.workspaceOwner(open)?.recovery !== undefined && !endedInPlace) {
4910
+ const parked = decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue
4911
+ const reason =
4912
+ state.status === 'paused'
4913
+ ? ('pause' as const)
4914
+ : state.status === 'blocked'
4915
+ ? ('blocked' as const)
4916
+ : ('replacement' as const)
4917
+ const reaped = await this.reapStaleWorkspace(record.slug, await history(), reason)
4918
+ if (!reaped) return
4919
+ if (!parked) {
4920
+ // Recovery-capable provider: reap inline (bounded), then kick the
4921
+ // same background continuation — it provisions and launches without
4922
+ // blocking this tick. Local providers never enter this branch.
4880
4923
  const kicked = await this.ensureProvisionContinuation(record, await history(), 'launch')
4881
4924
  if (kicked === 'kicked') {
4882
4925
  report.provisioning += 1
4883
4926
  report.swept += 1
4884
- continue
4885
4927
  }
4886
- // In-flight or foreign-live: whoever owns the marker completes the
4887
- // boundaries and the launch; this tick performs neither.
4888
- continue
4928
+ return
4889
4929
  }
4890
- try {
4891
- const result = await this.launch(record.slug, launched, report)
4892
- if (result === 'scheduled') report.swept += 1
4893
- } catch (error) {
4894
- // Launchers normally record provider failures themselves. Preserve
4895
- // durable attention if orphan cleanup fails before that boundary,
4896
- // without counting an already-recorded failure twice.
4897
- if (orphanRecoveryDue && open !== null) {
4898
- const current = (await readBuildFacts(this.store, record.slug)).value
4899
- if (current.infrastructureCount === facts.infrastructureCount)
4900
- await this.recordInfrastructureFailure(record.slug, current, {
4901
- provider: open.provider,
4902
- workspaceRef: open.ref,
4903
- operation: 'start',
4904
- error,
4905
- cleanupPending: false,
4906
- })
4907
- }
4908
- throw error
4930
+ }
4931
+ // Reachable via the reap block above: when the wait decision is parked
4932
+ // (no publication recovery due) the `if (!parked)` arm continues, but the
4933
+ // parked arm falls through here after a successful reap. Without this
4934
+ // guard the tick would reach the unconditional `launch` below and start a
4935
+ // fresh runner for a paused or blocked build whose workspace was just
4936
+ // reaped. Every other path that reaches this line with a wait decision
4937
+ // already continued earlier.
4938
+ if (decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue) return
4939
+ if (
4940
+ facts.workspace === null &&
4941
+ this.deps.workspaces.recovery !== undefined &&
4942
+ (await history()).workspaceGenerations > 0
4943
+ ) {
4944
+ const kicked = await this.ensureProvisionContinuation(record, await history(), 'launch')
4945
+ if (kicked === 'kicked') {
4946
+ report.provisioning += 1
4947
+ report.swept += 1
4948
+ return
4909
4949
  }
4950
+ // In-flight or foreign-live: whoever owns the marker completes the
4951
+ // boundaries and the launch; this tick performs neither.
4952
+ return
4953
+ }
4954
+ try {
4955
+ const result = await this.launch(record.slug, launched, report)
4956
+ if (result === 'scheduled') report.swept += 1
4957
+ } catch (error) {
4958
+ // Launchers normally record provider failures themselves. Preserve
4959
+ // durable attention if orphan cleanup fails before that boundary,
4960
+ // without counting an already-recorded failure twice.
4961
+ if (orphanRecoveryDue && open !== null) {
4962
+ const current = (await readBuildFacts(this.store, record.slug)).value
4963
+ if (current.infrastructureCount === facts.infrastructureCount)
4964
+ await this.recordInfrastructureFailure(record.slug, current, {
4965
+ provider: open.provider,
4966
+ workspaceRef: open.ref,
4967
+ operation: 'start',
4968
+ error,
4969
+ cleanupPending: false,
4970
+ })
4971
+ }
4972
+ throw error
4910
4973
  }
4911
4974
  }
4912
4975
 
@@ -1,40 +1,49 @@
1
1
  import type { RepositoryEvent } from '../events/repository'
2
2
  import type { TickReport } from './dispatcher'
3
3
 
4
- /** Every counter and diagnostic is significant, including standing counts.
5
- * Queue depth alone may be unchanged and nonzero. */
4
+ const standingCounters = ['invalidTickets', 'dependencyBlocked', 'creationWithheld'] as const
5
+ const diagnostics = [
6
+ 'blockedDiagnostics',
7
+ 'janitorDiagnostics',
8
+ 'ticketDiagnostics',
9
+ 'creationDiagnostics',
10
+ 'dependencyDiagnostics',
11
+ ] as const
12
+
13
+ /** Standing state changes publish; activity publishes on every occurrence. */
14
+ function reportRequiresPublication(
15
+ report: TickReport,
16
+ previous: RepositoryEvent | undefined,
17
+ ): boolean {
18
+ if (previous?.type !== 'dispatcher.tick-completed' || previous.payload.queued !== report.queued)
19
+ return true
20
+ for (const key of standingCounters)
21
+ if (report[key] !== (previous.payload.counters[key] ?? 0)) return true
22
+ for (const key of diagnostics) {
23
+ const before = previous.payload[key] ?? []
24
+ if (report[key].length !== before.length || report[key].some((value, i) => value !== before[i]))
25
+ return true
26
+ }
27
+ return Object.entries(report).some(
28
+ ([key, value]) =>
29
+ key !== 'queued' &&
30
+ key !== 'forgeRequests' &&
31
+ !standingCounters.some((standing) => standing === key) &&
32
+ typeof value === 'number' &&
33
+ value !== 0,
34
+ )
35
+ }
36
+
6
37
  export function shouldPublishTick(
7
38
  report: TickReport,
8
39
  events: readonly RepositoryEvent[],
9
40
  run: string,
10
41
  startedAt: string,
11
42
  ): boolean {
12
- if (
13
- Object.entries(report).some(
14
- ([key, value]) =>
15
- key !== 'queued' &&
16
- key !== 'forgeRequests' &&
17
- (typeof value === 'number' ? value !== 0 : value.length > 0),
18
- )
19
- )
20
- return true
21
- // Queue and diagnostic readers reduce per run, so each run must publish
22
- // its own baseline before quiet ticks can be suppressed.
23
43
  const previous = events.findLast(
24
44
  (e) => e.type === 'dispatcher.tick-completed' && e.payload.run === run,
25
45
  )
26
- if (previous?.type !== 'dispatcher.tick-completed' || previous.payload.queued !== report.queued)
27
- return true
28
- if (
29
- [
30
- previous.payload.blockedDiagnostics ?? [],
31
- previous.payload.janitorDiagnostics,
32
- previous.payload.ticketDiagnostics,
33
- previous.payload.creationDiagnostics ?? [],
34
- previous.payload.dependencyDiagnostics,
35
- ].some((list) => list.length > 0)
36
- )
37
- return true
46
+ if (reportRequiresPublication(report, previous)) return true
38
47
  const boundary = events.findLast(
39
48
  (e) =>
40
49
  (e.type === 'dispatcher.tick-completed' || e.type === 'dispatcher.tick-failed') &&
@@ -84,28 +93,7 @@ export function shouldPublishTickFromFacts(
84
93
  run: import('../kernel/read-facts').DispatcherRunFacts,
85
94
  startedAt: string,
86
95
  ): boolean {
87
- if (
88
- Object.entries(report).some(
89
- ([key, value]) =>
90
- key !== 'queued' &&
91
- key !== 'forgeRequests' &&
92
- (typeof value === 'number' ? value !== 0 : value.length > 0),
93
- )
94
- )
95
- return true
96
- const previous = run.completed
97
- if (previous?.type !== 'dispatcher.tick-completed' || previous.payload.queued !== report.queued)
98
- return true
99
- if (
100
- [
101
- previous.payload.blockedDiagnostics ?? [],
102
- previous.payload.janitorDiagnostics,
103
- previous.payload.ticketDiagnostics,
104
- previous.payload.creationDiagnostics ?? [],
105
- previous.payload.dependencyDiagnostics,
106
- ].some((list) => list.length > 0)
107
- )
108
- return true
96
+ if (reportRequiresPublication(report, run.completed)) return true
109
97
  if (run.tick?.type === 'dispatcher.tick-failed') return true
110
98
  return facts.attention.sources.some(
111
99
  ([, source]) =>
@@ -156,7 +156,7 @@ export async function preserveWorkspaceBeforeRelease(deps: {
156
156
  (sha) => !prior?.heads.some((head) => head.sha === sha),
157
157
  ),
158
158
  inventory: 'additional-shas-unavailable' as const,
159
- reason: `${deps.reason}: source environment is absent; additional unpublished SHAs could not be inspected`,
159
+ reason: `${deps.reason}: source environment or checkout is absent; additional unpublished SHAs could not be inspected`,
160
160
  },
161
161
  }
162
162
  if (!(await deps.store.appendIfCurrent(deps.slug, current.cursor, write)))
@@ -33,5 +33,27 @@
33
33
  "provenance": {
34
34
  "tag": "v1.4.0"
35
35
  }
36
+ },
37
+ {
38
+ "version": "1.4.1",
39
+ "publishedAt": "2026-11-03T00:07:39.172Z",
40
+ "protocol": "7",
41
+ "contract": "1.4.0.json",
42
+ "projects": true,
43
+ "catalogIdentity": "f9289449e0df64c1de972d7456cd4d50f179f06b36a20bed05ba91411573b194",
44
+ "provenance": {
45
+ "tag": "v1.4.1"
46
+ }
47
+ },
48
+ {
49
+ "version": "1.4.2",
50
+ "publishedAt": "2026-11-03T20:12:21.908Z",
51
+ "protocol": "7",
52
+ "contract": "1.4.0.json",
53
+ "projects": true,
54
+ "catalogIdentity": "f9289449e0df64c1de972d7456cd4d50f179f06b36a20bed05ba91411573b194",
55
+ "provenance": {
56
+ "tag": "v1.4.2"
57
+ }
36
58
  }
37
59
  ]
@@ -1160,6 +1160,118 @@ export async function parkedSweepReadBudget(opts: {
1160
1160
  }
1161
1161
  }
1162
1162
 
1163
+ /** Append filler facts to one build until its log holds `length` events. */
1164
+ async function seedBuildFiller(
1165
+ store: import('../store/memory').MemoryBuildStore,
1166
+ slug: string,
1167
+ length: number,
1168
+ ): Promise<void> {
1169
+ const events = buildEventRows(store, slug)
1170
+ while (events.length < length)
1171
+ await store.append(slug, {
1172
+ actor: humanActor('budget'),
1173
+ type: 'build.auto-merge-cancelled',
1174
+ payload: {},
1175
+ })
1176
+ }
1177
+
1178
+ function buildEventRows(
1179
+ store: import('../store/memory').MemoryBuildStore,
1180
+ slug: string,
1181
+ ): import('../events/catalog').AbEvent[] {
1182
+ return Reflect.get(store, 'builds').get(slug).events
1183
+ }
1184
+
1185
+ /** Count every event row MemoryBuildStore returns for one build, including
1186
+ * getReducerValue's private snapshot-tail reads, split at `boundary`. */
1187
+ function instrumentBuildRows(
1188
+ store: import('../store/memory').MemoryBuildStore,
1189
+ slug: string,
1190
+ boundary: () => number,
1191
+ metrics: { historicalRows: number; tailRows: number },
1192
+ ): () => void {
1193
+ const events = buildEventRows(store, slug)
1194
+ const slice = Array.prototype.slice
1195
+ events.slice = function (start?: number, end?: number) {
1196
+ const result = slice.call(this, start, end) as typeof events
1197
+ const limit = boundary()
1198
+ for (const event of result) {
1199
+ if (event.seq <= limit) metrics.historicalRows++
1200
+ else metrics.tailRows++
1201
+ }
1202
+ return result
1203
+ }
1204
+ return () => Reflect.deleteProperty(events, 'slice')
1205
+ }
1206
+
1207
+ /** A stale build whose open workspace is flagged `cleanup-required` and whose
1208
+ * preservation keeps failing re-enters the sweep's reap branch on every pass.
1209
+ * Each pass must read only the tail it appended itself, the same number of
1210
+ * reduced reads at 100 and 100,000 events, and nothing at all once the build
1211
+ * is healthy again. Fresh dispatchers retain no per-process cache. */
1212
+ export async function flaggedWorkspaceSweepReadBudget(opts: {
1213
+ store: import('../store/memory').MemoryBuildStore
1214
+ slug: string
1215
+ dispatcher: () => Dispatcher
1216
+ advance: () => void
1217
+ effects: () => { reaps: number; launches: number }
1218
+ }) {
1219
+ const { store, slug } = opts
1220
+ const sweeps = 4
1221
+ const metrics = { historicalRows: 0, tailRows: 0 }
1222
+ let reducerReads = 0
1223
+ const getReducerValue = store.getReducerValue.bind(store)
1224
+ store.getReducerValue = async (...args) => {
1225
+ reducerReads++
1226
+ return getReducerValue(...args)
1227
+ }
1228
+ const infrastructureFailures = async () =>
1229
+ (await readBuildFacts(store, slug)).value.infrastructureCount
1230
+ const perTick: Record<number, number[]> = {}
1231
+ for (const length of [100, 100_000]) {
1232
+ await seedBuildFiller(store, slug, length)
1233
+ opts.advance()
1234
+ // Rows the previous pass appended are the only tail a pass may read.
1235
+ let boundary = buildEventRows(store, slug).at(-1)!.seq
1236
+ await opts.dispatcher().tick({ acceptNewWork: false }) // warm durable projections
1237
+ const restore = instrumentBuildRows(store, slug, () => boundary, metrics)
1238
+ const before = opts.effects()
1239
+ perTick[length] = []
1240
+ for (let tick = 0; tick < sweeps; tick++) {
1241
+ const failures = await infrastructureFailures()
1242
+ const appendedBefore = buildEventRows(store, slug).at(-1)!.seq
1243
+ opts.advance()
1244
+ metrics.historicalRows = metrics.tailRows = reducerReads = 0
1245
+ await opts.dispatcher().tick({ acceptNewWork: false })
1246
+ perTick[length]!.push(reducerReads)
1247
+ expect(metrics.historicalRows).toBe(0)
1248
+ expect(await infrastructureFailures()).toBe(failures + 1)
1249
+ boundary = appendedBefore
1250
+ }
1251
+ expect(new Set(perTick[length]).size).toBe(1)
1252
+ expect(opts.effects()).toEqual(before)
1253
+ restore()
1254
+ }
1255
+ expect(perTick[100]).toEqual(perTick[100_000])
1256
+ // Unchanged path: a live lease makes the build healthy, so the sweep skips
1257
+ // it. After one settling pass, nothing changes and nothing is read.
1258
+ await store.claimLease(slug, 'budget-runner', 3_600_000)
1259
+ await opts.dispatcher().tick({ acceptNewWork: false })
1260
+ const restore = instrumentBuildRows(store, slug, () => Number.POSITIVE_INFINITY, metrics)
1261
+ metrics.historicalRows = metrics.tailRows = 0
1262
+ for (let tick = 0; tick < 2; tick++) await opts.dispatcher().tick({ acceptNewWork: false })
1263
+ expect(metrics).toEqual({ historicalRows: 0, tailRows: 0 })
1264
+ restore()
1265
+ Reflect.deleteProperty(store, 'getReducerValue')
1266
+ console.log('flagged workspace sweep read budget', {
1267
+ histories: [100, 100_000],
1268
+ sweeps,
1269
+ reducedReadsPerSweep: perTick[100_000]![0],
1270
+ historicalRows: 0,
1271
+ idleRows: 0,
1272
+ })
1273
+ }
1274
+
1163
1275
  /** In-memory history seeding for preparation budgets; never used as a recurring read. */
1164
1276
  export async function seedPreparationHistory(store: BuildStore, repo: string, facts: number) {
1165
1277
  await store.ensureRepo(repo)
@@ -903,10 +903,15 @@ It preserves unpublished branch commits and distinct detached producer candidate
903
903
  under immutable `refs/autobuild/archive/<build>/<sha>` refs, verifies their exact
904
904
  readback, and records `workspace.commits-preserved` before cleanup. Replacement
905
905
  provisioning restores those exact refs before starting an agent. Preservation
906
- never advances the public build branch. A confirmed absent environment records
907
- `workspace.commits-lost`, naming known candidates and explicitly noting that any
908
- additional unpublished SHAs could not be inspected. Unknown fencing, inspection,
909
- transport, or receipt-write outcomes leave the workspace and snapshots intact.
906
+ never advances the public build branch. A confirmed absent environment, or one
907
+ that exists without a provisioned checkout, records `workspace.commits-lost`,
908
+ naming known candidates and explicitly noting that any additional unpublished
909
+ SHAs could not be inspected. Unknown fencing, inspection, transport, or
910
+ receipt-write outcomes leave the workspace and snapshots intact. A workspace
911
+ flagged by `workspace.cleanup-required` is never launched into: the dispatcher
912
+ releases it and provisions the next generation. A preservation or release
913
+ failure is recorded against its build, as an infrastructure failure or janitor
914
+ attention, and never stops the dispatcher from advancing other builds.
910
915
  Fencing is revalidated after restart; a saved receipt alone never authorizes
911
916
  cleanup of a newer execution. Current recovery notes are linked by the session
912
917
  manifest's `workspaceRecovery` field. Recovery notes apply to the next session
@@ -1384,7 +1389,7 @@ commit, and the PR; a refused or failed attempt is journaled too.
1384
1389
  `[upgrade] automatic` is a strict boolean, defaults to `true`, and hot-reloads.
1385
1390
  Resident checkout dispatchers check every 60 seconds, independently of tick cadence.
1386
1391
  Exact changed targets can include downgrades. Missing or inconsistent declared-pin
1387
- metadata never falls back to installed mode. Self-hosting source launches follow
1392
+ metadata never falls back to installed mode. Source-mode launches follow
1388
1393
  the authoritative base commit using packaged-content and production-lock equality,
1389
1394
  without modifying operator or build worktrees. Equal-content advances still record
1390
1395
  the latest resolved target SHA. Compatible generations overlap through the durable draining handoff described above. `--once`, origin-mode and direct hot
@@ -1671,6 +1676,18 @@ saved credential for CI and other non-interactive hosts. A service override
1671
1676
  never borrows another service's credential. Build and harvest sessions keep
1672
1677
  their explicit scoped authority.
1673
1678
 
1679
+ ## Self-hosting the service
1680
+
1681
+ Connecting a project to an existing Autobuild service, as above, is the
1682
+ supported path. Running your own service instance, store-only or with its
1683
+ hosted dispatcher, is an unsupported, buyer-beware path: it is not fully
1684
+ production-ready, and its packaging, variables and procedure may change without
1685
+ notice. The deployment guide installs with the service package at
1686
+ `node_modules/@defrex/autobuild-hosted-store-service/SELF-HOSTING.md` inside the
1687
+ deployment folder; before that folder exists, read it at
1688
+ https://github.com/defrex/autobuild/blob/main/packages/hosted-store-service/SELF-HOSTING.md.
1689
+ Do not present self-hosting to users as a supported product feature.
1690
+
1674
1691
  ## Source-agnostic ticket operations
1675
1692
 
1676
1693
  The sessionless `ab ticket` namespace constructs whichever TicketSource the
@@ -2475,7 +2492,11 @@ Dispatcher liveness is also visible through `ab repository status --json`:
2475
2492
  `dispatcher.holder` identifies the unexpired repository lease owner, independently
2476
2493
  of `latestRun`. Each run includes its recorded `runtime` (version, commit, and
2477
2494
  source kind/location), or null for unrecorded historical starts. Heartbeat age measures attributable renewals; tick age measures
2478
- actual tick completion. Successful unchanged ticks leave no journal pair; bounded,
2495
+ actual tick completion. Unchanged standing ticket counts and diagnostics do not publish
2496
+ tick pairs. Changes to those counts or diagnostics, per-tick activity, recovery from a
2497
+ failed tick, and due attention retries still publish. The last published diagnostics
2498
+ remain visible while lease-fenced completion telemetry advances independently of the
2499
+ journal cursor. Successful unchanged ticks leave no journal pair; bounded,
2479
2500
  lease-fenced repository telemetry still records each actual completion and its
2480
2501
  outcome. Last-tick age refreshes independently of the event cursor and never uses
2481
2502
  heartbeat as completion evidence. Open telemetry protects unsafe work during
@@ -2611,6 +2632,12 @@ ab wait --for blocked --json my-build # exit 0: record says why; 2: it ended;
2611
2632
  Second, a plain blocking call — Codex, Pi, and the shell only expose "run a
2612
2633
  command and wait": run it in the turn and read the record when it returns.
2613
2634
 
2635
+ The same split governs `ab watch`, which streams and does not exit when it
2636
+ emits a record. Run an unbounded watch only under a monitor that wakes the
2637
+ agent on each output line. Under exit-only notification, bound it with
2638
+ `--count 1` so the first record ends the command, then re-arm from its
2639
+ trailing cursor.
2640
+
2614
2641
  The loop pattern ties the two together: wait, act on the record (answer the
2615
2642
  escalation, inspect the build, merge the PR), then wait again, passing the
2616
2643
  record's `cursor` back through `--since` so no event is ever examined twice:
@@ -1556,6 +1556,10 @@ is `{outcome:"completed", counters}` or `{outcome:"failed", error}`; events is
1556
1556
  empty for a quiet success or a matching dispatcher start/terminal pair for that
1557
1557
  holder. The validated batch and finished telemetry commit atomically. The reply
1558
1558
  is `{observation, events}` with assigned envelopes, or null on fencing failure.
1559
+ Unchanged standing ticket counts and diagnostics do not publish tick pairs. Changes to
1560
+ those counts or diagnostics, per-tick activity, recovery from a failed tick, and due
1561
+ attention retries still publish. The last published diagnostics remain visible while
1562
+ lease-fenced completion telemetry advances independently of the journal cursor.
1559
1563
  These operations never renew the lease. Repository records optionally expose
1560
1564
  `tick: {run, open?: {startedAt}, finished?: {run, startedAt, completedAt, ...completion}}`.
1561
1565
  They retain the previous completion while a new tick is open and after lease
@@ -162,12 +162,26 @@ satisfied only by new events. Conditions include `attention`,
162
162
  condition, 3 timeout, 4 interrupted. On 3 and 4 with `--json`, the output is a
163
163
  bare `{"cursor": …}` to resume from.
164
164
 
165
- Run long watches and waits in whatever background or monitor facility your
166
- harness provides, so the session stays responsive and you are woken when they
167
- emit. Use precisely the same resolved invocation and working directory as
168
- foreground commands, including inside background shells and harness monitors.
169
- Do not rely on a shell alias or function that those facilities may lose.
170
- Never block a foreground command for their whole duration.
165
+ An unbounded watch streams: it prints each record and keeps running, so it
166
+ does not exit when a build blocks. Match how you run it to how your harness
167
+ wakes you:
168
+
169
+ - **Woken on each new output line** (a monitor that streams stdout, such as
170
+ Claude Code's Monitor tool): run the standing watch unbounded there and act
171
+ on every line as it arrives.
172
+ - **Woken only when a command exits** (a background shell such as Claude
173
+ Code's background Bash, or a plain blocking call): never run an unbounded
174
+ watch this way, because its records sit unread until it exits. Add
175
+ `--count 1` so the watch exits on its first record:
176
+ `ab watch --operator --json --count 1 [--since <watch-cursor>]`. Act on the
177
+ record, then re-arm at once from the trailing cursor line. Presence survives
178
+ the re-arm gap.
179
+
180
+ `ab wait` exits on its first match, so it suits either kind. Use precisely the
181
+ same resolved invocation and working directory as foreground commands,
182
+ including inside background shells and harness monitors. Do not rely on a
183
+ shell alias or function that those facilities may lose. Never block a
184
+ foreground command for their whole duration.
171
185
 
172
186
  Ticket-source degradation records mean dispatch intake cannot evaluate the source;
173
187
  existing builds may still advance. Inspect `ab repository status --json` for the
@@ -215,8 +229,9 @@ Neither a loss observation nor a later retry authorizes dispatcher intervention.
215
229
  Operate the builds the repository's dispatcher dispatches, including new builds
216
230
  that appear after you arm. Finishing the initially queued set is no reason to stop.
217
231
 
218
- 1. Check presence as above, then arm `ab watch --operator --json` with no slugs.
219
- Retain its own cursor and re-arm with
232
+ 1. Check presence as above, then arm `ab watch --operator --json` with no slugs,
233
+ adding `--count 1` if your harness wakes you only on exit. Retain its own
234
+ cursor and re-arm with
220
235
  `ab watch --operator --json --since <watch-cursor>`. If it reports
221
236
  `cursor-too-old`, re-arm without `--since`, reconcile status and acknowledge
222
237
  the unavailable historical gap.
@@ -4,8 +4,8 @@
4
4
  "build": "ab-hosted-service-build"
5
5
  },
6
6
  "dependencies": {
7
- "@defrex/autobuild-hosted-store-service": "1.4.0",
8
- "@defrex/autobuild": "1.4.0",
7
+ "@defrex/autobuild-hosted-store-service": "1.4.2",
8
+ "@defrex/autobuild": "1.4.2",
9
9
  "next": "16.1.6",
10
10
  "react": "19.2.4",
11
11
  "react-dom": "19.2.4"