@defrex/autobuild 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +118 -14
  3. package/docs/accounts.md +12 -1
  4. package/docs/answering-blocked-builds.md +4 -1
  5. package/docs/architecture.md +120 -7
  6. package/docs/builds.md +2 -0
  7. package/docs/configuration-overview.md +6 -0
  8. package/docs/configuration.md +6 -0
  9. package/docs/integration-tree.md +16 -5
  10. package/docs/operator-api.md +44 -6
  11. package/docs/operator-surfaces.md +29 -0
  12. package/docs/plugin-authoring.md +6 -1
  13. package/docs/remote-store-protocol.md +69 -10
  14. package/docs/restacking.md +45 -0
  15. package/docs/spec-standard.md +4 -2
  16. package/docs/ticket-dependencies.md +8 -0
  17. package/package.json +3 -3
  18. package/packages/core/src/cli/dispatch-frontend.ts +1 -0
  19. package/packages/core/src/cli/dispatch-repository-feed.ts +107 -26
  20. package/packages/core/src/cli/dispatch.ts +64 -25
  21. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  22. package/packages/core/src/cli/forge-clear.ts +30 -0
  23. package/packages/core/src/cli/help.ts +1 -0
  24. package/packages/core/src/cli/main.ts +28 -0
  25. package/packages/core/src/cli/watch.ts +9 -13
  26. package/packages/core/src/events/catalog.ts +1 -0
  27. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  28. package/packages/core/src/events/payloads.ts +10 -0
  29. package/packages/core/src/events/policy.ts +9 -0
  30. package/packages/core/src/events/repository.ts +73 -2
  31. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +275 -0
  32. package/packages/core/src/kernel/change-presence.ts +74 -8
  33. package/packages/core/src/kernel/engine.ts +8 -0
  34. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  35. package/packages/core/src/kernel/node-polling.ts +40 -7
  36. package/packages/core/src/kernel/node-restack-demand.ts +74 -0
  37. package/packages/core/src/kernel/node-restack-state.ts +5 -1
  38. package/packages/core/src/kernel/node-restack-transaction.ts +33 -1
  39. package/packages/core/src/kernel/read-facts.ts +6 -0
  40. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  41. package/packages/core/src/kernel/reducer.ts +1 -1
  42. package/packages/core/src/kernel/ticket-preparation.ts +66 -0
  43. package/packages/core/src/operator/annotations.ts +6 -0
  44. package/packages/core/src/operator/control.ts +20 -0
  45. package/packages/core/src/operator/index.ts +2 -0
  46. package/packages/core/src/operator/registry.ts +20 -0
  47. package/packages/core/src/ports/runner/account-env.ts +60 -9
  48. package/packages/core/src/ports/runner/claude.ts +49 -45
  49. package/packages/core/src/processes/dispatcher.ts +470 -121
  50. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  51. package/packages/core/src/processes/harvest.ts +11 -16
  52. package/packages/core/src/processes/repo-view.ts +3 -0
  53. package/packages/core/src/store/artifact-meta.ts +7 -0
  54. package/packages/core/src/store/contract.ts +57 -0
  55. package/packages/core/src/store/memory.ts +4 -0
  56. package/packages/core/src/store/reducer-value-shapes.json +7302 -6668
  57. package/packages/core/src/store/reducer-value-validation.ts +106 -6
  58. package/packages/core/src/store/remote/client.ts +48 -8
  59. package/packages/core/src/store/remote/compatibility.ts +39 -0
  60. package/packages/core/src/store/remote/index.ts +6 -0
  61. package/packages/core/src/store/remote/protocol.ts +8 -1
  62. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  63. package/packages/core/src/store/remote/version.ts +4 -0
  64. package/packages/core/src/store/repo-state-events.ts +4 -2
  65. package/packages/core/src/store/snapshots.ts +16 -3
  66. package/packages/core/src/store/types.ts +2 -0
  67. package/packages/core/src/testing/dispatch-read-budget.ts +144 -5
  68. package/packages/core/src/testing/index.ts +1 -1
  69. package/packages/core/src/testing/reduced-read-budget.ts +513 -5
  70. package/skills/guide/SKILL.md +44 -7
  71. package/skills/guide/references/accounts.md +12 -1
  72. package/skills/guide/references/integration-tree.md +16 -5
  73. package/skills/guide/references/operator-api.md +44 -6
  74. package/skills/guide/references/plugin-authoring.md +6 -1
  75. package/skills/guide/references/remote-store-protocol.md +69 -10
  76. package/skills/guide/references/restacking.md +45 -0
  77. package/skills/guide/references/spec-standard.md +4 -2
  78. package/skills/guide/references/ticket-dependencies.md +8 -0
  79. package/skills/operate/SKILL.md +21 -5
  80. package/skills/reconcile/SKILL.md +6 -0
  81. package/skills/tickets/SKILL.md +7 -3
  82. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,5 @@
1
+ import { ArtifactMetaUnsupportedError } from '../store/artifact-meta'
2
+ import type { TicketPreparation } from '../kernel/ticket-preparation'
1
3
  import { sampleTargetDistance } from '../kernel/target-distance'
2
4
  import { capturedBuildConfig } from './verify-cycle-config'
3
5
  import { publicationRetryGate } from '../kernel/publication-retry'
@@ -8,6 +10,8 @@ import {
8
10
  import {
9
11
  nodeActivityKey,
10
12
  nodePollingSchedule,
13
+ nodePollingCheckpointRequired,
14
+ nodePollingEvidenceValid,
11
15
  nodePollingUnsettled,
12
16
  nodeTicketObservationKey,
13
17
  } from '../kernel/node-polling'
@@ -17,7 +21,13 @@ import {
17
21
  migrationIdentity,
18
22
  historicalTicketIdentity,
19
23
  } from '../kernel/ticket-migrations'
20
- import { nodeRestackDemand, presenceRestackPath } from '../kernel/node-restack-demand'
24
+ import { suspendNativeLanding } from '../kernel/landing-publication'
25
+ import {
26
+ actionableRestackDemand,
27
+ restackAvailabilityFingerprint,
28
+ restackLandingKey,
29
+ presenceRestackPath,
30
+ } from '../kernel/node-restack-demand'
21
31
  import {
22
32
  deferMixedVersion,
23
33
  mixedVersionDeferred,
@@ -59,7 +69,11 @@ import {
59
69
  blockerBuild,
60
70
  missingChanges,
61
71
  presenceInputs,
62
- observePresence,
72
+ confirmedLandings,
73
+ presenceWitness,
74
+ projectPresence,
75
+ presenceEvidence,
76
+ destinationAliases,
63
77
  ownedContribution,
64
78
  type ChangeIdentity,
65
79
  type PresenceInputs,
@@ -371,9 +385,9 @@ export interface TickReport {
371
385
  abandoned: number
372
386
  /** Janitor: queued builds explicitly discarded and returned to Ready. */
373
387
  discarded: number
374
- /** Janitor failures contained to individual builds during this pass. */
388
+ /** Contained build janitor and ticket-preparation recovery failures this pass. */
375
389
  janitorFailed: number
376
- /** One actionable line per contained janitor failure, attributed by slug. */
390
+ /** One actionable line per contained failure, attributed by build or attempt. */
377
391
  janitorDiagnostics: string[]
378
392
  /** Ordinary-tick recovery completed an interrupted post-creation dispatch. */
379
393
  recovered: number
@@ -687,6 +701,8 @@ export function heldByRepositoryPause(state: BuildState, paused: boolean): boole
687
701
  return paused && state.status === 'queued'
688
702
  }
689
703
 
704
+ export const SWEEP_PIN_CACHE_CAPACITY = 128
705
+
690
706
  export class Dispatcher {
691
707
  // Only scheduling is cached. Eligibility facts still come from durable state,
692
708
  // and each admitted verification/publication samples the source this pass.
@@ -779,28 +795,72 @@ export class Dispatcher {
779
795
  })
780
796
  }
781
797
 
798
+ // Disposable parsed pins only. Current facts, live policy and cycle captures
799
+ // are recomputed on every decision; action boundaries never use this cache.
800
+ private readonly sweepPins = new Map<string, { revision: number; config: Config }>()
801
+
782
802
  /** Read at each decision boundary: artifact revisions are independent of events. */
783
803
  private async decideBuild(
784
804
  slug: string,
785
805
  state: Parameters<typeof decideNextFromFacts>[0],
786
806
  log: Parameters<typeof decideNextFromFacts>[1],
787
807
  report: TickReport,
808
+ sweep = false,
788
809
  ): Promise<ReturnType<typeof decideNextFromFacts> | undefined> {
789
810
  let revision: number | undefined
790
811
  try {
791
- let artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
792
- if (artifact === null) return decideNextFromFacts(state, log, this.deps.config)
793
- revision = artifact.meta.revision
794
- let pinned: Config
795
- try {
796
- pinned = parseEffectiveBuildConfig(artifact)
797
- } catch (error) {
798
- if (this.deps.repairBuildConfig === undefined) throw error
799
- await this.deps.repairBuildConfig(slug)
800
- artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
801
- if (artifact === null) throw new Error('configuration repair deposited no pipeline')
812
+ let pinned: Config | undefined
813
+ let cacheable = false
814
+ if (sweep && this.store.getLatestArtifactMeta) {
815
+ try {
816
+ const meta = await this.store.getLatestArtifactMeta(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
817
+ if (meta === null) {
818
+ this.sweepPins.delete(slug)
819
+ return decideNextFromFacts(state, log, this.deps.config)
820
+ }
821
+ revision = meta.revision
822
+ cacheable = true
823
+ const cached = this.sweepPins.get(slug)
824
+ if (cached?.revision === revision) {
825
+ pinned = cached.config
826
+ // Map insertion order is the deterministic LRU order.
827
+ this.sweepPins.delete(slug)
828
+ this.sweepPins.set(slug, cached)
829
+ } else {
830
+ this.sweepPins.delete(slug)
831
+ }
832
+ } catch (error) {
833
+ if (!(error instanceof ArtifactMetaUnsupportedError)) throw error
834
+ this.sweepPins.delete(slug)
835
+ }
836
+ }
837
+ if (pinned === undefined) {
838
+ let artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
839
+ if (artifact === null) {
840
+ this.sweepPins.delete(slug)
841
+ return decideNextFromFacts(state, log, this.deps.config)
842
+ }
802
843
  revision = artifact.meta.revision
803
- pinned = parseEffectiveBuildConfig(artifact)
844
+ try {
845
+ pinned = parseEffectiveBuildConfig(artifact)
846
+ } catch (error) {
847
+ this.sweepPins.delete(slug)
848
+ if (this.deps.repairBuildConfig === undefined) throw error
849
+ await this.deps.repairBuildConfig(slug)
850
+ artifact = await this.store.getArtifact(slug, BUILD_EFFECTIVE_CONFIG_ARTIFACT)
851
+ if (artifact === null) throw new Error('configuration repair deposited no pipeline')
852
+ revision = artifact.meta.revision
853
+ pinned = parseEffectiveBuildConfig(artifact)
854
+ }
855
+ if (cacheable) {
856
+ // A concurrent deposit may have advanced the revision after the probe:
857
+ // label the bytes with the full response's revision, never the probe's.
858
+ this.sweepPins.delete(slug)
859
+ this.sweepPins.set(slug, { revision, config: pinned })
860
+ if (this.sweepPins.size > SWEEP_PIN_CACHE_CAPACITY) {
861
+ this.sweepPins.delete(this.sweepPins.keys().next().value!)
862
+ }
863
+ }
804
864
  }
805
865
  return decideNextFromFacts(
806
866
  state,
@@ -813,6 +873,7 @@ export class Dispatcher {
813
873
  ),
814
874
  )
815
875
  } catch (error) {
876
+ this.sweepPins.delete(slug)
816
877
  report.blockedDiagnostics.push(
817
878
  `build ${slug} pipeline${revision === undefined ? '' : ` revision ${revision}`} unavailable: pipeline decisions withheld; next tick retries. Restore readable build-branch configuration or use a compatible dispatcher version. ${error instanceof Error || isForgeFailure(error) ? error.message : String(error)}`,
818
879
  )
@@ -855,6 +916,12 @@ export class Dispatcher {
855
916
  * slug here defers to the continuation; it never blocks on it. */
856
917
  private readonly continuations = new Map<string, ProvisionContinuation>()
857
918
 
919
+ // Batched confirmed landing evidence is shared across nodes for this tick.
920
+ // Only durable availability facts authorize the shortcut after restart.
921
+ private availabilityLandings?: ReturnType<typeof confirmedLandings>
922
+ private availabilityLandingKey?: string
923
+ private availabilityEntries?: ReturnType<Dispatcher['repoBuildDigests']>
924
+
858
925
  /** The incremental repository view every stage reads and writes through
859
926
  * (AUT-647): `deps.store` itself when the caller already wrapped it. */
860
927
  private readonly store: RepoViewStore
@@ -909,6 +976,9 @@ export class Dispatcher {
909
976
 
910
977
  lastForgeRequests?: import('../ports/forge-telemetry').ForgeRequestCounts
911
978
  async tick(opts: TickOpts = {}): Promise<TickReport> {
979
+ this.availabilityEntries = undefined
980
+ this.availabilityLandings = undefined
981
+ this.availabilityLandingKey = undefined
912
982
  const builds = new Map<string, number>()
913
983
  let total = 0
914
984
  let unattributed = 0
@@ -990,6 +1060,8 @@ export class Dispatcher {
990
1060
  // durable fact drives it, so a second dispatcher polling the same
991
1061
  // repository converges the same state.
992
1062
  if (this.outOfBudget(opts)) return report
1063
+ await this.recoverTicketPreparations(report, opts)
1064
+ if (this.outOfBudget(opts)) return report
993
1065
  await this.janitor(report, launched, opts)
994
1066
  if (this.outOfBudget(opts)) return report
995
1067
  await this.recoverDispatches(report, launched, paused, opts)
@@ -1212,7 +1284,17 @@ export class Dispatcher {
1212
1284
  }
1213
1285
  const activeTicketIds = await this.activeTicketIdentities(refs, listing.tickets)
1214
1286
  report.queued = listing.tickets.filter(
1215
- (ticket) => !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`),
1287
+ (ticket) =>
1288
+ !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
1289
+ !Object.values(this.store.repositoryFacts().preparation).some((attempt) => {
1290
+ const ref = resolveTicketRef(
1291
+ this.store.repositoryFacts().ticketMigrations,
1292
+ attempt.ticket,
1293
+ this.deps.tickets.name,
1294
+ attempt.slug ?? attempt.attempt,
1295
+ )
1296
+ return ref.source === ticket.ref.source && ref.id === ticket.ref.id
1297
+ }),
1216
1298
  ).length
1217
1299
  report.invalidTickets = listing.diagnostics.length
1218
1300
  report.ticketDiagnostics = [...listing.diagnostics]
@@ -2042,21 +2124,24 @@ export class Dispatcher {
2042
2124
  )
2043
2125
  return
2044
2126
  const now = this.deps.clock().toISOString()
2045
- const previousCheck = pollStart.nodePolling
2127
+ const previousCheck = current.nodePolling
2128
+ if (
2129
+ !nodePollingCheckpointRequired(current, key, this.deps.config.policy, new Date(now))
2130
+ )
2131
+ return
2046
2132
  await this.store.appendIfCurrent(record.slug, current.lastSeq, {
2047
2133
  actor: DISPATCHER,
2048
2134
  type: 'node.poll-checked',
2049
2135
  payload: {
2050
2136
  activityKey: key,
2051
- unchangedSince:
2052
- previousCheck?.activityKey === key &&
2053
- previousCheck.nodeIdleAfterSeconds ===
2054
- this.deps.config.policy.nodeIdleAfterSeconds &&
2055
- previousCheck.nodeIdlePollSeconds ===
2056
- this.deps.config.policy.nodeIdlePollSeconds &&
2057
- Date.parse(previousCheck.unchangedSince) <= Date.parse(now)
2058
- ? previousCheck.unchangedSince
2059
- : now,
2137
+ unchangedSince: nodePollingEvidenceValid(
2138
+ current,
2139
+ key,
2140
+ this.deps.config.policy,
2141
+ new Date(now),
2142
+ )
2143
+ ? previousCheck!.unchangedSince
2144
+ : now,
2060
2145
  nodeIdleAfterSeconds: this.deps.config.policy.nodeIdleAfterSeconds,
2061
2146
  nodeIdlePollSeconds: this.deps.config.policy.nodeIdlePollSeconds,
2062
2147
  },
@@ -4531,7 +4616,7 @@ export class Dispatcher {
4531
4616
  throw error
4532
4617
  }
4533
4618
  }
4534
- const decision = await this.decideBuild(record.slug, state, facts.log, report)
4619
+ const decision = await this.decideBuild(record.slug, state, facts.log, report, true)
4535
4620
  if (decision === undefined) continue
4536
4621
  if (state.status === 'done' || state.status === 'aborted') continue
4537
4622
  if (
@@ -4558,7 +4643,17 @@ export class Dispatcher {
4558
4643
  // place: the guest finished its work, the workspace is still the
4559
4644
  // build's, and replacing the environment would discard a healthy
4560
4645
  // generation. Only an unproven stale lease or a proved loss reaps.
4561
- let endedInPlace = facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch'
4646
+ // A start that later found the open workspace missing is a proved loss
4647
+ // too: the recorded end no longer vouches for an environment that is
4648
+ // gone, and re-attaching would fail against the same ref forever.
4649
+ const failure = state.infrastructureFailure
4650
+ const workspaceMissing =
4651
+ failure?.cause === 'missing' &&
4652
+ failure.operation === 'start' &&
4653
+ failure.workspaceRef === facts.workspace?.ref
4654
+ let endedInPlace =
4655
+ (facts.lastExecution === 'completed' || facts.lastExecution === 'relaunch') &&
4656
+ !workspaceMissing
4562
4657
  if (
4563
4658
  foreignExecution !== null &&
4564
4659
  foreignExecution.commandId !== undefined &&
@@ -4644,6 +4739,145 @@ export class Dispatcher {
4644
4739
  }
4645
4740
  }
4646
4741
 
4742
+ /** Retry a fixed batch under the same repository ownership as intake.
4743
+ * No provider calls for parked deadlines; no history or orphan scans. */
4744
+ private async recoverTicketPreparations(report: TickReport, opts: TickOpts): Promise<void> {
4745
+ const pending = Object.values(this.store.repositoryFacts().preparation)
4746
+ .filter(
4747
+ (attempt) => !attempt.retryAt || Date.parse(attempt.retryAt) <= this.deps.clock().getTime(),
4748
+ )
4749
+ .sort(
4750
+ (a, b) =>
4751
+ Date.parse(a.retryAt ?? '1970-01-01T00:00:00.000Z') -
4752
+ Date.parse(b.retryAt ?? '1970-01-01T00:00:00.000Z') ||
4753
+ a.attempt.localeCompare(b.attempt),
4754
+ )
4755
+ .slice(0, 8)
4756
+ const failures: unknown[] = []
4757
+ for (const attempt of pending) {
4758
+ if (this.outOfBudget(opts)) break
4759
+ try {
4760
+ await this.recoverTicketPreparation(attempt)
4761
+ } catch (error) {
4762
+ failures.push(error)
4763
+ }
4764
+ }
4765
+ for (const error of failures) {
4766
+ report.janitorFailed += 1
4767
+ report.janitorDiagnostics.push(String(error))
4768
+ }
4769
+ }
4770
+
4771
+ private async preparationResolved(
4772
+ attempt: TicketPreparation,
4773
+ outcome: 'lost-claim' | 'handed-back' | 'bounced' | 'owned' | 'abandoned',
4774
+ reason?: string,
4775
+ ): Promise<void> {
4776
+ await this.store.appendRepo(this.deps.repo, {
4777
+ actor: DISPATCHER,
4778
+ type: 'ticket-preparation.resolved',
4779
+ payload: {
4780
+ attempt: attempt.attempt,
4781
+ ticket: attempt.ticket,
4782
+ outcome,
4783
+ ...(reason ? { reason: reason.slice(0, 4000) } : {}),
4784
+ },
4785
+ })
4786
+ }
4787
+
4788
+ private async recoverTicketPreparation(attempt: TicketPreparation): Promise<void> {
4789
+ try {
4790
+ // A rejected create can have committed. Unavailable or conflicting readback
4791
+ // is never absence and must not authorize a ticket transition.
4792
+ if (attempt.slug) {
4793
+ const record = await this.store.getBuild(attempt.slug)
4794
+ if (record) {
4795
+ const created = (await this.store.buildFacts(attempt.slug)).created
4796
+ if (
4797
+ record.repo !== this.deps.repo ||
4798
+ record.ticket?.source !== attempt.ticket.source ||
4799
+ record.ticket?.id !== attempt.ticket.id ||
4800
+ created?.payload.repo !== this.deps.repo ||
4801
+ created.payload.ticket?.source !== attempt.ticket.source ||
4802
+ created.payload.ticket?.id !== attempt.ticket.id
4803
+ )
4804
+ return await this.preparationResolved(
4805
+ attempt,
4806
+ 'abandoned',
4807
+ `Conflicting build ownership at ${attempt.slug}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
4808
+ )
4809
+ await this.preparationResolved(attempt, 'owned')
4810
+ return
4811
+ }
4812
+ }
4813
+ const ref = resolveTicketRef(
4814
+ this.store.repositoryFacts().ticketMigrations,
4815
+ attempt.ticket,
4816
+ this.deps.tickets.name,
4817
+ attempt.slug ?? attempt.attempt,
4818
+ )
4819
+ const ticket = await this.deps.tickets.get(ref.id)
4820
+ if (!ticket)
4821
+ return await this.preparationResolved(
4822
+ attempt,
4823
+ 'abandoned',
4824
+ 'Ticket no longer exists; ticket unchanged.',
4825
+ )
4826
+ if (ticket.state === undefined)
4827
+ return await this.preparationResolved(
4828
+ attempt,
4829
+ 'abandoned',
4830
+ 'Ticket state is unavailable; ticket unchanged. Inspect the provider record before manually retrying.',
4831
+ )
4832
+ const state = (value: string) => value.toLowerCase()
4833
+ const handback = attempt.handback ?? attempt.readyState
4834
+ if (state(ticket.state) === state(handback)) {
4835
+ await this.preparationResolved(
4836
+ attempt,
4837
+ handback === attempt.readyState ? 'handed-back' : 'bounced',
4838
+ )
4839
+ return
4840
+ }
4841
+ if (!attempt.claimed || state(ticket.state) !== state(attempt.claimedState))
4842
+ return await this.preparationResolved(
4843
+ attempt,
4844
+ 'abandoned',
4845
+ `Uncertain claim or externally changed ticket state ${ticket.state}; ticket unchanged. Inspect ownership before manually retrying. Original failure: ${attempt.error ?? 'unknown'}`,
4846
+ )
4847
+ await this.deps.tickets.transition(ref.id, handback)
4848
+ await this.preparationResolved(
4849
+ attempt,
4850
+ handback === attempt.readyState ? 'handed-back' : 'bounced',
4851
+ )
4852
+ } catch (error) {
4853
+ const message = error instanceof Error ? error.message : String(error)
4854
+ try {
4855
+ await this.store.appendRepo(this.deps.repo, {
4856
+ actor: DISPATCHER,
4857
+ type: 'ticket-preparation.recovery-failed',
4858
+ payload: {
4859
+ attempt: attempt.attempt,
4860
+ ticket: attempt.ticket,
4861
+ claimed: attempt.claimed,
4862
+ handback: attempt.handback ?? attempt.readyState,
4863
+ ...(attempt.error ? { preparationError: attempt.error } : {}),
4864
+ error: message.slice(0, 4000) || 'unknown recovery failure',
4865
+ retryAt: new Date(this.deps.clock().getTime() + 30_000).toISOString(),
4866
+ },
4867
+ })
4868
+ } catch (diagnosticError) {
4869
+ throw new AggregateError(
4870
+ [error, diagnosticError],
4871
+ `ticket preparation recovery failed: ${message}; diagnostic append failed: ${String(diagnosticError)}`,
4872
+ )
4873
+ }
4874
+ throw new Error(
4875
+ `ticket preparation recovery failed: ${message}; original preparation failure: ${attempt.error ?? 'unfinished durable preparation'}`,
4876
+ { cause: error },
4877
+ )
4878
+ }
4879
+ }
4880
+
4647
4881
  // ── e. Dispatch (SPEC §12, §6.3) ───────────────────────────────────────────
4648
4882
 
4649
4883
  private async dispatch(
@@ -4696,7 +4930,17 @@ export class Dispatcher {
4696
4930
  ]),
4697
4931
  )
4698
4932
  const ready = listing.tickets.filter(
4699
- (ticket) => !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`),
4933
+ (ticket) =>
4934
+ !activeTicketIds.has(`${ticket.ref.source}:${ticket.ref.id}`) &&
4935
+ !Object.values(this.store.repositoryFacts().preparation).some((attempt) => {
4936
+ const ref = resolveTicketRef(
4937
+ this.store.repositoryFacts().ticketMigrations,
4938
+ attempt.ticket,
4939
+ this.deps.tickets.name,
4940
+ attempt.slug ?? attempt.attempt,
4941
+ )
4942
+ return ref.source === ticket.ref.source && ref.id === ticket.ref.id
4943
+ }),
4700
4944
  )
4701
4945
  report.invalidTickets += listing.diagnostics.length
4702
4946
  report.ticketDiagnostics.push(...listing.diagnostics)
@@ -4926,70 +5170,156 @@ export class Dispatcher {
4926
5170
  continue
4927
5171
  }
4928
5172
  }
4929
- // Claim-before-launch (§12): losing the claim means another dispatcher
4930
- // (or an earlier tick) owns this ticket.
4931
- if (!(await tickets.claim(ticket.ref.id))) {
4932
- report.claimRaces += 1
4933
- report.queued -= 1
4934
- continue
5173
+ const attempt: TicketPreparation = {
5174
+ attempt: this.deps.ids('prep'),
5175
+ ticket: ticket.ref,
5176
+ readyState: config.tickets.readyState,
5177
+ claimedState: ticketLifecycle(config.tickets).doing,
5178
+ claimed: false,
4935
5179
  }
4936
-
4937
- // Freeze the ticket's assets at the claim (SPEC §6.3): sampled before the
4938
- // spec-authoring interval so edits made during it are never pinned.
4939
- const assets = await preparePinnedAssets(tickets, store, this.deps.repo, ticket.ref.id)
4940
-
4941
- // Quality gate (§6.3): import a conforming ticket body as the spec;
4942
- // author one for thin-but-groomed tickets; otherwise bounce.
5180
+ await store.ensureRepo(this.deps.repo)
5181
+ await store.appendRepo(this.deps.repo, {
5182
+ actor: DISPATCHER,
5183
+ type: 'ticket-preparation.intended',
5184
+ payload: {
5185
+ attempt: attempt.attempt,
5186
+ ticket: attempt.ticket,
5187
+ readyState: attempt.readyState,
5188
+ claimedState: attempt.claimedState,
5189
+ },
5190
+ })
5191
+ let stage = 'claim'
5192
+ let established = false
5193
+ let record: BuildRecord
4943
5194
  let body = ticket.body
4944
- let conformance = specConformance(body)
4945
5195
  let authoredSession: string | undefined
4946
- if (!conformance.conforms && this.deps.authorSpec) {
4947
- const authored = await this.deps.authorSpec(ticket)
4948
- if (authored !== null) {
4949
- conformance = specConformance(authored)
4950
- if (conformance.conforms) {
4951
- body = authored
4952
- authoredSession = this.deps.ids('s')
5196
+ let createdSeed: Parameters<Dispatcher['buildCreatedPayload']>[2]
5197
+ try {
5198
+ if (!(await tickets.claim(ticket.ref.id))) {
5199
+ await this.preparationResolved(attempt, 'lost-claim')
5200
+ report.claimRaces += 1
5201
+ report.queued -= 1
5202
+ continue
5203
+ }
5204
+ attempt.claimed = true
5205
+ stage = 'claim-confirmation'
5206
+ await store.appendRepo(this.deps.repo, {
5207
+ actor: DISPATCHER,
5208
+ type: 'ticket-preparation.claimed',
5209
+ payload: { attempt: attempt.attempt, ticket: attempt.ticket },
5210
+ })
5211
+ stage = 'assets'
5212
+ // Freeze the ticket's assets at the claim (SPEC §6.3): sampled before the
5213
+ // spec-authoring interval so edits made during it are never pinned.
5214
+ const assets = await preparePinnedAssets(tickets, store, this.deps.repo, ticket.ref.id)
5215
+
5216
+ // Quality gate (§6.3): import a conforming ticket body as the spec;
5217
+ // author one for thin-but-groomed tickets; otherwise bounce.
5218
+ stage = 'spec'
5219
+ let conformance = specConformance(body)
5220
+ if (!conformance.conforms && this.deps.authorSpec) {
5221
+ const authored = await this.deps.authorSpec(ticket)
5222
+ if (authored !== null) {
5223
+ conformance = specConformance(authored)
5224
+ if (conformance.conforms) {
5225
+ body = authored
5226
+ authoredSession = this.deps.ids('s')
5227
+ }
4953
5228
  }
4954
5229
  }
4955
- }
4956
- if (!conformance.conforms) {
4957
- await this.bounce(ticket, conformance.missing)
4958
- report.bounced += 1
4959
- report.queued -= 1
4960
- continue
4961
- }
5230
+ if (!conformance.conforms) {
5231
+ attempt.handback = this.triageState()
5232
+ await store.appendRepo(this.deps.repo, {
5233
+ actor: DISPATCHER,
5234
+ type: 'ticket-preparation.handback-selected',
5235
+ payload: { attempt: attempt.attempt, ticket: attempt.ticket, state: attempt.handback },
5236
+ })
5237
+ stage = 'bounce'
5238
+ await this.bounce(ticket, conformance.missing)
5239
+ await this.preparationResolved(attempt, 'bounced')
5240
+ report.bounced += 1
5241
+ report.queued -= 1
5242
+ continue
5243
+ }
4962
5244
 
4963
- const baseSlug = await this.chooseSlugBase(ticket.title, body)
4964
- const slug = await this.uniqueSlug(baseSlug)
4965
- const branch = `${ticket.kind === 'node' ? 'ab-node' : 'ab'}/${slug}`
4966
- const repoOrigin = await this.resolveRepoOriginOnce()
4967
- const createdSeed = {
4968
- ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
4969
- ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
4970
- ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
4971
- // Claim-time provenance: the newest durable default fact that agrees
4972
- // with the launch sample, recorded on `build.created` so the fan-out's
4973
- // seq comparison sees the claim as already answering that fact — and
4974
- // so a newer opposite fact (an interleaved toggle) stays strictly
4975
- // ahead of it and reconciles this build on the next tick (f_b851c0e8).
4976
- ...(autoMergeSeedFact !== undefined ? { autoMergeDefaultSeq: autoMergeSeedFact.seq } : {}),
4977
- assets,
4978
- }
4979
- // `build.created` rides with the record so the pinned assets and the
4980
- // record exist together or not at all.
4981
- const record = await store.createBuild({
4982
- slug,
4983
- repo: this.deps.repo,
4984
- ticket: ticket.ref,
4985
- branch,
4986
- ...(repoOrigin !== undefined ? { repoOrigin } : {}),
4987
- created: {
5245
+ stage = 'naming'
5246
+ const baseSlug = await this.chooseSlugBase(ticket.title, body)
5247
+ const slug = await this.uniqueSlug(baseSlug)
5248
+ const branch = `${ticket.kind === 'node' ? 'ab-node' : 'ab'}/${slug}`
5249
+ const repoOrigin = await this.resolveRepoOriginOnce()
5250
+ createdSeed = {
5251
+ ...(ticket.kind === 'node' ? { kind: ticket.kind } : {}),
5252
+ ...(target !== undefined ? { target: target.target, baseBranch: target.branch } : {}),
5253
+ ...(autoMergeUser !== undefined ? { autoMergeUser } : {}),
5254
+ // Claim-time provenance: the newest durable default fact that agrees
5255
+ // with the launch sample, recorded on `build.created` so the fan-out's
5256
+ // seq comparison sees the claim as already answering that fact — and
5257
+ // so a newer opposite fact (an interleaved toggle) stays strictly
5258
+ // ahead of it and reconciles this build on the next tick (f_b851c0e8).
5259
+ ...(autoMergeSeedFact !== undefined
5260
+ ? { autoMergeDefaultSeq: autoMergeSeedFact.seq }
5261
+ : {}),
5262
+ assets,
5263
+ }
5264
+ // `build.created` rides with the record so the pinned assets and the
5265
+ // record exist together or not at all.
5266
+ stage = 'creation-identity'
5267
+ attempt.slug = slug
5268
+ await store.appendRepo(this.deps.repo, {
4988
5269
  actor: DISPATCHER,
4989
- type: 'build.created',
4990
- payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
4991
- },
4992
- })
5270
+ type: 'ticket-preparation.creation-selected',
5271
+ payload: { attempt: attempt.attempt, ticket: attempt.ticket, slug },
5272
+ })
5273
+ stage = 'create-build'
5274
+ record = await store.createBuild({
5275
+ slug,
5276
+ repo: this.deps.repo,
5277
+ ticket: ticket.ref,
5278
+ branch,
5279
+ ...(repoOrigin !== undefined ? { repoOrigin } : {}),
5280
+ created: {
5281
+ actor: DISPATCHER,
5282
+ type: 'build.created',
5283
+ payload: this.buildCreatedPayload(ticket.ref, this.deps.repo, createdSeed),
5284
+ },
5285
+ })
5286
+ established = true
5287
+ await this.preparationResolved(attempt, 'owned')
5288
+ } catch (error) {
5289
+ // Settlement and completion errors after successful creation cannot
5290
+ // release the claim. A later tick settles the retained creation identity.
5291
+ if (established) throw error
5292
+ const errors: unknown[] = [error]
5293
+ attempt.error =
5294
+ (error instanceof Error ? error.message : String(error)).slice(0, 4000) ||
5295
+ 'unknown preparation failure'
5296
+ attempt.stage = stage
5297
+ try {
5298
+ await store.appendRepo(this.deps.repo, {
5299
+ actor: DISPATCHER,
5300
+ type: 'ticket-preparation.failed',
5301
+ payload: {
5302
+ attempt: attempt.attempt,
5303
+ ticket: attempt.ticket,
5304
+ stage,
5305
+ claimed: attempt.claimed,
5306
+ handback: attempt.handback ?? attempt.readyState,
5307
+ error: attempt.error,
5308
+ },
5309
+ })
5310
+ } catch (diagnosticError) {
5311
+ errors.push(diagnosticError)
5312
+ }
5313
+ try {
5314
+ await this.recoverTicketPreparation(attempt)
5315
+ } catch (recoveryError) {
5316
+ errors.push(recoveryError)
5317
+ }
5318
+ throw new AggregateError(
5319
+ errors,
5320
+ `ticket preparation failed (${stage}): ${errors.map(String).join('; ')}`,
5321
+ )
5322
+ }
4993
5323
  report.queued -= 1
4994
5324
  if (ticket.kind !== 'node') capacity -= 1
4995
5325
  const outcome = await this.attemptDispatchCompletion(record, launched, report, {
@@ -5201,12 +5531,35 @@ export class Dispatcher {
5201
5531
  forge.remoteBranchSha(state.baseBranch),
5202
5532
  forge.remoteBranchSha(record.branch),
5203
5533
  ])
5534
+ this.availabilityEntries ??= this.repoBuildDigests()
5535
+ const entries = await this.availabilityEntries
5536
+ this.availabilityLandings ??= confirmedLandings(entries)
5537
+ this.availabilityLandingKey ??= restackLandingKey(this.availabilityLandings)
5538
+ const evidence = await presenceInputs(
5539
+ this.store,
5540
+ entries,
5541
+ [record.slug],
5542
+ this.availabilityLandings,
5543
+ )
5544
+ const fingerprint =
5545
+ parent && head
5546
+ ? restackAvailabilityFingerprint(
5547
+ state,
5548
+ record.branch,
5549
+ state.baseBranch,
5550
+ head,
5551
+ parent,
5552
+ evidence,
5553
+ this.availabilityLandingKey,
5554
+ )
5555
+ : ''
5556
+ const actionable = actionableRestackDemand(state, fingerprint)
5204
5557
  if (
5205
- (parent === state.nodeRestack?.contributionBase || !nodeRestackDemand(state)) &&
5558
+ (parent === state.nodeRestack?.contributionBase || !actionable) &&
5206
5559
  state.nodeRestack?.distance?.parent === parent &&
5207
5560
  state.nodeRestack.distance.base === state.nodeRestack.contributionBase &&
5208
5561
  head === state.nodeRestack?.inventory?.head &&
5209
- !Object.keys(state.nodeRestack?.requests ?? {}).length
5562
+ (!Object.keys(state.nodeRestack?.requests ?? {}).length || !actionable)
5210
5563
  )
5211
5564
  return
5212
5565
  }
@@ -5280,15 +5633,7 @@ export class Dispatcher {
5280
5633
  )
5281
5634
  if (result.exitCode !== 0) throw new Error(result.stderr)
5282
5635
  added = true
5283
- const parentHead = forge.remoteBranchSha
5284
- ? await forge.remoteBranchSha(state.baseBranch!)
5285
- : undefined
5286
- if (
5287
- state.nodeRestack?.active ||
5288
- (nodeRestackDemand(state) && parentHead !== state.nodeRestack?.contributionBase)
5289
- ) {
5290
- // Upgrade recovery: an old dispatcher may have left a native request
5291
- // armed. Cancel every targeting leaf before admitting a node rewrite.
5636
+ const beforeReplay = async (operation: string) => {
5292
5637
  for (const child of await this.repoBuildDigests()) {
5293
5638
  if (child.digest.terminal || child.digest.kind === 'node') continue
5294
5639
  const childState = (await this.store.buildFacts(child.record.slug)).state
@@ -5298,11 +5643,10 @@ export class Dispatcher {
5298
5643
  childState.prState !== 'open'
5299
5644
  )
5300
5645
  continue
5301
- const cancelled = await forge.setAutoMerge(checkout, childState.pr.number, false)
5302
- if (cancelled.kind !== 'applied')
5303
- throw new Error(
5304
- `node restack waits for native auto-merge cancellation on ${child.record.slug}`,
5305
- )
5646
+ await suspendNativeLanding(
5647
+ { store: this.store, forge, slug: child.record.slug, workspacePath: checkout },
5648
+ `node:${record.slug}:${operation}`,
5649
+ )
5306
5650
  }
5307
5651
  }
5308
5652
  const outcome = await runNodeTransaction(
@@ -5313,6 +5657,7 @@ export class Dispatcher {
5313
5657
  exec: forge.kernelExec ?? this.deps.exec,
5314
5658
  workspacePath,
5315
5659
  holder,
5660
+ beforeReplay,
5316
5661
  canWrite: async () => {
5317
5662
  if (await deferMixedVersion(this.store, record.slug)) return false
5318
5663
  if (this.outOfBudget(opts)) return false
@@ -5818,22 +6163,25 @@ export class Dispatcher {
5818
6163
  let observed = observations.get(destination)
5819
6164
  if (!observed) {
5820
6165
  const forge = this.kernelForge()
5821
- if (!forge.remoteBranchSha || (!forge.snapshotBase && !forge.kernelExec && !forge.rewrite))
5822
- throw new Error('forge cannot snapshot destination presence')
6166
+ if (!forge.remoteBranchSha) throw new Error('forge cannot read destination head')
5823
6167
  const head = await forge.remoteBranchSha(branch)
5824
- const evidence = JSON.stringify({
5825
- version: 2,
5826
- revisions: [
5827
- ...inputs.entries
5828
- .filter(({ digest }) => digest.mergedSha || digest.nodeContribution)
5829
- .map(({ record, digest }) => [record.slug, digest.readinessChangeSeq]),
5830
- ...[...inputs.states].map(([slug, state]) => [slug, state.lastSeq]),
5831
- ].sort(),
5832
- })
6168
+ const aliases = destinationAliases(inputs, target?.target.build)
5833
6169
  const cached = this.store.repositoryFacts().presence[destination]
5834
- if (cached?.head === head && cached.branch === branch && cached.evidence === evidence)
5835
- observed = cached
5836
- else
6170
+ if (cached?.head === head && cached.branch === branch && cached.witness?.version === 1) {
6171
+ const identities = projectPresence(cached.witness, inputs.landings, aliases)
6172
+ const evidence = presenceEvidence(cached.witness, identities)
6173
+ observed = { ...cached, identities }
6174
+ if (cached.evidence !== evidence) {
6175
+ await this.store.ensureRepo(this.deps.repo)
6176
+ await this.store.appendRepo(this.deps.repo, {
6177
+ actor: DISPATCHER,
6178
+ type: 'change-presence.observed',
6179
+ payload: { ...cached, identities, evidence },
6180
+ })
6181
+ }
6182
+ } else {
6183
+ if (!forge.snapshotBase && !forge.kernelExec && !forge.rewrite)
6184
+ throw new Error('forge cannot snapshot destination presence')
5837
6185
  observed = await this.withKernelRepository(async (path) => {
5838
6186
  const destinationRef = `refs/autobuild/reconcile/${target?.target.build ?? 'presence'}/presence`
5839
6187
  let sampled: string
@@ -5872,13 +6220,13 @@ export class Dispatcher {
5872
6220
  sampled = resolved.stdout.trim()
5873
6221
  }
5874
6222
  if (sampled !== head) throw new Error('destination moved while sampling presence')
5875
- const identities = await observePresence(
6223
+ const witness = await presenceWitness(
5876
6224
  { exec: forge.kernelExec ?? this.deps.exec, workspacePath: path },
5877
6225
  head,
5878
- inputs.landings,
5879
- inputs.aliases,
5880
6226
  )
5881
- const payload = { branch, destination, head, evidence, identities }
6227
+ const identities = projectPresence(witness, inputs.landings, aliases)
6228
+ const evidence = presenceEvidence(witness, identities)
6229
+ const payload = { branch, destination, head, evidence, identities, witness }
5882
6230
  await this.store.ensureRepo(this.deps.repo)
5883
6231
  await this.store.appendRepo(this.deps.repo, {
5884
6232
  actor: DISPATCHER,
@@ -5887,6 +6235,7 @@ export class Dispatcher {
5887
6235
  })
5888
6236
  return payload
5889
6237
  })
6238
+ }
5890
6239
  observations.set(destination, observed)
5891
6240
  }
5892
6241
  return observed!