@defrex/autobuild 1.12.0 → 1.13.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 (159) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +435 -160
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +25 -3
  5. package/docs/architecture.md +124 -53
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +110 -15
  8. package/docs/dispatcher.md +19 -8
  9. package/docs/integration-overview.md +1 -1
  10. package/docs/integration-tree.md +12 -9
  11. package/docs/merge-policy.md +7 -2
  12. package/docs/operating.md +5 -3
  13. package/docs/operator-api.md +46 -23
  14. package/docs/operator-surfaces.md +7 -6
  15. package/docs/optimization-nodes.md +7 -6
  16. package/docs/plugin-authoring.md +46 -18
  17. package/docs/remote-store-protocol.md +51 -12
  18. package/docs/remote-ticket-protocol.md +85 -38
  19. package/docs/restacking.md +48 -3
  20. package/docs/setup.md +2 -1
  21. package/docs/ticket-migration.md +2 -2
  22. package/docs/ticket-sources.md +23 -8
  23. package/docs/tickets.md +4 -4
  24. package/docs/troubleshooting.md +17 -2
  25. package/docs/verification.md +3 -1
  26. package/package.json +3 -3
  27. package/packages/core/src/cli/build-control.ts +72 -6
  28. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  29. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  30. package/packages/core/src/cli/dashboard/model.ts +14 -8
  31. package/packages/core/src/cli/dashboard/poll.ts +218 -10
  32. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  33. package/packages/core/src/cli/dashboard/row-text.ts +2 -1
  34. package/packages/core/src/cli/dashboard/vocabulary.ts +5 -1
  35. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  36. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  37. package/packages/core/src/cli/dispatch.ts +527 -144
  38. package/packages/core/src/cli/help.ts +38 -24
  39. package/packages/core/src/cli/main.ts +7 -5
  40. package/packages/core/src/cli/publication-settlement.ts +4 -0
  41. package/packages/core/src/cli/remote-poll.ts +22 -5
  42. package/packages/core/src/cli/repository-status.ts +19 -9
  43. package/packages/core/src/cli/status.ts +23 -11
  44. package/packages/core/src/cli/store-opening.ts +12 -0
  45. package/packages/core/src/cli/ticket-start.ts +3 -3
  46. package/packages/core/src/cli/ticket.ts +12 -11
  47. package/packages/core/src/cli/wait.ts +8 -28
  48. package/packages/core/src/cli/watch.ts +113 -50
  49. package/packages/core/src/config/reference-metadata.ts +7 -1
  50. package/packages/core/src/config/reference.ts +5 -2
  51. package/packages/core/src/config/schema.ts +51 -16
  52. package/packages/core/src/events/payloads.ts +74 -14
  53. package/packages/core/src/events/repository.ts +14 -3
  54. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +27 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  61. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  62. package/packages/core/src/kernel/dispatch-capacity.ts +243 -107
  63. package/packages/core/src/kernel/done-escalations.ts +269 -0
  64. package/packages/core/src/kernel/engine.ts +28 -9
  65. package/packages/core/src/kernel/integration-landing.ts +24 -4
  66. package/packages/core/src/kernel/integration-stack.ts +39 -0
  67. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  68. package/packages/core/src/kernel/log-index-value.ts +3 -0
  69. package/packages/core/src/kernel/log-index.ts +41 -2
  70. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  71. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  72. package/packages/core/src/kernel/reducer-revisions.ts +15 -0
  73. package/packages/core/src/kernel/reducer.ts +27 -7
  74. package/packages/core/src/kernel/repository-attention.ts +14 -5
  75. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  76. package/packages/core/src/kernel/verify-stages.ts +46 -7
  77. package/packages/core/src/operator/attention.ts +28 -3
  78. package/packages/core/src/operator/done-escalations.ts +38 -0
  79. package/packages/core/src/operator/presentation.ts +1 -1
  80. package/packages/core/src/operator/protocol.ts +8 -5
  81. package/packages/core/src/operator/query.ts +33 -19
  82. package/packages/core/src/operator/registry.ts +17 -13
  83. package/packages/core/src/operator/ticket-start.ts +8 -7
  84. package/packages/core/src/operator/tickets.ts +28 -9
  85. package/packages/core/src/plugin-sdk/index.ts +10 -0
  86. package/packages/core/src/plugins/manifest.ts +14 -1
  87. package/packages/core/src/ports/forge/create.ts +8 -0
  88. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  89. package/packages/core/src/ports/forge/github.ts +3 -0
  90. package/packages/core/src/ports/tickets/contract.ts +147 -76
  91. package/packages/core/src/ports/tickets/create.ts +47 -7
  92. package/packages/core/src/ports/tickets/fake.ts +8 -4
  93. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  94. package/packages/core/src/ports/tickets/file.ts +7 -3
  95. package/packages/core/src/ports/tickets/github.ts +1 -0
  96. package/packages/core/src/ports/tickets/grants.ts +11 -3
  97. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  98. package/packages/core/src/ports/tickets/linear.ts +28 -9
  99. package/packages/core/src/ports/tickets/migration.ts +4 -4
  100. package/packages/core/src/ports/tickets/operations.ts +4 -2
  101. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  102. package/packages/core/src/ports/tickets/priority.ts +127 -21
  103. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  104. package/packages/core/src/ports/tickets/remote.ts +104 -11
  105. package/packages/core/src/ports/tickets/revision.ts +5 -3
  106. package/packages/core/src/ports/tickets/search.ts +9 -0
  107. package/packages/core/src/ports/tickets/tree.ts +8 -6
  108. package/packages/core/src/ports/types.ts +30 -15
  109. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  110. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  111. package/packages/core/src/ports/workspace/create.ts +16 -3
  112. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  113. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  114. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  115. package/packages/core/src/processes/build-execution-state.ts +4 -0
  116. package/packages/core/src/processes/build-runner.ts +14 -1
  117. package/packages/core/src/processes/dispatcher.ts +544 -212
  118. package/packages/core/src/processes/execution-settlement.ts +1 -0
  119. package/packages/core/src/processes/harvest-runner.ts +12 -7
  120. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  121. package/packages/core/src/processes/invocation-budget.ts +176 -0
  122. package/packages/core/src/processes/publication-loss.ts +38 -3
  123. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  124. package/packages/core/src/store/contract.ts +81 -3
  125. package/packages/core/src/store/event-reads.ts +30 -1
  126. package/packages/core/src/store/reduced-reads.ts +23 -0
  127. package/packages/core/src/store/reducer-value-shapes.json +6628 -6469
  128. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  129. package/packages/core/src/store/remote/client.ts +169 -29
  130. package/packages/core/src/store/remote/compatibility.ts +113 -56
  131. package/packages/core/src/store/remote/credentials.ts +4 -1
  132. package/packages/core/src/store/remote/protocol.ts +3 -0
  133. package/packages/core/src/store/remote/released-clients.json +11 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  135. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  136. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  137. package/packages/core/src/store/remote/retry.ts +406 -0
  138. package/packages/core/src/testing/dispatch-read-budget.ts +144 -10
  139. package/packages/core/src/testing/index.ts +2 -0
  140. package/packages/core/src/testing/invocation-budget.ts +42 -0
  141. package/packages/core/src/testing/reduced-read-budget.ts +381 -18
  142. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  143. package/packages/core/src/web/overview-source.ts +19 -6
  144. package/skills/guide/SKILL.md +138 -67
  145. package/skills/guide/references/integration-tree.md +12 -9
  146. package/skills/guide/references/merge-policy.md +7 -2
  147. package/skills/guide/references/operator-api.md +46 -23
  148. package/skills/guide/references/optimization-nodes.md +7 -6
  149. package/skills/guide/references/plugin-authoring.md +46 -18
  150. package/skills/guide/references/remote-store-protocol.md +51 -12
  151. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  152. package/skills/guide/references/restacking.md +48 -3
  153. package/skills/guide/references/setup.md +2 -1
  154. package/skills/guide/references/ticket-migration.md +2 -2
  155. package/skills/operate/SKILL.md +82 -51
  156. package/skills/plan/SKILL.md +4 -3
  157. package/skills/spec/SKILL.md +9 -5
  158. package/skills/tickets/SKILL.md +25 -17
  159. package/templates/hosted-service/package.json +2 -2
@@ -108,6 +108,7 @@ function observationIdentity(open: {
108
108
  return {
109
109
  provider: open.provider,
110
110
  workspaceRef: open.workspaceRef,
111
+ instance: open.instance,
111
112
  ...(open.environmentId !== undefined ? { environmentId: open.environmentId } : {}),
112
113
  ...(open.sessionId !== undefined ? { sessionId: open.sessionId } : {}),
113
114
  ...(open.commandId !== undefined ? { commandId: open.commandId } : {}),
@@ -97,6 +97,10 @@ export interface HarvestRunnerOpts {
97
97
 
98
98
  export interface HarvestRunnerDeps {
99
99
  store: BuildStore
100
+ /** Host fetch for phase credential delegation and ticket grants; a bounded
101
+ * dispatcher invocation passes one that cancels at its deadline. Absent ⇒
102
+ * global `fetch`. */
103
+ fetchFn?: typeof fetch
100
104
  tickets: TicketSource
101
105
  config: Config
102
106
  /** Current dispatcher snapshot, sampled only at workflow/session boundaries. */
@@ -1443,7 +1447,7 @@ export class HarvestRunner {
1443
1447
  const labels = creationLabels(config.tickets, [HARVEST_PROPOSAL_LABEL]) ?? [
1444
1448
  HARVEST_PROPOSAL_LABEL,
1445
1449
  ]
1446
- // Harvest proposals are always normal priority; grooming may mark one urgent.
1450
+ // Harvest proposals are always normal priority; grooming may set another level.
1447
1451
  const ticket = (
1448
1452
  await tickets.create(
1449
1453
  {
@@ -1874,12 +1878,12 @@ export class HarvestRunner {
1874
1878
  const parent = this.deps.sessionEnv
1875
1879
  const token =
1876
1880
  parent?.AB_STORE && /^https?:/i.test(parent.AB_STORE)
1877
- ? await delegateCredential(parent.AB_STORE, parent.AB_TOKEN, {
1878
- kind: 'harvest-phase',
1879
- repo: this.deps.repo,
1880
- id: run,
1881
- session,
1882
- })
1881
+ ? await delegateCredential(
1882
+ parent.AB_STORE,
1883
+ parent.AB_TOKEN,
1884
+ { kind: 'harvest-phase', repo: this.deps.repo, id: run, session },
1885
+ this.deps.fetchFn,
1886
+ )
1883
1887
  : undefined
1884
1888
  const ticketGrant =
1885
1889
  parent?.AB_TICKET_URL && parent.AB_TICKET_TOKEN
@@ -1889,6 +1893,7 @@ export class HarvestRunner {
1889
1893
  this.deps.repo,
1890
1894
  this.deps.instance,
1891
1895
  'phase',
1896
+ this.deps.fetchFn,
1892
1897
  )
1893
1898
  : undefined
1894
1899
  return {
@@ -5,6 +5,7 @@ import type { EventPayload } from '../events/payloads'
5
5
  import type { IdSource } from '../ids'
6
6
  import { defineReducer } from '../kernel/incremental'
7
7
  import type { BuildStore } from '../store/types'
8
+ import { recoveryStepOf } from '../ports/workspace/recovery-step'
8
9
 
9
10
  export type InfrastructureOperation = EventPayload<'infrastructure.failed'>['operation']
10
11
  export type InfrastructureCause = EventPayload<'infrastructure.failed'>['cause']
@@ -80,7 +81,10 @@ export function normalizeInfrastructureError(error: unknown): string {
80
81
  const text = String(value).trim()
81
82
  return text === '' ? [] : [text]
82
83
  }
83
- const messages = [...new Set(collect(error).map((part) => part.trim()))]
84
+ // A wrapper usually quotes its cause; a cause already said is not repeated.
85
+ const messages: string[] = []
86
+ for (const part of collect(error).map((entry) => entry.trim()))
87
+ if (!messages.some((kept) => kept.includes(part))) messages.push(part)
84
88
  return messages.join('; ') || 'provider operation failed without an error message'
85
89
  }
86
90
 
@@ -112,6 +116,7 @@ export async function recordInfrastructureFailure(
112
116
  ).length + 1
113
117
  : (input.events as CurrentBuildFacts).infrastructureCount + 1
114
118
  const message = normalizeInfrastructureError(input.error)
119
+ const step = recoveryStepOf(input.error)
115
120
  const failure = await deps.store.append(input.slug, {
116
121
  actor: DISPATCHER,
117
122
  type: 'infrastructure.failed',
@@ -144,7 +149,7 @@ export async function recordInfrastructureFailure(
144
149
  phase: 'setup',
145
150
  source: 'policy',
146
151
  policyCause: 'infrastructure-failure-limit',
147
- question: `maxInfrastructureAttempts (${input.maxAttempts}) exhausted during ${input.operation}; provider cleanup/recovery must succeed before retry: ${message}`,
152
+ question: `maxInfrastructureAttempts (${input.maxAttempts}) exhausted during ${input.operation}${step === undefined ? '' : ` at step ${step}`}; provider cleanup/recovery must succeed before retry: ${message}`,
148
153
  refs: [input.workspaceRef],
149
154
  },
150
155
  }),
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Bounded-invocation budget (hosted cron dispatcher).
3
+ *
4
+ * One configured budget becomes three wall-time deadlines, each with its own
5
+ * `AbortSignal`:
6
+ *
7
+ * - `work`: stop starting work and cancel in-flight work I/O. It falls a
8
+ * teardown reserve before the budget ends.
9
+ * - `cleanup`: secondary teardown (provisioning abandonment, hooks,
10
+ * executions, harvest) must finish by then.
11
+ * - `final`: the repository lease release, `dispatcher.run-stopped` and the
12
+ * store close must finish by the budget end.
13
+ *
14
+ * The current phase's signal travels in an `AsyncLocalStorage`, so a promise
15
+ * chain started during work keeps the work signal even after teardown begins:
16
+ * abandoned work cannot write after the work deadline. `budgetedFetch` applies
17
+ * the ambient signal to every request made through it.
18
+ *
19
+ * Server-side only: this module imports `node:async_hooks`.
20
+ */
21
+ import { AsyncLocalStorage } from 'node:async_hooks'
22
+
23
+ /** Timer seam for invocation deadlines: production uses `DEFAULT_TIMERS`;
24
+ * tests inject a fake whose pending handles are inspectable and fireable, so
25
+ * race outcomes are deterministic with no real-time sleeps. Handles are opaque
26
+ * (`unknown`) so the interface stays runtime-agnostic. */
27
+ export interface TimerScheduler {
28
+ setTimeout(handler: () => void, ms: number): unknown
29
+ clearTimeout(handle: unknown): void
30
+ }
31
+
32
+ /** Production scheduler: real global timers, `unref()`'d so a pending expiry
33
+ * never holds the process open. */
34
+ export const DEFAULT_TIMERS: TimerScheduler = {
35
+ setTimeout(handler, ms) {
36
+ const timer = setTimeout(handler, ms)
37
+ ;(timer as { unref?: () => void }).unref?.()
38
+ return timer
39
+ },
40
+ clearTimeout(handle) {
41
+ clearTimeout(handle as ReturnType<typeof setTimeout>)
42
+ },
43
+ }
44
+
45
+ export type InvocationPhase = 'work' | 'cleanup' | 'final'
46
+
47
+ /** The abort reason of each budget signal, naming the deadline that passed. */
48
+ export class InvocationDeadlineError extends Error {
49
+ constructor(readonly phase: InvocationPhase) {
50
+ super(`invocation ${phase} deadline reached`)
51
+ this.name = 'InvocationDeadlineError'
52
+ }
53
+ }
54
+
55
+ /** Thrown when a bounded invocation's work deadline passes before the run
56
+ * started: nothing durable was claimed, so the caller reports it skipped. */
57
+ export class InvocationBudgetExhaustedError extends Error {
58
+ constructor(
59
+ message = 'invocation budget exhausted before the dispatcher run started',
60
+ options?: ErrorOptions,
61
+ ) {
62
+ super(message, options)
63
+ this.name = 'InvocationBudgetExhaustedError'
64
+ }
65
+ }
66
+
67
+ /** Time reserved at the end of a budget for teardown: `min(30 s, budget/4)`. */
68
+ export function teardownReserveMs(budgetMs: number): number {
69
+ return Math.min(30_000, Math.floor(budgetMs / 4))
70
+ }
71
+
72
+ export interface InvocationBudget {
73
+ /** Epoch ms: stop starting work; in-flight work I/O is cancelled. */
74
+ readonly workDeadlineAt: number
75
+ /** Epoch ms: secondary teardown steps must have finished. */
76
+ readonly cleanupDeadlineAt: number
77
+ /** Epoch ms: the budget end; lease release and `run-stopped` finish by it. */
78
+ readonly hardDeadlineAt: number
79
+ readonly work: AbortSignal
80
+ readonly cleanup: AbortSignal
81
+ readonly final: AbortSignal
82
+ /** Clear every pending deadline timer. */
83
+ dispose(): void
84
+ }
85
+
86
+ export function createInvocationBudget(opts: {
87
+ workDeadlineAt: number
88
+ hardDeadlineAt: number
89
+ now: () => number
90
+ timers?: TimerScheduler
91
+ }): InvocationBudget {
92
+ const { workDeadlineAt, hardDeadlineAt } = opts
93
+ if (!(hardDeadlineAt > workDeadlineAt)) {
94
+ throw new Error('invocation budget: the hard deadline must fall after the work deadline')
95
+ }
96
+ const cleanupDeadlineAt =
97
+ hardDeadlineAt - Math.min(10_000, Math.floor((hardDeadlineAt - workDeadlineAt) / 3))
98
+ const timers = opts.timers ?? DEFAULT_TIMERS
99
+ const handles: unknown[] = []
100
+ const arm = (phase: InvocationPhase, deadline: number): AbortSignal => {
101
+ const controller = new AbortController()
102
+ handles.push(
103
+ timers.setTimeout(
104
+ () => controller.abort(new InvocationDeadlineError(phase)),
105
+ Math.max(0, deadline - opts.now()),
106
+ ),
107
+ )
108
+ return controller.signal
109
+ }
110
+ const work = arm('work', workDeadlineAt)
111
+ const cleanup = arm('cleanup', cleanupDeadlineAt)
112
+ const final = arm('final', hardDeadlineAt)
113
+ return {
114
+ workDeadlineAt,
115
+ cleanupDeadlineAt,
116
+ hardDeadlineAt,
117
+ work,
118
+ cleanup,
119
+ final,
120
+ dispose() {
121
+ for (const handle of handles.splice(0)) timers.clearTimeout(handle)
122
+ },
123
+ }
124
+ }
125
+
126
+ const ambient = new AsyncLocalStorage<AbortSignal>()
127
+
128
+ /** Run `work` with `signal` as the ambient phase signal. Every continuation
129
+ * started inside keeps it, whatever phase the caller later enters. */
130
+ export function withInvocationSignal<T>(signal: AbortSignal, work: () => T): T {
131
+ return ambient.run(signal, work)
132
+ }
133
+
134
+ /** The current phase's cancellation signal, or `undefined` outside a bounded
135
+ * invocation. */
136
+ export function invocationSignal(): AbortSignal | undefined {
137
+ return ambient.getStore()
138
+ }
139
+
140
+ /** A fetch that cancels each request at the ambient phase deadline, together
141
+ * with any caller `init.signal`. Without an ambient signal it is `base`. */
142
+ export function budgetedFetch(base: typeof fetch = globalThis.fetch): typeof fetch {
143
+ const wrapped = (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
144
+ const signal = ambient.getStore()
145
+ if (signal === undefined) return base(input, init)
146
+ return base(input, {
147
+ ...init,
148
+ signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal,
149
+ })
150
+ }
151
+ return wrapped as typeof fetch
152
+ }
153
+
154
+ /** Await `work` unless `signal` aborts first. A rejection before the abort
155
+ * rethrows; a late rejection after the abort is swallowed. */
156
+ export function untilAborted<T>(
157
+ work: Promise<T>,
158
+ signal: AbortSignal,
159
+ ): Promise<{ settled: true; value: T } | { settled: false }> {
160
+ work.catch(() => {})
161
+ if (signal.aborted) return Promise.resolve({ settled: false })
162
+ return new Promise((resolve, reject) => {
163
+ const onAbort = (): void => resolve({ settled: false })
164
+ signal.addEventListener('abort', onAbort, { once: true })
165
+ work.then(
166
+ (value) => {
167
+ signal.removeEventListener('abort', onAbort)
168
+ resolve({ settled: true, value })
169
+ },
170
+ (error: unknown) => {
171
+ signal.removeEventListener('abort', onAbort)
172
+ reject(error)
173
+ },
174
+ )
175
+ })
176
+ }
@@ -1,6 +1,7 @@
1
1
  import { PublicationRetryPersistenceError } from '../kernel/publication-retry'
2
2
  import { ForgeRequestDeferred } from '../ports/forge-request-context'
3
3
  import { isRemoteWorkspace } from '../events/workspace-remote'
4
+ import { isRecoveryDeferred, recoveryStepOf } from '../ports/workspace/recovery-step'
4
5
  /**
5
6
  * Last-chance publication settlement at the workspace-release boundary
6
7
  * (AUT-328). A pending `publication.requested` whose workspace is destroyed
@@ -15,6 +16,13 @@ import { DISPATCHER } from '../events/envelope'
15
16
  import type { AbEvent } from '../events/catalog'
16
17
  import type { BuildStore } from '../store/types'
17
18
 
19
+ /** A deadline deferral or a failed resume of a stopped environment says
20
+ * nothing about the work inside it: keep the workspace and retry, never
21
+ * record the publication lost. */
22
+ function retainsWorkspace(error: unknown): boolean {
23
+ return isRecoveryDeferred(error) || recoveryStepOf(error) === 'resume'
24
+ }
25
+
18
26
  export interface PublicationLossDeps {
19
27
  store: BuildStore
20
28
  /** Trusted publication settlement (dispatcher-injected). A throw means the
@@ -66,7 +74,8 @@ export async function settlePublicationFactsBeforeRelease(
66
74
  } catch (error) {
67
75
  if (
68
76
  error instanceof ForgeRequestDeferred ||
69
- error instanceof PublicationRetryPersistenceError
77
+ error instanceof PublicationRetryPersistenceError ||
78
+ retainsWorkspace(error)
70
79
  )
71
80
  throw error
72
81
  /* Summary is best effort. */
@@ -78,11 +87,37 @@ export async function settlePublicationFactsBeforeRelease(
78
87
  try {
79
88
  await deps.settlePublication?.(slug)
80
89
  } catch (error) {
81
- if (error instanceof ForgeRequestDeferred || error instanceof PublicationRetryPersistenceError)
90
+ if (
91
+ error instanceof ForgeRequestDeferred ||
92
+ error instanceof PublicationRetryPersistenceError ||
93
+ retainsWorkspace(error)
94
+ )
82
95
  throw error
83
96
  /* Record loss before release. */
84
97
  }
85
- const refreshed = (await readBuildFacts(deps.store, slug)).value
98
+ return recordPublicationLossBeforeRelease(
99
+ deps,
100
+ slug,
101
+ (await readBuildFacts(deps.store, slug)).value,
102
+ reason,
103
+ request,
104
+ )
105
+ }
106
+
107
+ /** Record `publication.lost` for the latest uncompleted request, without any
108
+ * settlement attempt, unless it completed or its loss is already recorded.
109
+ * Abort release calls it directly: it never waits on a guest or the forge. */
110
+ export async function recordPublicationLossBeforeRelease(
111
+ deps: Pick<PublicationLossDeps, 'store'>,
112
+ slug: string,
113
+ refreshed: import('../store/reduced-reads').CurrentBuildFacts,
114
+ reason: string,
115
+ /** The request a settlement attempt targeted; defaults to the latest uncompleted one. */
116
+ pending = refreshed.publication.latestUncompletedRequest(),
117
+ ) {
118
+ const { readBuildFacts } = await import('../store/reduced-reads')
119
+ const request = pending
120
+ if (request === undefined) return refreshed
86
121
  if (
87
122
  refreshed.publication.requestCompleted(request) ||
88
123
  refreshed.publication.lostRecorded(request)
@@ -6,8 +6,42 @@ import { preserveGitCommits } from '../ports/workspace/commit-preservation'
6
6
  import { restoreRetainedHead, retainPreservedCopy } from '../kernel/history-retention'
7
7
  import { readBuildFacts } from '../store/reduced-reads'
8
8
  import type { BuildStore } from '../store/types'
9
+ import type { CurrentBuildFacts } from '../store/reduced-reads'
10
+ import {
11
+ WorkspaceRecoveryStepError,
12
+ type WorkspaceRecoveryStep,
13
+ } from '../ports/workspace/recovery-step'
9
14
 
10
- export class WorkspaceFenceUnknown extends Error {}
15
+ /** The fence could not prove the workspace's execution stopped. */
16
+ export class WorkspaceFenceUnknown extends WorkspaceRecoveryStepError {
17
+ constructor(detail: string) {
18
+ super('fence', detail)
19
+ this.name = 'WorkspaceFenceUnknown'
20
+ }
21
+ }
22
+
23
+ /** Preservation refused because an execution lease is still live. Never
24
+ * swallowed: no release may tear down under a live process tree. */
25
+ export class WorkspaceLeaseLive extends Error {}
26
+
27
+ /** The workspace generation a preservation receipt describes, or `undefined`
28
+ * when no workspace is open. */
29
+ function preservationSource(current: CurrentBuildFacts) {
30
+ const source = current.latestWorkspace
31
+ if (!source || current.workspace === null) return undefined
32
+ const handle = { ...source.payload, path: source.payload.path ?? source.payload.ref }
33
+ const execution = current.state.executions.at(-1)
34
+ const executionSeq = execution?.workspaceRef === source.payload.ref ? execution.seq : 0
35
+ const metadata = {
36
+ workspace: source.seq,
37
+ execution: executionSeq,
38
+ ref: handle.ref,
39
+ branch: handle.branch,
40
+ phase: current.state.phase ?? 'implement',
41
+ round: current.state.round ?? 1,
42
+ }
43
+ return { source, handle, executionSeq, metadata }
44
+ }
11
45
 
12
46
  /** Key-order-independent identity of a preserved head. */
13
47
  const headIdentity = (head: WorkspacePreservationHead) => [
@@ -44,13 +78,14 @@ export async function preserveWorkspaceBeforeRelease(deps: {
44
78
  exec: Exec
45
79
  reason: string
46
80
  now?: Date
81
+ /** Told which recovery step is starting, so a caller can name it when
82
+ * recording a failure. */
83
+ onStep?: (step: WorkspaceRecoveryStep) => void
47
84
  }): Promise<void> {
48
85
  let current = await readBuildFacts(deps.store, deps.slug)
49
- const source = current.value.latestWorkspace
50
- if (!source || current.value.workspace === null) return
51
- const handle = { ...source.payload, path: source.payload.path ?? source.payload.ref }
52
- const execution = current.value.state.executions.at(-1)
53
- const executionSeq = execution?.workspaceRef === source.payload.ref ? execution.seq : 0
86
+ const found = preservationSource(current.value)
87
+ if (!found) return
88
+ const { source, handle, executionSeq, metadata } = found
54
89
  // Any execution on this ref, not only the latest, keeps a reused ref strict.
55
90
  const neverExecuted = !current.value.state.executions.some(
56
91
  (started) => started.workspaceRef === source.payload.ref,
@@ -61,7 +96,8 @@ export async function preserveWorkspaceBeforeRelease(deps: {
61
96
  record?.lease &&
62
97
  new Date(record.lease.expiresAt).getTime() > (deps.now ?? new Date()).getTime()
63
98
  )
64
- throw new Error('workspace preservation refused while execution lease is live')
99
+ throw new WorkspaceLeaseLive('workspace preservation refused while execution lease is live')
100
+ deps.onStep?.('fence')
65
101
  if (!deps.owner.recovery && current.value.open !== null)
66
102
  throw new WorkspaceFenceUnknown('local execution teardown has not been recorded')
67
103
  const outcome = deps.owner.recovery
@@ -107,14 +143,6 @@ export async function preserveWorkspaceBeforeRelease(deps: {
107
143
  ...(prior?.heads.map((head) => head.sha) ?? []),
108
144
  ]),
109
145
  ]
110
- const metadata = {
111
- workspace: source.seq,
112
- execution: executionSeq,
113
- ref: handle.ref,
114
- branch: handle.branch,
115
- phase: current.value.state.phase ?? 'implement',
116
- round: current.value.state.round ?? 1,
117
- }
118
146
  const local = deps.forge.name === 'local-git'
119
147
  const rewriteCapability = deps.forge.kernelRewrite ?? deps.forge.rewrite
120
148
  // Strict store fallback for heads the forge refused to archive; it runs on
@@ -139,6 +167,7 @@ export async function preserveWorkspaceBeforeRelease(deps: {
139
167
  let preserved:
140
168
  | { outcome: 'preserved'; heads: import('../ports/types').WorkspacePreservationHead[] }
141
169
  | { outcome: 'absent' }
170
+ deps.onStep?.('preserve')
142
171
  if (outcome.outcome === 'absent') preserved = { outcome: 'absent' }
143
172
  else if (deps.owner.preservation || deps.owner.publication) {
144
173
  const preserve = deps.owner.preservation ?? deps.owner.publication?.preserve
@@ -255,3 +284,45 @@ export async function preserveWorkspaceBeforeRelease(deps: {
255
284
  if (!(await deps.store.appendIfCurrent(deps.slug, current.cursor, write)))
256
285
  throw new Error('workspace changed during commit preservation; retry cleanup')
257
286
  }
287
+
288
+ /** Abort cleanup's paper trail when commit preservation failed: abort discards
289
+ * the build's work, so the open workspace's unpreserved commits are recorded as
290
+ * lost and teardown continues. Idempotent per workspace generation and
291
+ * execution; a lost compare-and-append throws so the cleanup retries. */
292
+ export async function recordAbortPreservationFailure(deps: {
293
+ store: BuildStore
294
+ slug: string
295
+ error: unknown
296
+ }): Promise<void> {
297
+ const current = await readBuildFacts(deps.store, deps.slug)
298
+ const found = preservationSource(current.value)
299
+ if (!found) return
300
+ const { source, executionSeq, metadata } = found
301
+ const loss = current.value.workspaceLoss?.payload
302
+ if (loss?.workspace === source.seq && loss.execution === executionSeq) return
303
+ const prior = current.value.workspacePreservation?.payload
304
+ const request = current.value.publication.latestUncompletedRequest()
305
+ const shas = (
306
+ request && !current.value.publication.lostRecorded(request) ? [request.payload.sha] : []
307
+ ).filter((sha) => !prior?.heads.some((head) => head.sha === sha))
308
+ const message =
309
+ deps.error instanceof Error
310
+ ? deps.error.message
311
+ : typeof deps.error === 'object' && deps.error !== null && 'message' in deps.error
312
+ ? String((deps.error as { message: unknown }).message)
313
+ : String(deps.error)
314
+ const detail = message.length > 2000 ? `${message.slice(0, 2000)}…` : message
315
+ if (
316
+ !(await deps.store.appendIfCurrent(deps.slug, current.cursor, {
317
+ actor: DISPATCHER,
318
+ type: 'workspace.commits-lost',
319
+ payload: {
320
+ ...metadata,
321
+ shas,
322
+ inventory: 'additional-shas-unavailable',
323
+ reason: `abort: commit preservation failed — ${detail || 'no error message'}`,
324
+ },
325
+ }))
326
+ )
327
+ throw new Error('workspace changed while recording abort commit loss; retry cleanup')
328
+ }
@@ -1,8 +1,9 @@
1
1
  import { IncompleteEventReadError, BUILD_EVENT_PAGE_SIZE } from './event-reads'
2
2
  import { repositoryReadFactsReducer } from '../kernel/read-facts'
3
- import { validateReducerValue } from './reducer-value-validation'
3
+ import { REDUCER_VALUE_CONTRACT_IDENTITY, validateReducerValue } from './reducer-value-validation'
4
4
  import { READ_CATALOG_IDENTITY } from '../events/compatibility'
5
5
  import { AUTOBUILD_VERSION } from './remote/version'
6
+ import { reducerValueForClient } from './remote/compatibility'
6
7
  import { sameParentRejection } from '../kernel/node-restack-state'
7
8
  import {
8
9
  readBuildFacts,
@@ -20,6 +21,11 @@ import {
20
21
  buildRosterRollup,
21
22
  type BuildRosterValue,
22
23
  } from '../kernel/build-roster'
24
+ import {
25
+ doneEscalationEntryReducer,
26
+ doneEscalationsRollup,
27
+ type DoneEscalationsValue,
28
+ } from '../kernel/done-escalations'
23
29
  import { prepareAssetSnapshots } from './ticket-asset-snapshots'
24
30
  import { MemoryBuildStore } from './memory'
25
31
  import { summarizeTicketAsset } from './ticket-assets'
@@ -2240,6 +2246,66 @@ export function describeBuildStoreContract(name: string, factory: BuildStoreFact
2240
2246
  })
2241
2247
  })
2242
2248
 
2249
+ describe('doneEscalations', () => {
2250
+ const read = async (store: BuildStore) =>
2251
+ (await store.getReducerValue(scope, { reducer: 'doneEscalations' }))
2252
+ .value as unknown as DoneEscalationsValue
2253
+ const fold = async (store: BuildStore, slugs: string[], now: Date) => {
2254
+ const acc = doneEscalationsRollup.initial()
2255
+ for (const slug of slugs) {
2256
+ const entry = doneEscalationEntryReducer.reduce(await store.getEvents(slug))
2257
+ const contribution = doneEscalationsRollup.contribute(entry, {}, now, slug)
2258
+ if (contribution) doneEscalationsRollup.add(acc, contribution)
2259
+ }
2260
+ return doneEscalationsRollup.finish(acc, {}, now, await store.getRepoChangePosition(repo))
2261
+ }
2262
+ const raise = (store: BuildStore, slug: string) =>
2263
+ store.append(slug, {
2264
+ actor: KERNEL,
2265
+ type: 'escalation.raised',
2266
+ payload: {
2267
+ id: `${slug}-esc`,
2268
+ phase: 'verify:integration',
2269
+ source: 'agent',
2270
+ question: 'q',
2271
+ },
2272
+ })
2273
+ const complete = (store: BuildStore, slug: string) =>
2274
+ store.append(slug, {
2275
+ actor: DISPATCHER,
2276
+ type: 'build.completed',
2277
+ payload: { outcome: 'merged' },
2278
+ })
2279
+
2280
+ test('lists done builds with an open escalation until they are answered', async () => {
2281
+ const clock = manualClock(CONTRACT_T0)
2282
+ await withStore(factory, { clock }, async (store) => {
2283
+ const slugs = ['de-active', 'de-late', 'de-aborted', 'de-plain']
2284
+ for (const slug of slugs) await store.createBuild({ slug, repo })
2285
+ await raise(store, 'de-active')
2286
+ await complete(store, 'de-late')
2287
+ await raise(store, 'de-aborted')
2288
+ await store.append('de-aborted', { actor: KERNEL, type: 'build.aborted', payload: {} })
2289
+ await complete(store, 'de-plain')
2290
+ expect((await read(store)).builds).toEqual([])
2291
+ await raise(store, 'de-late')
2292
+ const listed = await read(store)
2293
+ expect(listed).toEqual(await fold(store, slugs, clock()))
2294
+ expect(listed.builds).toEqual([{ slug: 'de-late', kind: 'work' }])
2295
+ // Idle: the same answer again.
2296
+ expect(await read(store)).toEqual(listed)
2297
+ await store.append('de-late', {
2298
+ actor: humanActor('op'),
2299
+ type: 'escalation.answered',
2300
+ payload: { id: 'de-late-esc', answer: 'ack', resolution: 'retry' },
2301
+ })
2302
+ const answered = await read(store)
2303
+ expect(answered.builds).toEqual([])
2304
+ expect(answered).toEqual(await fold(store, slugs, clock()))
2305
+ })
2306
+ })
2307
+ })
2308
+
2243
2309
  test('scoped handles reject the rollup scope; rollup rows are private', async () => {
2244
2310
  await withStore(factory, { clock: manualClock(CONTRACT_T0) }, async (store) => {
2245
2311
  await store.createBuild({ slug: 'rollup-scoped', repo })
@@ -2847,11 +2913,23 @@ export function describeBuildStoreContract(name: string, factory: BuildStoreFact
2847
2913
  const events = scope.kind === 'repo' ? repoEvents : buildEvents
2848
2914
  const expected = JSON.parse(JSON.stringify(resolved.reducer.reduce(events)))
2849
2915
  const answer = await store.getReducerValue(scope, request)
2916
+ const canonical = { version: resolved.reducer.version, value: expected }
2917
+ // A remote server answers this source client, whose value contract
2918
+ // matches the current package release, in that release's versions,
2919
+ // so a fold revision made since the release reads as the published one.
2920
+ const published = reducerValueForClient(
2921
+ {
2922
+ version: AUTOBUILD_VERSION,
2923
+ projects: true,
2924
+ catalogIdentity: REDUCER_VALUE_CONTRACT_IDENTITY,
2925
+ },
2926
+ name,
2927
+ canonical,
2928
+ )
2850
2929
  expect(answer).toEqual({
2851
2930
  catalogIdentity: READ_CATALOG_IDENTITY,
2852
- version: resolved.reducer.version,
2853
2931
  cursor: events.at(-1)?.seq ?? 0,
2854
- value: expected,
2932
+ ...(answer.version === canonical.version ? canonical : published),
2855
2933
  })
2856
2934
  if (answer.value && typeof answer.value === 'object')
2857
2935
  Object.assign(answer.value, { poison: true })
@@ -76,12 +76,17 @@ export function assertResumeWindow(scope: SnapshotScope, cursor: number, head: n
76
76
  if (cursor < Math.max(0, head - REPOSITORY_TAIL_WINDOW))
77
77
  throw new CursorTooOldError(scope, cursor, head)
78
78
  }
79
+ /** Errors no retry can cure. A reducer incompatibility (the client cannot
80
+ * represent the server's canonical value) is classified by name so this module
81
+ * never imports the remote adapter; the command exits with its upgrade advice
82
+ * and never falls back to reconstructing the value from history. */
79
83
  export function isTerminalEventReadError(error: unknown): boolean {
80
84
  return (
81
85
  error instanceof CursorTooOldError ||
82
86
  error instanceof CheckpointIntegrityError ||
83
87
  error instanceof IncompleteEventReadError ||
84
- error instanceof RetiredSeedGenerationError
88
+ error instanceof RetiredSeedGenerationError ||
89
+ (error instanceof Error && error.name === 'ReducerValueIncompatibilityError')
85
90
  )
86
91
  }
87
92
 
@@ -133,6 +138,30 @@ export async function readBuildRange(
133
138
  } while (cursor < through)
134
139
  return events
135
140
  }
141
+ /**
142
+ * Follow a live tail from a known cursor: every event after `since`, paged
143
+ * until caught up. No seed read and no frozen upper bound — a follower polls
144
+ * again, so anything appended meanwhile arrives on the next read. Only the
145
+ * first page may hold (`waitSeconds`); continuations return at once.
146
+ */
147
+ export async function readBuildTail(
148
+ store: import('./types').BuildStore,
149
+ slug: string,
150
+ since: number,
151
+ opts?: EventReadOptions,
152
+ ): Promise<AbEvent[]> {
153
+ if (!store.getBuildEventPage) return store.getEvents(slug, since, opts)
154
+ const events: AbEvent[] = []
155
+ let cursor = since
156
+ let page = await store.getBuildEventPage(slug, cursor, opts)
157
+ for (;;) {
158
+ events.push(...page.events)
159
+ if (!page.hasMore) return events
160
+ if (page.cursor <= cursor) throw new CheckpointIntegrityError('nonadvancing event page')
161
+ cursor = page.cursor
162
+ page = await store.getBuildEventPage(slug, cursor, { ...opts, waitSeconds: 0 })
163
+ }
164
+ }
136
165
  export async function readHarvestTail(
137
166
  store: import('./types').BuildStore,
138
167
  repo: string,