@defrex/autobuild 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +307 -27
  3. package/docs/accounts.md +38 -0
  4. package/docs/architecture.md +198 -25
  5. package/docs/build-store.md +18 -0
  6. package/docs/builds.md +5 -1
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +38 -19
  9. package/docs/dispatcher-hosting.md +42 -0
  10. package/docs/dispatcher.md +41 -0
  11. package/docs/forges.md +5 -0
  12. package/docs/integration-tree.md +8 -0
  13. package/docs/operating.md +11 -3
  14. package/docs/operator-api.md +37 -4
  15. package/docs/plugin-authoring.md +45 -1
  16. package/docs/remote-store-protocol.md +262 -42
  17. package/docs/remote-ticket-protocol.md +12 -10
  18. package/docs/restacking.md +60 -3
  19. package/docs/setup.md +37 -8
  20. package/docs/skills.md +1 -1
  21. package/docs/spec-standard.md +37 -3
  22. package/docs/troubleshooting.md +9 -0
  23. package/docs/workspaces.md +1 -1
  24. package/package.json +4 -3
  25. package/packages/core/src/accounts/availability.ts +96 -0
  26. package/packages/core/src/accounts/local-owner.ts +49 -2
  27. package/packages/core/src/cli/attention.ts +2 -0
  28. package/packages/core/src/cli/binary.ts +17 -1
  29. package/packages/core/src/cli/context.ts +62 -0
  30. package/packages/core/src/cli/dashboard/model.ts +12 -3
  31. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  32. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  33. package/packages/core/src/cli/dashboard/render.ts +46 -5
  34. package/packages/core/src/cli/dispatch-args.ts +27 -3
  35. package/packages/core/src/cli/dispatch-frontend.ts +187 -53
  36. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  38. package/packages/core/src/cli/dispatch-repository-feed.ts +45 -9
  39. package/packages/core/src/cli/dispatch.ts +145 -11
  40. package/packages/core/src/cli/harvest.ts +2 -1
  41. package/packages/core/src/cli/help.ts +16 -3
  42. package/packages/core/src/cli/historical-build-state.ts +6 -0
  43. package/packages/core/src/cli/main.ts +15 -2
  44. package/packages/core/src/cli/publication-settlement.ts +17 -0
  45. package/packages/core/src/cli/remote-poll.ts +11 -1
  46. package/packages/core/src/cli/repository-status.ts +11 -0
  47. package/packages/core/src/cli/status.ts +7 -1
  48. package/packages/core/src/cli/wait.ts +9 -2
  49. package/packages/core/src/cli/watch.ts +38 -3
  50. package/packages/core/src/config/roles.ts +16 -1
  51. package/packages/core/src/events/catalog.ts +7 -0
  52. package/packages/core/src/events/payloads.ts +85 -2
  53. package/packages/core/src/events/policy.ts +10 -0
  54. package/packages/core/src/events/repository.ts +35 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +189 -0
  56. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  57. package/packages/core/src/kernel/engine.ts +19 -12
  58. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  59. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  60. package/packages/core/src/kernel/log-index.ts +1 -1
  61. package/packages/core/src/kernel/node-landing.ts +27 -10
  62. package/packages/core/src/kernel/node-restack-demand.ts +1 -0
  63. package/packages/core/src/kernel/node-restack-state.ts +16 -1
  64. package/packages/core/src/kernel/node-restack-transaction.ts +14 -0
  65. package/packages/core/src/kernel/read-facts.ts +114 -9
  66. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  67. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  68. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  69. package/packages/core/src/kernel/reducer.ts +20 -2
  70. package/packages/core/src/kernel/replay-retention.ts +176 -0
  71. package/packages/core/src/kernel/target-lineage.ts +65 -0
  72. package/packages/core/src/kernel/target-observation.ts +117 -0
  73. package/packages/core/src/operator/registry.ts +5 -13
  74. package/packages/core/src/operator/tickets.ts +8 -2
  75. package/packages/core/src/plugin-sdk/index.ts +1 -0
  76. package/packages/core/src/ports/forge/fake.ts +22 -0
  77. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  78. package/packages/core/src/ports/forge/github.ts +42 -10
  79. package/packages/core/src/ports/forge/local-git.ts +16 -1
  80. package/packages/core/src/ports/types.ts +58 -4
  81. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  82. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  83. package/packages/core/src/ports/workspace/create.ts +2 -0
  84. package/packages/core/src/ports/workspace/distribution-archive.ts +14 -4
  85. package/packages/core/src/ports/workspace/fake.ts +4 -0
  86. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  87. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  88. package/packages/core/src/processes/build-runner.ts +240 -111
  89. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  90. package/packages/core/src/processes/dispatcher.ts +262 -80
  91. package/packages/core/src/processes/execution-no-progress.ts +7 -0
  92. package/packages/core/src/processes/harvest-runner.ts +6 -7
  93. package/packages/core/src/processes/publication-state.ts +2 -1
  94. package/packages/core/src/processes/repo-view.ts +22 -0
  95. package/packages/core/src/processes/tick-publication.ts +35 -47
  96. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  97. package/packages/core/src/scenarios/harness.ts +7 -0
  98. package/packages/core/src/store/adapter.ts +9 -0
  99. package/packages/core/src/store/build-scope.ts +28 -0
  100. package/packages/core/src/store/contract.ts +125 -0
  101. package/packages/core/src/store/event-reads.ts +156 -0
  102. package/packages/core/src/store/local/schema.ts +11 -0
  103. package/packages/core/src/store/local/store.ts +117 -2
  104. package/packages/core/src/store/memory.ts +237 -0
  105. package/packages/core/src/store/phase-session.ts +47 -0
  106. package/packages/core/src/store/reduced-reads.ts +8 -0
  107. package/packages/core/src/store/reducer-value-shapes.json +6262 -5227
  108. package/packages/core/src/store/reducer-value-validation.ts +3 -0
  109. package/packages/core/src/store/reducer-values.ts +62 -2
  110. package/packages/core/src/store/remote/client.ts +161 -16
  111. package/packages/core/src/store/remote/compatibility.ts +177 -46
  112. package/packages/core/src/store/remote/errors.ts +16 -0
  113. package/packages/core/src/store/remote/index.ts +11 -0
  114. package/packages/core/src/store/remote/protocol.ts +22 -0
  115. package/packages/core/src/store/remote/released-clients.json +48 -0
  116. package/packages/core/src/store/remote/released-clients.ts +88 -0
  117. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  118. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  119. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  120. package/packages/core/src/store/remote/version.ts +5 -2
  121. package/packages/core/src/store/repo-state-events.ts +4 -3
  122. package/packages/core/src/store/scan-cadence.ts +15 -0
  123. package/packages/core/src/store/session-handle.ts +18 -0
  124. package/packages/core/src/store/types.ts +27 -6
  125. package/packages/core/src/testing/dispatch-read-budget.ts +313 -2
  126. package/packages/core/src/testing/index.ts +5 -0
  127. package/packages/core/src/testing/reduced-read-budget.ts +728 -5
  128. package/skills/guide/SKILL.md +201 -18
  129. package/skills/guide/references/accounts.md +38 -0
  130. package/skills/guide/references/integration-tree.md +8 -0
  131. package/skills/guide/references/operator-api.md +37 -4
  132. package/skills/guide/references/plugin-authoring.md +45 -1
  133. package/skills/guide/references/remote-store-protocol.md +262 -42
  134. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  135. package/skills/guide/references/restacking.md +60 -3
  136. package/skills/guide/references/setup.md +37 -8
  137. package/skills/guide/references/spec-standard.md +37 -3
  138. package/skills/implement/SKILL.md +12 -3
  139. package/skills/operate/SKILL.md +87 -15
  140. package/skills/plan/SKILL.md +27 -4
  141. package/skills/plan-review/SKILL.md +22 -2
  142. package/skills/reconcile/SKILL.md +10 -1
  143. package/skills/spec/SKILL.md +7 -4
  144. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,14 @@
1
+ import { proveTargetLineage } from '../kernel/target-lineage'
2
+ import { assertTargetOid, observeTarget } from '../kernel/target-observation'
3
+ import {
4
+ MissingAccountCredentialsError,
5
+ missingAccountCredentials,
6
+ reconcileMissingAccounts,
7
+ type MissingAccountCredential,
8
+ } from '../accounts/availability'
9
+
10
+ import { WorkspaceFenceUnknown, preserveWorkspaceBeforeRelease } from './workspace-preservation'
11
+ import { WorkspaceCleanupRequired } from '../ports/types'
1
12
  import { ArtifactMetaUnsupportedError } from '../store/artifact-meta'
2
13
  import type { TicketPreparation } from '../kernel/ticket-preparation'
3
14
  import { sampleTargetDistance } from '../kernel/target-distance'
@@ -155,6 +166,7 @@ import type {
155
166
  Ticket,
156
167
  TicketSource,
157
168
  WorkspaceProvider,
169
+ WorkspaceProvisionResult,
158
170
  } from '../ports/types'
159
171
  import { NoCommitsBetweenBranchesError, TicketSourceRateLimitError } from '../ports/types'
160
172
  import type { Exec } from '../ports/workspace/git-worktree'
@@ -595,6 +607,9 @@ export interface TickOpts {
595
607
  export type LaunchRunnerResult = 'scheduled' | 'already-active'
596
608
 
597
609
  export interface DispatcherDeps {
610
+ /** Current selected-account presence; no store reads. */
611
+ missingAccounts?: () => MissingAccountCredential[]
612
+ accountCredentialSource?: MissingAccountCredential['source']
598
613
  store: BuildStore
599
614
  tickets: TicketSource
600
615
  workspaces: WorkspaceProvider
@@ -1037,6 +1052,7 @@ export class Dispatcher {
1037
1052
  // the durable driver of this tick's fan-out below. Neither control
1038
1053
  // pretends to a serialization the store does not offer.
1039
1054
  const repoFacts = this.store.repositoryFacts()
1055
+ if (this.deps.missingAccounts) await this.reconcileAccountPresence(this.deps.missingAccounts())
1040
1056
  const paused = repoFacts.settings.paused
1041
1057
  const autoMergeSeedFact = undefined
1042
1058
  // Stage 0 — SETTLEMENT: observe foreign executions from durable facts plus
@@ -1345,13 +1361,25 @@ export class Dispatcher {
1345
1361
  const criteriaFingerprint = hash(readyCriteria(this.deps.config))
1346
1362
  const startedAt = this.deps.clock().toISOString()
1347
1363
  const previous = this.latestScan()
1364
+ const cached = await this.store.getScanCadence(this.deps.repo)
1365
+ // Outcomes always come from the reduction. This row only acknowledges their cadence.
1366
+ const valid =
1367
+ previous !== undefined &&
1368
+ cached !== null &&
1369
+ cached.scanSeq === this.store.repositoryFacts().scanSeq &&
1370
+ cached.mode === previous.mode &&
1371
+ cached.readinessFingerprint === previous.readinessFingerprint &&
1372
+ cached.criteriaFingerprint === previous.criteriaFingerprint &&
1373
+ Number.isFinite(Date.parse(cached.startedAt))
1374
+ const baseline = valid ? cached : previous
1348
1375
  const elapsed =
1349
- previous === undefined ? Infinity : Date.parse(startedAt) - Date.parse(previous.startedAt)
1376
+ baseline === undefined ? Infinity : Date.parse(startedAt) - Date.parse(baseline.startedAt)
1350
1377
  return {
1351
1378
  startedAt,
1352
1379
  mode,
1353
1380
  readinessFingerprint,
1354
1381
  criteriaFingerprint,
1382
+ allowClockRollback: elapsed < 0,
1355
1383
  due:
1356
1384
  previous === undefined ||
1357
1385
  elapsed < 0 ||
@@ -1366,27 +1394,94 @@ export class Dispatcher {
1366
1394
  checkpoint: Awaited<ReturnType<Dispatcher['scanCheckpoint']>>,
1367
1395
  report: TickReport,
1368
1396
  ): Promise<void> {
1397
+ const payload = {
1398
+ startedAt: checkpoint.startedAt,
1399
+ mode: checkpoint.mode,
1400
+ readinessFingerprint: checkpoint.readinessFingerprint,
1401
+ criteriaFingerprint: checkpoint.criteriaFingerprint,
1402
+ queued: report.queued,
1403
+ invalidTickets: report.invalidTickets,
1404
+ ticketDiagnostics: report.ticketDiagnostics.slice(0, 1000),
1405
+ dependencyBlocked: report.dependencyBlocked,
1406
+ dependencyDiagnostics: report.dependencyDiagnostics.slice(0, 1000),
1407
+ creationWithheld: report.creationWithheld,
1408
+ creationDiagnostics: report.creationDiagnostics.slice(0, 1000),
1409
+ }
1410
+ const previous = this.latestScan()
1411
+ const unchanged =
1412
+ previous !== undefined &&
1413
+ Object.keys(payload)
1414
+ .filter((key) => key !== 'startedAt')
1415
+ .every(
1416
+ (key) =>
1417
+ JSON.stringify(previous[key as keyof typeof payload]) ===
1418
+ JSON.stringify(payload[key as keyof typeof payload]),
1419
+ )
1369
1420
  await this.store.ensureRepo(this.deps.repo)
1370
- await this.store.appendRepo(this.deps.repo, {
1371
- actor: DISPATCHER,
1372
- type: 'dispatcher.ticket-scan-completed',
1373
- payload: {
1421
+ let scanSeq = this.store.repositoryFacts().scanSeq
1422
+ if (!unchanged) {
1423
+ const event = await this.store.appendRepo(this.deps.repo, {
1424
+ actor: DISPATCHER,
1425
+ type: 'dispatcher.ticket-scan-completed',
1426
+ payload,
1427
+ })
1428
+ scanSeq = event.seq
1429
+ }
1430
+ if (scanSeq === undefined) throw new Error('completed scan has no canonical fact')
1431
+ await this.store.putScanCadence(
1432
+ this.deps.repo,
1433
+ {
1434
+ scanSeq,
1374
1435
  startedAt: checkpoint.startedAt,
1375
1436
  mode: checkpoint.mode,
1376
1437
  readinessFingerprint: checkpoint.readinessFingerprint,
1377
1438
  criteriaFingerprint: checkpoint.criteriaFingerprint,
1378
- queued: report.queued,
1379
- invalidTickets: report.invalidTickets,
1380
- ticketDiagnostics: report.ticketDiagnostics.slice(0, 1000),
1381
- dependencyBlocked: report.dependencyBlocked,
1382
- dependencyDiagnostics: report.dependencyDiagnostics.slice(0, 1000),
1383
- creationWithheld: report.creationWithheld,
1384
- creationDiagnostics: report.creationDiagnostics.slice(0, 1000),
1385
1439
  },
1440
+ checkpoint.allowClockRollback,
1441
+ )
1442
+ }
1443
+
1444
+ private accountsAvailable(): boolean {
1445
+ return !this.deps.missingAccounts?.().length
1446
+ }
1447
+
1448
+ private accountReconciliation: Promise<unknown> = Promise.resolve()
1449
+
1450
+ private reconcileAccountPresence(
1451
+ missing: readonly MissingAccountCredential[],
1452
+ merge = false,
1453
+ ): Promise<void> {
1454
+ const operation = this.accountReconciliation.then(async () => {
1455
+ if (missing.length && !this.store.journalRecorded())
1456
+ await this.store.ensureRepo(this.deps.repo)
1457
+ const current = this.store.repositoryFacts().missingAccounts
1458
+ const next = merge
1459
+ ? Object.values({
1460
+ ...current,
1461
+ ...Object.fromEntries(missing.map((account) => [account.name, account])),
1462
+ })
1463
+ : missing
1464
+ await reconcileMissingAccounts(next, current, (event) =>
1465
+ this.store.appendRepo(this.deps.repo, event),
1466
+ )
1386
1467
  })
1468
+ this.accountReconciliation = operation.catch(() => {})
1469
+ return operation
1470
+ }
1471
+
1472
+ async holdForMissingAccounts(error: unknown): Promise<boolean> {
1473
+ if (!(error instanceof MissingAccountCredentialsError)) return false
1474
+ const absent = missingAccountCredentials(
1475
+ Object.fromEntries(error.missing.map((account) => [account.name, account.descriptor])),
1476
+ {},
1477
+ this.deps.accountCredentialSource,
1478
+ )
1479
+ await this.reconcileAccountPresence(absent, true)
1480
+ return true
1387
1481
  }
1388
1482
 
1389
1483
  private async triggerHarvest(): Promise<void> {
1484
+ if (!this.accountsAvailable()) return
1390
1485
  const start = this.deps.startHarvest
1391
1486
  if (start === undefined) return
1392
1487
  // Use the tick sample, advanced by any local repository append.
@@ -1411,6 +1506,7 @@ export class Dispatcher {
1411
1506
  launched: Set<string>,
1412
1507
  report: TickReport = emptyTickReport(),
1413
1508
  ): Promise<LaunchRunnerResult> {
1509
+ if (!this.accountsAvailable()) return 'already-active'
1414
1510
  if (await this.forgeCoolingDown()) return 'already-active'
1415
1511
  if (await deferMixedVersion(this.store, slug)) return 'already-active'
1416
1512
  const launchState = (await this.store.buildFacts(slug)).state
@@ -1747,6 +1843,7 @@ export class Dispatcher {
1747
1843
  },
1748
1844
  ): Promise<'kicked' | 'in-flight' | 'foreign-live'> {
1749
1845
  const slug = record.slug
1846
+ if (!this.accountsAvailable()) return 'in-flight'
1750
1847
  if (this.continuations.has(slug)) return 'in-flight'
1751
1848
  const marker = this.openProvisionMarker(events)
1752
1849
  if (marker !== undefined) {
@@ -1853,7 +1950,7 @@ export class Dispatcher {
1853
1950
  return
1854
1951
  }
1855
1952
  const priorGenerations = events.workspaceGenerations
1856
- const handle = await workspaces.provision({
1953
+ const handle = await this.provisionWorkspace(slug, {
1857
1954
  // Local providers provision FROM the physical checkout; remote
1858
1955
  // providers ignore the value (their host seams are injected).
1859
1956
  repo: this.deps.checkout ?? this.deps.repo,
@@ -1902,12 +1999,13 @@ export class Dispatcher {
1902
1999
  const queued = (await readBuildFacts(store, slug)).value.state.status === 'queued'
1903
2000
  boundary = input.tail === 'dispatch' || queued ? 'dispatch' : 'launch'
1904
2001
  if (boundary === 'dispatch') await this.completeDispatchBoundaries(record, input.seed)
1905
- else await this.deps.launchRunner(slug)
2002
+ else if (this.accountsAvailable()) await this.deps.launchRunner(slug)
1906
2003
  } catch (error) {
1907
2004
  // Dispatch boundaries own their failure facts and exhaustion repair.
1908
2005
  // A failed tail read/write leaves durable unfinished work for the next
1909
2006
  // tick; it is not another provider workspace failure. Replacement
1910
2007
  // runner launch errors retain the existing infrastructure-budget path.
2008
+ if (await this.holdForMissingAccounts(error)) return
1911
2009
  if (boundary === 'read' || boundary === 'dispatch') return
1912
2010
  const events = (await readBuildFacts(store, slug)).value
1913
2011
  if (workspaces.recovery !== undefined) {
@@ -2731,25 +2829,36 @@ export class Dispatcher {
2731
2829
  private async observeTarget(
2732
2830
  slug: string,
2733
2831
  branch: string,
2734
- previous: string | undefined,
2832
+ _previous: string | undefined,
2735
2833
  report: TickReport,
2736
2834
  ): Promise<boolean> {
2737
- let sha: string
2738
2835
  try {
2739
- sha = await this.baseSha(branch)
2836
+ const sha = await this.baseSha(branch)
2837
+ return (
2838
+ (await observeTarget({
2839
+ store: this.store,
2840
+ forge: this.deps.forge,
2841
+ slug,
2842
+ branch,
2843
+ sha,
2844
+ actor: DISPATCHER,
2845
+ proveRewrite: (node, from) =>
2846
+ proveTargetLineage({
2847
+ store: this.store,
2848
+ forge: this.deps.forge,
2849
+ node,
2850
+ from,
2851
+ branch,
2852
+ sha,
2853
+ }),
2854
+ })) !== 'unchanged'
2855
+ )
2740
2856
  } catch (error) {
2741
2857
  const message =
2742
2858
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
2743
2859
  report.janitorDiagnostics.push(`build ${slug}: target observation failed — ${message}`)
2744
2860
  return false
2745
2861
  }
2746
- if (sha === previous) return false
2747
- await this.store.append(slug, {
2748
- actor: DISPATCHER,
2749
- type: 'target.moved',
2750
- payload: { branch, sha },
2751
- })
2752
- return true
2753
2862
  }
2754
2863
 
2755
2864
  private forgeWorkspacePath(events: CurrentBuildFacts): string {
@@ -3844,6 +3953,32 @@ export class Dispatcher {
3844
3953
  }
3845
3954
  }
3846
3955
 
3956
+ private async provisionWorkspace(
3957
+ slug: string,
3958
+ input: Parameters<WorkspaceProvider['provision']>[0],
3959
+ ) {
3960
+ const facts = (await readBuildFacts(this.store, slug)).value
3961
+ try {
3962
+ return await this.deps.workspaces.provision({
3963
+ ...input,
3964
+ restoration: facts.workspacePreservation?.payload.heads,
3965
+ })
3966
+ } catch (error) {
3967
+ if (error instanceof WorkspaceCleanupRequired) {
3968
+ await this.store.append(slug, {
3969
+ actor: DISPATCHER,
3970
+ type: 'workspace.cleanup-required',
3971
+ payload: {
3972
+ ...error.workspace,
3973
+ base: error.workspace.base ?? facts.latestWorkspace!.payload.base,
3974
+ remote: this.deps.workspaces.publication !== undefined,
3975
+ },
3976
+ })
3977
+ }
3978
+ throw error
3979
+ }
3980
+ }
3981
+
3847
3982
  private async confirmedWorkspacePublication(events: CurrentBuildFacts, slug: string) {
3848
3983
  const sha = await readBuildSelector(this.store, slug, 'publishedBranchHead')
3849
3984
  return sha === undefined ? undefined : { sha, cacheHeads: events.gitTips }
@@ -3864,6 +3999,7 @@ export class Dispatcher {
3864
3999
  cleanupPending: boolean
3865
4000
  },
3866
4001
  ): Promise<void> {
4002
+ if (await this.holdForMissingAccounts(input.error)) return
3867
4003
  const execution = events.state.executions.at(-1)
3868
4004
  const _appended = await appendInfrastructureFailure(
3869
4005
  { store: this.store, ids: this.deps.ids },
@@ -3913,6 +4049,16 @@ export class Dispatcher {
3913
4049
  // failure propagates — a stale workspace with an unrecorded pending
3914
4050
  // request is never reaped (the next tick retries).
3915
4051
  try {
4052
+ await preserveWorkspaceBeforeRelease({
4053
+ store: this.store,
4054
+ slug,
4055
+ owner: this.workspaceOwner(open)!,
4056
+ forge: this.deps.forge,
4057
+ exec: this.deps.exec,
4058
+ reason,
4059
+ now: this.deps.clock(),
4060
+ })
4061
+ events = (await readBuildFacts(this.store, slug)).value
3916
4062
  events = await settlePublicationFactsBeforeRelease(
3917
4063
  { store: this.store, settlePublication: this.settlePublication },
3918
4064
  slug,
@@ -3923,7 +4069,15 @@ export class Dispatcher {
3923
4069
  // Keep this generation and its pending work until forge recovery,
3924
4070
  // while allowing the sweep to supervise the remaining builds.
3925
4071
  if (error instanceof ForgeRequestDeferred) return false
3926
- throw error
4072
+ if (!(error instanceof WorkspaceFenceUnknown)) throw error
4073
+ await this.recordInfrastructureFailure(slug, events, {
4074
+ provider: open.provider,
4075
+ workspaceRef: open.ref,
4076
+ operation: 'reconcile',
4077
+ error,
4078
+ cleanupPending: true,
4079
+ })
4080
+ return false
3927
4081
  }
3928
4082
  const attempt = (events.cleanupCounts[JSON.stringify(open.ref)] ?? 0) + 1
3929
4083
  try {
@@ -4004,6 +4158,16 @@ export class Dispatcher {
4004
4158
  // pending publication BEFORE any provider cleanup call, while the
4005
4159
  // workspace still exists. The guard's append failure propagates — the
4006
4160
  // release never proceeds past an unrecorded pending request.
4161
+ await preserveWorkspaceBeforeRelease({
4162
+ store: this.store,
4163
+ slug,
4164
+ owner,
4165
+ forge: this.deps.forge,
4166
+ exec: this.deps.exec,
4167
+ reason,
4168
+ now: this.deps.clock(),
4169
+ })
4170
+ events = (await readBuildFacts(this.store, slug)).value
4007
4171
  events = await settlePublicationFactsBeforeRelease(
4008
4172
  { store: this.store, settlePublication: this.settlePublication },
4009
4173
  slug,
@@ -4063,42 +4227,12 @@ export class Dispatcher {
4063
4227
  } satisfies EventWrite<'workspace.released'>)
4064
4228
  }
4065
4229
 
4066
- /** Current tip of the base branch. A forge with the checkout-less
4067
- * `remoteBranchSha` capability answers from the GitHub API (origin mode);
4068
- * otherwise `git ls-remote <path> refs/heads/<b>` against the dispatcher's
4069
- * physical checkout (§15.7: no network). The checkout, not the store
4070
- * identity — `deps.repo` is the normalized origin since the identity
4071
- * change, and ls-remote against it would hit the network from a URL.
4072
- * Origin-less fixtures whose identity is a path keep working through the
4073
- * fallback. */
4230
+ /** Only the authoritative forge may resolve a destination tip. */
4074
4231
  private async baseSha(baseBranch: string): Promise<string> {
4075
- const remoteBranchSha = this.deps.forge.remoteBranchSha
4076
- if (remoteBranchSha !== undefined) {
4077
- try {
4078
- return await remoteBranchSha.call(this.deps.forge, baseBranch)
4079
- } catch {
4080
- // A forge that advertises the capability but cannot resolve this branch
4081
- // (a checkout-mode adapter, an unseeded test fake, or a transient
4082
- // remote failure) falls through to the physical checkout's git read.
4083
- // In origin mode there is no checkout, so the git read's failure is the
4084
- // actionable error and the tick still fails closed.
4085
- }
4086
- }
4087
- const args = [
4088
- 'git',
4089
- 'ls-remote',
4090
- this.deps.checkout ?? this.deps.repo,
4091
- `refs/heads/${baseBranch}`,
4092
- ]
4093
- const result = await this.deps.exec(args, {})
4094
- const sha = result.stdout.trim().split(/\s+/)[0]
4095
- if (result.exitCode !== 0 || !sha) {
4096
- throw new Error(
4097
- `${args.join(' ')} exited ${result.exitCode}: ${
4098
- result.stderr.trim() || result.stdout.trim() || '(no output)'
4099
- }`,
4100
- )
4101
- }
4232
+ const read = this.deps.forge.remoteBranchSha
4233
+ if (!read) throw new Error('forge remoteBranchSha capability unavailable')
4234
+ const sha = await read.call(this.deps.forge, baseBranch)
4235
+ assertTargetOid(sha)
4102
4236
  return sha
4103
4237
  }
4104
4238
 
@@ -4173,6 +4307,7 @@ export class Dispatcher {
4173
4307
  assets?: PinnedAsset[]
4174
4308
  },
4175
4309
  ): Promise<DispatchOutcome> {
4310
+ if (!this.accountsAvailable()) return 'parked'
4176
4311
  const store = this.store
4177
4312
  const { config } = this.deps
4178
4313
  if (await deferMixedVersion(this.store, record.slug)) return 'parked'
@@ -4230,7 +4365,7 @@ export class Dispatcher {
4230
4365
  return 'deferred'
4231
4366
  }
4232
4367
  const priorGenerations = events.workspaceGenerations
4233
- const handle = await this.deps.workspaces.provision({
4368
+ const handle = await this.provisionWorkspace(record.slug, {
4234
4369
  // Local providers provision FROM the physical checkout; remote
4235
4370
  // providers ignore the value (their host seams are injected).
4236
4371
  repo: this.deps.checkout ?? this.deps.repo,
@@ -4260,6 +4395,7 @@ export class Dispatcher {
4260
4395
  events = (await readBuildFacts(store, record.slug)).value
4261
4396
  }
4262
4397
  } catch (error) {
4398
+ if (await this.holdForMissingAccounts(error)) return 'parked'
4263
4399
  if (error instanceof MixedVersionDeferral) return 'parked'
4264
4400
  const events = (await readBuildFacts(store, record.slug)).value
4265
4401
  if (stage === 'workspace' && this.deps.workspaces.recovery !== undefined) {
@@ -4406,11 +4542,13 @@ export class Dispatcher {
4406
4542
  if (launchState.status !== 'queued' || launchState.discardRequest !== undefined) {
4407
4543
  return 'parked'
4408
4544
  }
4545
+ if (!this.accountsAvailable()) return 'parked'
4409
4546
  if (launched === undefined) await this.deps.launchRunner(record.slug)
4410
4547
  else await this.launch(record.slug, launched, report)
4411
4548
  if (authored && report !== undefined) report.authored += 1
4412
4549
  return 'completed'
4413
4550
  } catch (error) {
4551
+ if (await this.holdForMissingAccounts(error)) return 'parked'
4414
4552
  const events = (await readBuildFacts(store, record.slug)).value
4415
4553
  const attempt = events.dispatchFailureCount + 1
4416
4554
  const message = (
@@ -4568,14 +4706,6 @@ export class Dispatcher {
4568
4706
  if (this.outOfBudget(opts)) break
4569
4707
  if (record.lease) {
4570
4708
  if (new Date(record.lease.expiresAt).getTime() > now) continue // healthy
4571
- } else if (now - new Date(record.updatedAt).getTime() < this.leaseTtlMs) {
4572
- const facts = await this.store.buildFacts(record.slug)
4573
- const cleanup = facts.state.verifyStage.cleanupExecutionSeq
4574
- if (
4575
- facts.lastExecution !== 'relaunch' &&
4576
- !(cleanup !== undefined && facts.state.verifyStage.executionSeq <= cleanup)
4577
- )
4578
- continue // absent lease within the first-claim grace (see DispatcherOpts)
4579
4709
  }
4580
4710
  const facts = await this.store.buildFacts(record.slug)
4581
4711
  const state = facts.state
@@ -4619,6 +4749,24 @@ export class Dispatcher {
4619
4749
  const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
4620
4750
  if (decision === undefined) continue
4621
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
4769
+
4622
4770
  if (
4623
4771
  state.kind === 'node' &&
4624
4772
  (!integrationCurrent(state) || facts.workspace === null) &&
@@ -4638,6 +4786,7 @@ export class Dispatcher {
4638
4786
  // proved end settles first (completion facts, lease release, publication)
4639
4787
  // and then falls through to the normal decision; a provider-proved loss
4640
4788
  // falls through to the existing stale path below.
4789
+ let orphanRecoveryDue = orphanEligible(state) && facts.open === null
4641
4790
  const foreignExecution = facts.open
4642
4791
  // A provider- or log-proved end in the same generation re-attaches in
4643
4792
  // place: the guest finished its work, the workspace is still the
@@ -4674,6 +4823,10 @@ export class Dispatcher {
4674
4823
  foreignExecution,
4675
4824
  )
4676
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)
4677
4830
  if (settlement === 'settled') {
4678
4831
  report.settled += 1
4679
4832
  endedInPlace = true
@@ -4690,7 +4843,7 @@ export class Dispatcher {
4690
4843
  // build's, and replacing the environment would discard a healthy
4691
4844
  // generation. Only an unproven stale lease or a proved loss reaps.
4692
4845
  if (open !== null && this.workspaceOwner(open)?.recovery !== undefined && !endedInPlace) {
4693
- const parked = decision.kind === 'wait' && !publicationRecoveryDue
4846
+ const parked = decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue
4694
4847
  const reason =
4695
4848
  state.status === 'paused'
4696
4849
  ? ('pause' as const)
@@ -4718,7 +4871,7 @@ export class Dispatcher {
4718
4871
  // fresh runner for a paused or blocked build whose workspace was just
4719
4872
  // reaped. Every other path that reaches this line with a wait decision
4720
4873
  // already continued earlier.
4721
- if (decision.kind === 'wait' && !publicationRecoveryDue) continue
4874
+ if (decision.kind === 'wait' && !publicationRecoveryDue && !orphanRecoveryDue) continue
4722
4875
  if (
4723
4876
  facts.workspace === null &&
4724
4877
  this.deps.workspaces.recovery !== undefined &&
@@ -4734,8 +4887,26 @@ export class Dispatcher {
4734
4887
  // boundaries and the launch; this tick performs neither.
4735
4888
  continue
4736
4889
  }
4737
- const result = await this.launch(record.slug, launched, report)
4738
- if (result === 'scheduled') report.swept += 1
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
4909
+ }
4739
4910
  }
4740
4911
  }
4741
4912
 
@@ -4888,6 +5059,7 @@ export class Dispatcher {
4888
5059
  opts: TickOpts = {},
4889
5060
  autoMergeSeedFact: AutoMergeDefaultFact | undefined = undefined,
4890
5061
  ): Promise<void> {
5062
+ if (!this.accountsAvailable()) return
4891
5063
  const health = this.store.repositoryFacts().forgeHealth
4892
5064
  if (health && Date.parse(health.resetAt) > this.deps.clock().getTime()) return
4893
5065
  const store = this.store
@@ -5720,13 +5892,14 @@ export class Dispatcher {
5720
5892
  }
5721
5893
  }
5722
5894
 
5895
+ if (!this.accountsAvailable()) return
5723
5896
  if (!(await this.nodeHasCapacity(record.slug))) return
5724
5897
  if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
5725
5898
  const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
5726
5899
  if (kicked === 'kicked') report.provisioning += 1
5727
5900
  } else {
5728
5901
  if (openWorkspace(facts) === null) {
5729
- const handle = await this.deps.workspaces.provision({
5902
+ const handle = await this.provisionWorkspace(record.slug, {
5730
5903
  repo: checkout,
5731
5904
  baseBranch: state.baseBranch!,
5732
5905
  branch: record.branch!,
@@ -5749,6 +5922,7 @@ export class Dispatcher {
5749
5922
  }
5750
5923
  }
5751
5924
  } catch (error) {
5925
+ if (await this.holdForMissingAccounts(error)) return
5752
5926
  const message =
5753
5927
  error instanceof Error || isForgeFailure(error) ? error.message : String(error)
5754
5928
  // Safety refusals require human judgment. Infrastructure failures remain
@@ -5790,6 +5964,7 @@ export class Dispatcher {
5790
5964
  sampling: { refreshOnly?: boolean } = {},
5791
5965
  ): Promise<void> {
5792
5966
  if (
5967
+ state.targetRewrite ||
5793
5968
  state.status === 'paused' ||
5794
5969
  state.status === 'done' ||
5795
5970
  state.status === 'aborted' ||
@@ -5955,6 +6130,7 @@ export class Dispatcher {
5955
6130
  await this.observeIntegration(record.slug)
5956
6131
  state = (await this.store.buildFacts(record.slug)).state
5957
6132
  if (!integrationCurrent(state)) return
6133
+ if (!this.accountsAvailable()) return
5958
6134
  const facts = (await readBuildFacts(this.store, record.slug)).value
5959
6135
  if (openWorkspace(facts) === null && this.deps.workspaces.recovery) {
5960
6136
  const kicked = await this.ensureProvisionContinuation(record, facts, 'launch')
@@ -5962,12 +6138,18 @@ export class Dispatcher {
5962
6138
  return
5963
6139
  }
5964
6140
  if (openWorkspace(facts) === null) {
5965
- const handle = await this.deps.workspaces.provision({
5966
- repo: this.deps.checkout ?? this.deps.repo,
5967
- baseBranch: record.branch,
5968
- branch: record.branch,
5969
- revision: state.integration!.cycle!.head,
5970
- })
6141
+ let handle: WorkspaceProvisionResult
6142
+ try {
6143
+ handle = await this.provisionWorkspace(record.slug, {
6144
+ repo: this.deps.checkout ?? this.deps.repo,
6145
+ baseBranch: record.branch,
6146
+ branch: record.branch,
6147
+ revision: state.integration!.cycle!.head,
6148
+ })
6149
+ } catch (error) {
6150
+ if (await this.holdForMissingAccounts(error)) return
6151
+ throw error
6152
+ }
5971
6153
  await this.store.append(record.slug, {
5972
6154
  actor: DISPATCHER,
5973
6155
  type: 'workspace.provisioned',
@@ -25,6 +25,8 @@ export const executionProgress = {
25
25
  'landing.forge-merged': 'progress',
26
26
  'landing.native-applied': 'bookkeeping',
27
27
  'target.distance': 'bookkeeping',
28
+ 'target.rewritten': 'bookkeeping',
29
+ 'target.rewrite-cleared': 'bookkeeping',
28
30
  'target.moved': 'bookkeeping',
29
31
  'restack.prepared': 'progress',
30
32
  'restack.replayed': 'progress',
@@ -71,6 +73,10 @@ export const executionProgress = {
71
73
  'runner.setup-failed': 'failure',
72
74
  'workspace.provisioned': 'bookkeeping',
73
75
  'workspace.provision-started': 'bookkeeping',
76
+ 'workspace.cleanup-required': 'bookkeeping',
77
+ 'workspace.fenced': 'bookkeeping',
78
+ 'workspace.commits-preserved': 'bookkeeping',
79
+ 'workspace.commits-lost': 'bookkeeping',
74
80
  'workspace.released': 'bookkeeping',
75
81
  'execution.started': 'bookkeeping',
76
82
  'execution.ended': 'bookkeeping',
@@ -82,6 +88,7 @@ export const executionProgress = {
82
88
  'pr-summary.settled': 'progress',
83
89
  'finalize.step-started': 'progress',
84
90
  'publication.requested': 'progress',
91
+ 'publication.candidate-retired': 'progress',
85
92
  'publication.lost': 'progress',
86
93
  'publication.retry-scheduled': 'failure',
87
94
  'publication.retry-exhausted': 'failure',
@@ -915,8 +915,11 @@ export class HarvestRunner {
915
915
  throw error
916
916
  }
917
917
 
918
- const since = await store.getRepoEvents(repo, started.seq)
919
- const terminal = since.some((event) => spec.terminal(event, session))
918
+ const hasTerminal = async () => {
919
+ const event = (await readRepositoryFacts(store, repo)).value.harvestTerminals[session]
920
+ return event !== undefined && event.seq > started.seq && spec.terminal(event, session)
921
+ }
922
+ const terminal = await hasTerminal()
920
923
  const owner = live?.runner ?? target.runner
921
924
  const close =
922
925
  streamBracket !== undefined
@@ -942,11 +945,7 @@ export class HarvestRunner {
942
945
  if (spec.producer) this.producer = undefined
943
946
  // Cleanup can finish a typed deposit already in flight. Its terminal
944
947
  // wins even when cancellation initially observed no result.
945
- const completed =
946
- terminal ||
947
- (await store.getRepoEvents(repo, started.seq)).some((event) =>
948
- spec.terminal(event, session),
949
- )
948
+ const completed = terminal || (await hasTerminal())
950
949
  if (completed) {
951
950
  await this.depositTranscript(spec, session, content, usage, target.model, close)
952
951
  return
@@ -37,7 +37,7 @@ export interface PublicationLedger {
37
37
  }
38
38
 
39
39
  /** Bump when `PublicationLedger` or its fold changes. */
40
- export const PUBLICATION_STATE_REDUCER_VERSION = 6
40
+ export const PUBLICATION_STATE_REDUCER_VERSION = 7
41
41
 
42
42
  function compact(event: AbEvent): LedgerItem | undefined {
43
43
  switch (event.type) {
@@ -45,6 +45,7 @@ function compact(event: AbEvent): LedgerItem | undefined {
45
45
  return { t: 'request', seq: event.seq, event }
46
46
  case 'restack.completed':
47
47
  return { t: 'restack', seq: event.seq, id: event.payload.id, head: event.payload.headSha }
48
+ case 'publication.candidate-retired':
48
49
  case 'restack.contended':
49
50
  case 'reconcile.contended':
50
51
  return { t: 'cancelled', seq: event.seq, request: event.payload.request }