@defrex/autobuild 1.12.0 → 1.14.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 (167) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +465 -163
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +28 -4
  5. package/docs/architecture.md +136 -53
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +120 -17
  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 +13 -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 +52 -13
  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 +32 -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 +547 -145
  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/policy.ts +1 -0
  54. package/packages/core/src/events/repository.ts +33 -3
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +31 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/be211f0e31a65006.json.gz +0 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/312cc4090820a612.json +1078 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  61. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  62. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  63. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a2780567b4989fb6.json +105 -0
  64. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  65. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  66. package/packages/core/src/kernel/dispatch-capacity.ts +243 -107
  67. package/packages/core/src/kernel/done-escalations.ts +273 -0
  68. package/packages/core/src/kernel/engine.ts +28 -9
  69. package/packages/core/src/kernel/integration-landing.ts +24 -4
  70. package/packages/core/src/kernel/integration-stack.ts +39 -0
  71. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  72. package/packages/core/src/kernel/log-index-value.ts +3 -0
  73. package/packages/core/src/kernel/log-index.ts +41 -2
  74. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  75. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  76. package/packages/core/src/kernel/reducer-revisions.ts +19 -0
  77. package/packages/core/src/kernel/reducer.ts +42 -8
  78. package/packages/core/src/kernel/repository-attention.ts +14 -5
  79. package/packages/core/src/kernel/repository-read-facts.ts +9 -0
  80. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  81. package/packages/core/src/kernel/verify-stages.ts +46 -7
  82. package/packages/core/src/operator/attention.ts +28 -3
  83. package/packages/core/src/operator/done-escalations.ts +38 -0
  84. package/packages/core/src/operator/presentation.ts +1 -1
  85. package/packages/core/src/operator/protocol.ts +8 -5
  86. package/packages/core/src/operator/query.ts +33 -19
  87. package/packages/core/src/operator/registry.ts +17 -13
  88. package/packages/core/src/operator/ticket-start.ts +8 -7
  89. package/packages/core/src/operator/tickets.ts +28 -9
  90. package/packages/core/src/plugin-sdk/index.ts +10 -0
  91. package/packages/core/src/plugins/manifest.ts +14 -1
  92. package/packages/core/src/ports/forge/create.ts +8 -0
  93. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  94. package/packages/core/src/ports/forge/github.ts +3 -0
  95. package/packages/core/src/ports/tickets/contract.ts +147 -76
  96. package/packages/core/src/ports/tickets/create.ts +47 -7
  97. package/packages/core/src/ports/tickets/fake.ts +8 -4
  98. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  99. package/packages/core/src/ports/tickets/file.ts +7 -3
  100. package/packages/core/src/ports/tickets/github.ts +1 -0
  101. package/packages/core/src/ports/tickets/grants.ts +11 -3
  102. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  103. package/packages/core/src/ports/tickets/linear.ts +28 -9
  104. package/packages/core/src/ports/tickets/migration.ts +4 -4
  105. package/packages/core/src/ports/tickets/operations.ts +4 -2
  106. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  107. package/packages/core/src/ports/tickets/priority.ts +127 -21
  108. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  109. package/packages/core/src/ports/tickets/remote.ts +104 -11
  110. package/packages/core/src/ports/tickets/revision.ts +5 -3
  111. package/packages/core/src/ports/tickets/search.ts +9 -0
  112. package/packages/core/src/ports/tickets/tree.ts +8 -6
  113. package/packages/core/src/ports/types.ts +30 -15
  114. package/packages/core/src/ports/workspace/build-execution.ts +13 -1
  115. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  116. package/packages/core/src/ports/workspace/create.ts +16 -3
  117. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  118. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  119. package/packages/core/src/ports/workspace/vercel-sandbox.ts +596 -144
  120. package/packages/core/src/processes/build-execution-state.ts +4 -0
  121. package/packages/core/src/processes/build-runner.ts +14 -1
  122. package/packages/core/src/processes/dispatcher.ts +841 -230
  123. package/packages/core/src/processes/execution-settlement.ts +25 -3
  124. package/packages/core/src/processes/harvest-runner.ts +12 -7
  125. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  126. package/packages/core/src/processes/invocation-budget.ts +176 -0
  127. package/packages/core/src/processes/publication-loss.ts +38 -3
  128. package/packages/core/src/processes/tick-publication.ts +1 -0
  129. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  130. package/packages/core/src/store/contract.ts +88 -3
  131. package/packages/core/src/store/event-reads.ts +30 -1
  132. package/packages/core/src/store/reduced-reads.ts +23 -0
  133. package/packages/core/src/store/reducer-value-shapes.json +6759 -6490
  134. package/packages/core/src/store/reducer-value-validation.ts +188 -33
  135. package/packages/core/src/store/remote/client.ts +169 -29
  136. package/packages/core/src/store/remote/compatibility.ts +113 -56
  137. package/packages/core/src/store/remote/credentials.ts +4 -1
  138. package/packages/core/src/store/remote/protocol.ts +3 -0
  139. package/packages/core/src/store/remote/released-clients.json +22 -0
  140. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  141. package/packages/core/src/store/remote/released-reducer-values/1.14.0.json +36076 -0
  142. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  143. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  144. package/packages/core/src/store/remote/retry.ts +406 -0
  145. package/packages/core/src/store/repo-state-events.ts +1 -0
  146. package/packages/core/src/testing/dispatch-read-budget.ts +155 -11
  147. package/packages/core/src/testing/index.ts +2 -0
  148. package/packages/core/src/testing/invocation-budget.ts +42 -0
  149. package/packages/core/src/testing/reduced-read-budget.ts +589 -19
  150. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  151. package/packages/core/src/web/overview-source.ts +19 -6
  152. package/skills/guide/SKILL.md +147 -67
  153. package/skills/guide/references/integration-tree.md +12 -9
  154. package/skills/guide/references/merge-policy.md +7 -2
  155. package/skills/guide/references/operator-api.md +46 -23
  156. package/skills/guide/references/optimization-nodes.md +7 -6
  157. package/skills/guide/references/plugin-authoring.md +46 -18
  158. package/skills/guide/references/remote-store-protocol.md +52 -13
  159. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  160. package/skills/guide/references/restacking.md +48 -3
  161. package/skills/guide/references/setup.md +2 -1
  162. package/skills/guide/references/ticket-migration.md +2 -2
  163. package/skills/operate/SKILL.md +136 -55
  164. package/skills/plan/SKILL.md +4 -3
  165. package/skills/spec/SKILL.md +9 -5
  166. package/skills/tickets/SKILL.md +25 -17
  167. package/templates/hosted-service/package.json +2 -2
@@ -15,6 +15,7 @@ import type {
15
15
  TicketListing,
16
16
  TicketPage,
17
17
  TicketPageListing,
18
+ TicketPriority,
18
19
  TicketSearchPage,
19
20
  TicketSearchQuery,
20
21
  TicketSource,
@@ -23,6 +24,16 @@ import type {
23
24
  } from '../types'
24
25
  import { RemoteBuildStore, AuthError } from '../../store/remote/client'
25
26
  import { errorBodySchema } from '../../store/remote/protocol'
27
+ import {
28
+ RemoteUnavailableError,
29
+ fetchWithRetry,
30
+ isTransientStatus,
31
+ resolveRemoteRetry,
32
+ responseAttempts,
33
+ type RemoteRetryOptions,
34
+ type RemoteRetryPolicy,
35
+ type RetrySafety,
36
+ } from '../../store/remote/retry'
26
37
  import {
27
38
  claimWireSchema,
28
39
  TICKET_TREE_HEADER,
@@ -37,6 +48,8 @@ import {
37
48
  TICKET_ISSUE_LINKS_CAPABILITY,
38
49
  TICKET_PRIORITY_HEADER,
39
50
  TICKET_PRIORITY_CAPABILITY,
51
+ TICKET_PRIORITY_LEVELS_HEADER,
52
+ TICKET_PRIORITY_LEVELS_CAPABILITY,
40
53
  TICKET_DEPENDENCY_STATE_HEADER,
41
54
  TICKET_DEPENDENCY_STATE_CAPABILITY,
42
55
  TICKET_POLICY_ROLES_HEADER,
@@ -77,8 +90,29 @@ export interface HostedTicketSourceOptions extends HostedTicketContext {
77
90
  url: string
78
91
  token: string
79
92
  fetchFn?: HostedTicketFetch
93
+ /** Transient-failure retries; `false` makes a single attempt. */
94
+ retry?: RemoteRetryOptions
80
95
  }
81
96
 
97
+ /** Operations whose retry after a lost response is harmless: reads, and
98
+ * set-or-replace writes whose repeat is a no-op or a typed revision conflict. */
99
+ const IDEMPOTENT_TICKET_OPERATIONS: ReadonlySet<string> = new Set([
100
+ 'policy',
101
+ 'list-ready',
102
+ 'list-targeting',
103
+ 'list-page',
104
+ 'search',
105
+ 'states',
106
+ 'state-counts',
107
+ 'get',
108
+ 'dependency-states',
109
+ 'transition',
110
+ 'update',
111
+ 'add-blocker',
112
+ 'remove-blocker',
113
+ 'mutate-if-revision',
114
+ ])
115
+
82
116
  /** The project ticket policy a hosted `[tickets]` table publishes. The backlog
83
117
  * and rejected roles appear only when configured, and `createLabels` only when
84
118
  * nonempty, so a policy without them is exactly what services predating them
@@ -132,6 +166,7 @@ export class HostedTicketSource implements TicketSource {
132
166
  private readonly base: string
133
167
  private readonly token: string
134
168
  private readonly fetchFn: HostedTicketFetch
169
+ private readonly retry: RemoteRetryPolicy | false
135
170
  private readonly context: HostedTicketContext
136
171
  /** Unknown until a response settles it; see `noteCapabilities`. */
137
172
  private targetingSupport: boolean | undefined
@@ -150,6 +185,7 @@ export class HostedTicketSource implements TicketSource {
150
185
  url: options.url,
151
186
  token: options.token,
152
187
  ...(options.fetchFn ? { fetchFn: options.fetchFn as typeof fetch } : {}),
188
+ ...(options.retry !== undefined ? { retry: options.retry } : {}),
153
189
  })
154
190
  this.assets = {
155
191
  ticketAssetLimits: client.ticketAssetLimits.bind(client),
@@ -161,6 +197,7 @@ export class HostedTicketSource implements TicketSource {
161
197
  this.base = options.url.replace(/\/+$/, '')
162
198
  this.token = options.token
163
199
  this.fetchFn = options.fetchFn ?? fetch
200
+ this.retry = resolveRemoteRetry(options.retry)
164
201
  this.context = {
165
202
  teamKey: options.teamKey,
166
203
  ...(options.repo !== undefined ? { repo: options.repo } : {}),
@@ -179,6 +216,14 @@ export class HostedTicketSource implements TicketSource {
179
216
  })
180
217
  }
181
218
 
219
+ /** The dispatcher's ticket preparation (at its first tick boundary): publish
220
+ * the project policy when given, then settle targeted listing, which the
221
+ * policy response normally answers for free. */
222
+ async prepareForDispatch(policy: HostedTicketPolicy | undefined): Promise<void> {
223
+ if (policy !== undefined) await this.synchronizePolicy(policy)
224
+ await this.negotiateTargeting()
225
+ }
226
+
182
227
  /** Present only once the service has positively advertised `list-targeting`;
183
228
  * while support is unknown or refused, observation keeps the exhaustive path. */
184
229
  get listTargeting(): TicketSource['listTargeting'] {
@@ -230,8 +275,21 @@ export class HostedTicketSource implements TicketSource {
230
275
  else if (response.ok) this.searchSupport = false
231
276
  }
232
277
 
233
- private async send(operation: string, input: unknown): Promise<Response> {
234
- const response = await this.fetchFn(`${this.base}/tickets/${operation}`, {
278
+ private async send(
279
+ operation: string,
280
+ input: unknown,
281
+ safety: RetrySafety = IDEMPOTENT_TICKET_OPERATIONS.has(operation) ? 'idempotent' : 'unsafe',
282
+ ): Promise<Response> {
283
+ const response = await fetchWithRetry(
284
+ (signal) => this.fetchFn(`${this.base}/tickets/${operation}`, this.init(input, signal)),
285
+ { safety, policy: this.retry, label: 'ticket service' },
286
+ )
287
+ this.noteCapabilities(response)
288
+ return response
289
+ }
290
+
291
+ private init(input: unknown, signal: AbortSignal | undefined): RequestInit {
292
+ return {
235
293
  method: 'POST',
236
294
  headers: {
237
295
  [TICKET_TREE_HEADER]: TICKET_TREE_CAPABILITY,
@@ -241,6 +299,7 @@ export class HostedTicketSource implements TicketSource {
241
299
  [TICKET_REVISIONS_HEADER]: TICKET_REVISIONS_CAPABILITY,
242
300
  [TICKET_ISSUE_LINKS_HEADER]: TICKET_ISSUE_LINKS_CAPABILITY,
243
301
  [TICKET_PRIORITY_HEADER]: TICKET_PRIORITY_CAPABILITY,
302
+ [TICKET_PRIORITY_LEVELS_HEADER]: TICKET_PRIORITY_LEVELS_CAPABILITY,
244
303
  [TICKET_DEPENDENCY_STATE_HEADER]: TICKET_DEPENDENCY_STATE_CAPABILITY,
245
304
  [TICKET_POLICY_ROLES_HEADER]: TICKET_POLICY_ROLES_CAPABILITY,
246
305
  [TICKET_POLICY_CREATE_LABELS_HEADER]: TICKET_POLICY_CREATE_LABELS_CAPABILITY,
@@ -251,9 +310,8 @@ export class HostedTicketSource implements TicketSource {
251
310
  [REMOTE_STORE_PROTOCOL_VERSION_HEADER]: REMOTE_STORE_PROTOCOL_VERSION,
252
311
  },
253
312
  body: JSON.stringify({ context: this.context, input }),
254
- })
255
- this.noteCapabilities(response)
256
- return response
313
+ ...(signal !== undefined ? { signal } : {}),
314
+ }
257
315
  }
258
316
 
259
317
  private project(ticket: Ticket): Ticket {
@@ -267,11 +325,14 @@ export class HostedTicketSource implements TicketSource {
267
325
  names: {
268
326
  issueLinks?: boolean
269
327
  priority?: boolean
328
+ /** The write names `high` or `low`. */
329
+ priorityLevel?: boolean
270
330
  policyRoles?: boolean
271
331
  policyCreateLabels?: boolean
272
332
  } = {},
333
+ safety?: RetrySafety,
273
334
  ): Promise<T> {
274
- const response = await this.send(operation, input)
335
+ const response = await this.send(operation, input, safety)
275
336
  if (!response.ok) {
276
337
  // A service predating targeted listing has no such route (or refuses it
277
338
  // with a strict schema) and never echoes the capability header. The read
@@ -328,8 +389,10 @@ export class HostedTicketSource implements TicketSource {
328
389
  'ticket service predates backlog/rejected roles in ticket policy; upgrade the service or unset [tickets].backlogState and rejectedState',
329
390
  )
330
391
  let message = `ticket service responded ${response.status}`
392
+ let parsedBody: unknown
331
393
  try {
332
394
  const body = (await response.json()) as Record<string, unknown>
395
+ parsedBody = body
333
396
  if (
334
397
  response.status === 409 &&
335
398
  typeof body.currentRevision === 'string' &&
@@ -367,6 +430,16 @@ export class HostedTicketSource implements TicketSource {
367
430
  message.includes('priority')
368
431
  )
369
432
  throw new TicketPriorityUnsupported(this.name)
433
+ // A server storing only urgent and normal refuses `high` and `low`
434
+ // with its strict request schema and never echoes the levels header.
435
+ if (
436
+ names.priorityLevel &&
437
+ response.status === 400 &&
438
+ response.headers.get(TICKET_PRIORITY_LEVELS_HEADER) !==
439
+ TICKET_PRIORITY_LEVELS_CAPABILITY &&
440
+ message.includes('priority')
441
+ )
442
+ throw new TicketPriorityUnsupported(this.name)
370
443
  } catch (error) {
371
444
  if (
372
445
  error instanceof TicketRevisionConflict ||
@@ -380,6 +453,11 @@ export class HostedTicketSource implements TicketSource {
380
453
  // Keep the status-only safe fallback for non-protocol responses.
381
454
  }
382
455
  if (response.status === 401 || response.status === 403) throw new AuthError(message)
456
+ if (isTransientStatus(response.status, parsedBody))
457
+ throw new RemoteUnavailableError(message, {
458
+ status: response.status,
459
+ attempts: responseAttempts(response),
460
+ })
383
461
  throw new Error(message)
384
462
  }
385
463
  return schema.parse(await response.json())
@@ -516,13 +594,21 @@ export class HostedTicketSource implements TicketSource {
516
594
  // working against a service predating it.
517
595
  async create(draft: TicketDraft, options: TicketCreateOptions = {}): Promise<Ticket> {
518
596
  const { priority, ...rest } = draft
519
- const write = priority === 'urgent' ? { ...rest, priority } : rest
597
+ const write = priority !== undefined && priority !== 'normal' ? { ...rest, priority } : rest
520
598
  const { idempotencyKeyReservedAt: _reservedAt, ...wireOptions } = options
521
599
  return this.project(
522
- await this.request('create', { draft: write, options: wireOptions }, ticketWireSchema, {
523
- issueLinks: write.issueLinks !== undefined,
524
- priority: priority === 'urgent',
525
- }),
600
+ await this.request(
601
+ 'create',
602
+ { draft: write, options: wireOptions },
603
+ ticketWireSchema,
604
+ {
605
+ issueLinks: write.issueLinks !== undefined,
606
+ priority: 'priority' in write,
607
+ priorityLevel: namesLevel(priority),
608
+ },
609
+ // A keyed create is answered by the earlier ticket on a repeat.
610
+ options.idempotencyKey !== undefined ? 'idempotent' : 'unsafe',
611
+ ),
526
612
  )
527
613
  }
528
614
 
@@ -539,6 +625,7 @@ export class HostedTicketSource implements TicketSource {
539
625
  ? {
540
626
  issueLinks: mutation.patch.issueLinks !== undefined,
541
627
  priority: mutation.patch.priority !== undefined,
628
+ priorityLevel: namesLevel(mutation.patch.priority),
542
629
  }
543
630
  : {},
544
631
  )
@@ -548,6 +635,7 @@ export class HostedTicketSource implements TicketSource {
548
635
  await this.request('update', { id, patch }, successWireSchema, {
549
636
  issueLinks: patch.issueLinks !== undefined,
550
637
  priority: patch.priority !== undefined,
638
+ priorityLevel: namesLevel(patch.priority),
551
639
  })
552
640
  }
553
641
 
@@ -563,3 +651,8 @@ export class HostedTicketSource implements TicketSource {
563
651
  return this.request('dependency-states', { ids }, dependencyStatesWireSchema)
564
652
  }
565
653
  }
654
+
655
+ /** A level only a server echoing the priority-levels header can store. */
656
+ function namesLevel(priority: TicketPriority | undefined): boolean {
657
+ return priority === 'high' || priority === 'low'
658
+ }
@@ -39,9 +39,11 @@ export function ticketRevision(
39
39
  ...(issueLinks.length > 0
40
40
  ? [['issueLinks', issueLinks.map((link) => [link.issue, link.intent])]]
41
41
  : []),
42
- // Appended only when urgent, for the same reason: normal tickets keep
43
- // the revisions they had before priority existed.
44
- ...(ticket.priority === 'urgent' ? [['priority', 'urgent']] : []),
42
+ // Appended only when not normal, for the same reason: normal tickets
43
+ // keep the revisions they had before priority existed.
44
+ ...(ticket.priority !== undefined && ticket.priority !== 'normal'
45
+ ? [['priority', ticket.priority]]
46
+ : []),
45
47
  ]),
46
48
  )
47
49
  .digest('hex')
@@ -56,9 +56,17 @@ export function searchHit(ticket: Ticket): TicketSearchHit {
56
56
  labels: [...ticket.labels],
57
57
  kind: ticket.kind ?? 'work',
58
58
  ...(ticket.target !== undefined ? { target: ticket.target } : {}),
59
+ ...hitPriority(ticket),
59
60
  }
60
61
  }
61
62
 
63
+ /** A non-normal level, or nothing: absent and `normal` stay byte-identical,
64
+ * an unrecognised value is dropped. */
65
+ function hitPriority(value: { priority?: unknown }): Pick<TicketSearchHit, 'priority'> {
66
+ const level = value.priority
67
+ return level === 'urgent' || level === 'high' || level === 'low' ? { priority: level } : {}
68
+ }
69
+
62
70
  /** Search an in-memory listing in its own order. `query.state` must already be
63
71
  * the source's canonical state name. The cursor is a decimal match offset. */
64
72
  export function pageSearch(
@@ -135,5 +143,6 @@ function normalizeHit(hit: TicketSearchHit): TicketSearchHit {
135
143
  labels: [...hit.labels],
136
144
  kind: hit.kind ?? 'work',
137
145
  ...(hit.target !== undefined ? { target: hit.target } : {}),
146
+ ...hitPriority(hit),
138
147
  }
139
148
  }
@@ -2,7 +2,8 @@ import type { Ticket, TicketDraft, TicketSource, TicketUpdate } from '../types'
2
2
  import { checkTicketRevision } from './revision'
3
3
  import { validateTicketUpdate } from './update'
4
4
  import { refuseUnsupportedIssueLinks } from './issue-links'
5
- import { refuseUnsupportedPriority, withoutUnsupportedPriority } from './priority'
5
+ import { refuseUnsupportedPriority, ticketPriority, withoutUnsupportedPriority } from './priority'
6
+ import { priorityLabelSource } from './priority-labels'
6
7
  import { refuseUnsupportedAssignees } from './assignees'
7
8
  import { objectiveBlocks } from '../../objective'
8
9
 
@@ -14,14 +15,14 @@ export function normalizeTicket(
14
15
  priority = true,
15
16
  assignees = true,
16
17
  ): Ticket {
17
- const { target, issueLinks: links, priority: urgency, assignees: assigned, ...rest } = ticket
18
+ const { target, issueLinks: links, priority: level, assignees: assigned, ...rest } = ticket
18
19
  return {
19
20
  ...rest,
20
21
  kind: supported ? (ticket.kind ?? 'work') : 'work',
21
22
  ...(supported && target !== undefined ? { target } : {}),
22
23
  ...(issueLinks && links !== undefined ? { issueLinks: links } : {}),
23
24
  // Normal is the absence of the field, so strict wire schemas never see it.
24
- ...(priority && urgency === 'urgent' ? { priority: urgency } : {}),
25
+ ...(priority && ticketPriority({ priority: level }) !== 'normal' ? { priority: level } : {}),
25
26
  ...(assignees && assigned !== undefined ? { assignees: assigned } : {}),
26
27
  }
27
28
  }
@@ -105,11 +106,12 @@ function writablePatch(source: TicketSource, patch: TicketUpdate): TicketUpdate
105
106
  }
106
107
 
107
108
  /** Forward through an empty facade so frozen source properties do not constrain
108
- * proxy results. Methods and accessors still receive the original source. */
109
+ * proxy results. Methods and accessors still receive the original source. A
110
+ * source without native priority gets the `priority:<level>` label fallback. */
109
111
  export function compatibleTicketSource(source: TicketSource): TicketSource {
110
- return new Proxy(Object.create(source) as TicketSource, {
112
+ const target = source.priority ? source : priorityLabelSource(source)
113
+ return new Proxy(Object.create(target) as TicketSource, {
111
114
  get(_facade, property) {
112
- const target = source
113
115
  const value = Reflect.get(target, property, target)
114
116
  if (typeof value !== 'function') return value
115
117
  if (property === 'get')
@@ -94,16 +94,21 @@ export interface Ticket {
94
94
  /** Forge issues this ticket addresses, sorted by issue number. Absent ≡ none
95
95
  * or unsupported by the source. */
96
96
  issueLinks?: IssueLink[]
97
- /** `urgent` dispatches before normal ready work. Absent means normal, or a
98
- * source that cannot store priority. Normalized tickets never carry `normal`. */
97
+ /** Priority level. Absent means `normal`; normalized tickets never carry
98
+ * `normal`. Dispatch claims ready work by level, urgent, high, normal, then
99
+ * low, never preempting a running build. */
99
100
  priority?: TicketPriority
100
101
  /** Usernames the ticket is assigned to. Present (possibly empty) only for
101
102
  * sources with the `assignees` capability; not part of `revision`. */
102
103
  assignees?: string[]
103
104
  }
104
105
 
105
- /** Dispatch class: urgent ready work is claimed before normal ready work. */
106
- export type TicketPriority = 'urgent' | 'normal'
106
+ /** A ticket's priority level, highest first. `normal` is the default. */
107
+ export type TicketPriority = 'urgent' | 'high' | 'normal' | 'low'
108
+
109
+ /** A build's slot-admission level, the same four levels as a ticket's. A
110
+ * build claimed from a ticket takes the ticket's level (`dispatchPriority`). */
111
+ export type BuildPriority = TicketPriority
107
112
 
108
113
  export type IssueLinkIntent = 'closes' | 'refs'
109
114
 
@@ -161,6 +166,8 @@ export interface TicketSearchHit {
161
166
  labels: string[]
162
167
  kind: TicketKind
163
168
  target?: string
169
+ /** Same meaning as Ticket.priority: absent means `normal`. */
170
+ priority?: TicketPriority
164
171
  }
165
172
 
166
173
  export interface TicketSearchPage {
@@ -193,8 +200,9 @@ export interface TicketDraft {
193
200
  /** Forge issues this ticket addresses. An adapter without the `issueLinks`
194
201
  * capability must refuse, never discard. */
195
202
  issueLinks?: IssueLink[]
196
- /** Dispatch class. A source without the `priority` capability refuses
197
- * `urgent`; `normal` is a no-op. */
203
+ /** Priority level; absent files the ticket at `normal`. A raw source without
204
+ * the `priority` capability refuses any other level; the compatibility
205
+ * facade stores it as a `priority:<level>` label instead. */
198
206
  priority?: TicketPriority
199
207
  /** Exact assignees: entries are usernames or `me` (the owner of the source's
200
208
  * credential). Callers apply any `[tickets].createAssignee` default. A source
@@ -262,8 +270,9 @@ export interface TicketUpdate {
262
270
  labels?: string[]
263
271
  /** A complete issue-link replacement. An explicit empty array clears links. */
264
272
  issueLinks?: IssueLink[]
265
- /** `normal` removes urgency. A source without the `priority` capability
266
- * refuses `urgent`; `normal` is a no-op. */
273
+ /** Replaces the priority level; `normal` clears it. A raw source without the
274
+ * `priority` capability refuses any other level; the compatibility facade
275
+ * stores it as a `priority:<level>` label instead. */
267
276
  priority?: TicketPriority
268
277
  /** A complete assignee replacement; entries are usernames or `me`. An
269
278
  * explicit empty array clears assignees. A source without the `assignees`
@@ -349,13 +358,19 @@ export interface TicketSource {
349
358
  /** Opt in only when kind/target persistence, graph validation and complete
350
359
  * enumeration are supported at every write boundary, including guarded writes. */
351
360
  readonly integrationTree?: boolean
361
+ /** The label through which this source records the `node` kind, when it
362
+ * records kind as a label rather than natively. The priority-label fallback
363
+ * adds or removes it to match a kind change written beside a priority; on
364
+ * sources without it, that fallback never touches a non-priority label. */
365
+ readonly kindLabel?: string
352
366
  /** Opt in only when issue links are persisted and returned at every write
353
367
  * boundary, including create and guarded writes. Sources without it refuse
354
368
  * any write naming issue links. */
355
369
  readonly issueLinks?: boolean
356
- /** Opt in only when urgent priority is persisted and returned at every write
357
- * boundary, including create and guarded writes. Sources without it read
358
- * every ticket as normal and refuse any write naming `urgent`. */
370
+ /** Opt in only when all four priority levels are persisted natively and
371
+ * returned at every write boundary, including create and guarded writes.
372
+ * A raw source without it refuses any level but `normal`; the compatibility
373
+ * facade gives it the `priority:<level>` label fallback instead. */
359
374
  readonly priority?: boolean
360
375
  /** Opt in only when assignees are persisted, returned on every read (an
361
376
  * empty array when unassigned) and verified at every write boundary,
@@ -422,10 +437,10 @@ export interface TicketSource {
422
437
  * Fatal source failures and invariants still reject the call. */
423
438
  listReady(criteria: TicketCriteria): Promise<TicketListing>
424
439
  /** Optional native window over the listReady matches. `oldest` (default)
425
- * is dispatch order: with `priority`, urgent first, then normal, each in
426
- * listReady order. `newest` is newest filed first: creation time descending,
427
- * independent of urgency, with a stable tie-break; it is not the reverse of
428
- * dispatch order. Offset and limit apply after ordering. Default offset 0.
440
+ * is priority order: with `priority`, urgent, then high, then normal, then
441
+ * low, each in listReady order. `newest` is newest filed first: creation
442
+ * time descending, independent of priority, with a stable tie-break; it is
443
+ * not the reverse of priority order. Offset and limit apply after ordering. Default offset 0.
429
444
  * Arguments are nonnegative integers; zero limit returns no tickets with the
430
445
  * full matching total. Diagnostics
431
446
  * and failures match listReady; a failure must not trigger a full-read fallback.
@@ -1,3 +1,5 @@
1
+ import type { WorkspaceRecoveryStep } from './recovery-step'
2
+
1
3
  /** Immutable identity passed when a workspace-adjacent executor is asked to
2
4
  * start a build. Build state, workspace location, config, progress, and outcome
3
5
  * are deliberately absent: both sides obtain those only from the BuildStore. */
@@ -67,6 +69,10 @@ export interface BuildExecutionIdentity {
67
69
  /** Provider-native detached command identity, recorded durably at launch so
68
70
  * a later process can re-observe the execution without process memory. */
69
71
  commandId?: string
72
+ /** The execution instance being observed. In-memory observation input
73
+ * only, never persisted as part of the identity: it keys the runner's own
74
+ * exit record when the provider can no longer report the command's state. */
75
+ instance?: string
70
76
  }
71
77
 
72
78
  /** Teardown must distinguish proof from an interrupted/ambiguous acknowledgement. */
@@ -108,7 +114,13 @@ export interface BuildExecutionHandle {
108
114
  * exit code; `lost` means the provider proved the environment/command no
109
115
  * longer exists without an exit code. */
110
116
  export type ExecutionObservation = (
111
- | { state: 'running' }
117
+ | {
118
+ state: 'running'
119
+ /** Observation could not finish within the invocation budget; this
120
+ * proves neither liveness nor exit, and the caller retries. `step`
121
+ * names the recovery step it waited on. */
122
+ deferred?: { step: WorkspaceRecoveryStep; detail: string }
123
+ }
112
124
  | { state: 'ended'; exitCode?: number }
113
125
  | { state: 'lost' }
114
126
  ) & {
@@ -94,6 +94,10 @@ const BUILTINS: Record<string, BuiltinWorkspaceProviderDeclaration> = {
94
94
  ...(opts.sandboxEgressReadCredential !== undefined
95
95
  ? { egressReadCredential: opts.sandboxEgressReadCredential }
96
96
  : {}),
97
+ ...(opts.fetchFn !== undefined ? { fetch: opts.fetchFn } : {}),
98
+ ...(opts.invocationDeadlineAt !== undefined
99
+ ? { invocationDeadlineAt: opts.invocationDeadlineAt }
100
+ : {}),
97
101
  })
98
102
  },
99
103
  },
@@ -62,6 +62,16 @@ export interface CreateWorkspaceProviderOptions {
62
62
  * provider places it only in the host-side upload-pack egress transform,
63
63
  * never in a create `source`, a guest command, or the guest env. */
64
64
  sandboxEgressReadCredential?: { username: string; password: string }
65
+ /** Host fetch: the builtin `vercel-sandbox` SDK transport, and the plugin
66
+ * factory context's `fetch` (plugin API ≥ 1.12). Absent ⇒ global `fetch`.
67
+ * A bounded dispatcher invocation passes one that cancels at its deadline. */
68
+ fetchFn?: typeof fetch
69
+ /** Plugin factory context `invocationSignal`; absent ⇒ `() => undefined`. */
70
+ invocationSignal?: () => AbortSignal | undefined
71
+ /** Builtin-only: the hosted invocation's deadline (epoch ms). The built-in
72
+ * sandbox bounds every recovery-path provider call by it, so recovery
73
+ * never runs past the invocation. Plugin factories never receive it. */
74
+ invocationDeadlineAt?: number
65
75
  }
66
76
 
67
77
  export interface WorkspaceRuntime {
@@ -145,8 +155,9 @@ export async function createWorkspaceProvider(
145
155
 
146
156
  try {
147
157
  // Conditional spreads keep the existing exactness guarantee: a call site
148
- // that supplies no seams constructs exactly `{ config, env, repoRoot }`,
149
- // so plugin factories see no `undefined`-valued additions. With seams,
158
+ // that supplies no seams constructs exactly `{ config, env, repoRoot }`
159
+ // plus the plugin API 1.12 `fetch` and `invocationSignal`, so plugin
160
+ // factories see no `undefined`-valued additions. With seams,
150
161
  // the context widens in place (AUT-560) — the seams the builtin factory
151
162
  // receives through `opts` reach the plugin factory through the context.
152
163
  return await factory({
@@ -157,6 +168,8 @@ export async function createWorkspaceProvider(
157
168
  ),
158
169
  ),
159
170
  repoRoot: resolve(opts.repoRoot),
171
+ fetch: opts.fetchFn ?? globalThis.fetch,
172
+ invocationSignal: opts.invocationSignal ?? (() => undefined),
160
173
  ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
161
174
  ...(opts.storeRef !== undefined && opts.storeToken !== undefined
162
175
  ? {
@@ -164,7 +177,7 @@ export async function createWorkspaceProvider(
164
177
  _ref: string,
165
178
  _token: string | undefined,
166
179
  target: Parameters<typeof delegateCredential>[2],
167
- ) => delegateCredential(opts.storeRef!, opts.storeToken, target),
180
+ ) => delegateCredential(opts.storeRef!, opts.storeToken, target, opts.fetchFn),
168
181
  }
169
182
  : {}),
170
183
  ...(opts.accounts !== undefined ? { accounts: opts.accounts } : {}),
@@ -0,0 +1,41 @@
1
+ /** The guest runner's own record of its exit, written on the environment's
2
+ * persistent filesystem just before the process exits. A provider that can
3
+ * no longer read the command's final state (a stopped persistent sandbox)
4
+ * reads this file instead, keyed by the execution instance. */
5
+ import { mkdirSync, renameSync, writeFileSync } from 'node:fs'
6
+ import { dirname } from 'node:path'
7
+
8
+ /** Guest environment variable naming the marker path for this execution. */
9
+ export const EXECUTION_EXIT_FILE_ENV = 'AB_EXECUTION_EXIT_FILE'
10
+
11
+ export function formatExecutionExit(instance: string, exitCode: number): string {
12
+ return `${JSON.stringify({ instance, exitCode })}\n`
13
+ }
14
+
15
+ /** The recorded exit code for exactly this instance, or null when the text is
16
+ * malformed, belongs to another instance, or carries no integer code. */
17
+ export function parseExecutionExit(text: string, instance: string): number | null {
18
+ let value: unknown
19
+ try {
20
+ value = JSON.parse(text)
21
+ } catch {
22
+ return null
23
+ }
24
+ if (value === null || typeof value !== 'object') return null
25
+ const record = value as { instance?: unknown; exitCode?: unknown }
26
+ if (record.instance !== instance) return null
27
+ return Number.isInteger(record.exitCode) ? (record.exitCode as number) : null
28
+ }
29
+
30
+ /** Atomically write the marker. Never throws: a failed marker write must not
31
+ * change the runner's exit code. */
32
+ export function writeExecutionExitSync(path: string, instance: string, exitCode: number): void {
33
+ try {
34
+ mkdirSync(dirname(path), { recursive: true })
35
+ const temporary = `${path}.${process.pid}.tmp`
36
+ writeFileSync(temporary, formatExecutionExit(instance, exitCode))
37
+ renameSync(temporary, path)
38
+ } catch {
39
+ /* best effort */
40
+ }
41
+ }
@@ -0,0 +1,101 @@
1
+ /** Provider-neutral vocabulary for the steps of workspace recovery, so a
2
+ * recorded failure says which one broke: resuming a stopped environment,
3
+ * fencing its execution, preserving its commits, or cleaning it up.
4
+ *
5
+ * The step travels inside the existing `infrastructure.failed` error text and
6
+ * escalation question; no event schema carries it. Messages avoid the words
7
+ * the infrastructure classifier reads as provider limits, and timeout
8
+ * messages say "timeout" so they classify as one. */
9
+
10
+ export type WorkspaceRecoveryStep = 'resume' | 'fence' | 'preserve' | 'cleanup'
11
+
12
+ const STEPS: readonly WorkspaceRecoveryStep[] = ['resume', 'fence', 'preserve', 'cleanup']
13
+
14
+ function detailOf(error: unknown): string {
15
+ if (error instanceof Error) return error.message
16
+ if (typeof error === 'object' && error !== null) {
17
+ const message = (error as { message?: unknown }).message
18
+ if (typeof message === 'string') return message
19
+ }
20
+ return String(error)
21
+ }
22
+
23
+ /** A recovery operation failed at a named step. */
24
+ export class WorkspaceRecoveryStepError extends Error {
25
+ readonly step: WorkspaceRecoveryStep
26
+
27
+ constructor(step: WorkspaceRecoveryStep, failure: unknown) {
28
+ super(
29
+ `workspace recovery step "${step}" failed: ${detailOf(failure)}`,
30
+ failure instanceof Error ? { cause: failure } : undefined,
31
+ )
32
+ this.name = 'WorkspaceRecoveryStepError'
33
+ this.step = step
34
+ }
35
+ }
36
+
37
+ /** A recovery step stopped because the invocation deadline left too little
38
+ * time for it. Nothing failed: the caller keeps the workspace, records
39
+ * nothing, and the next invocation retries. */
40
+ export class WorkspaceRecoveryDeferred extends Error {
41
+ readonly step: WorkspaceRecoveryStep
42
+
43
+ constructor(
44
+ step: WorkspaceRecoveryStep,
45
+ detail: { remainingMs: number; requiredMs?: number },
46
+ options?: { cause?: unknown },
47
+ ) {
48
+ super(
49
+ detail.requiredMs === undefined
50
+ ? `workspace recovery step "${step}" stopped at the invocation deadline (timeout); ${Math.max(0, Math.round(detail.remainingMs))} ms remained; retrying next invocation`
51
+ : `workspace recovery step "${step}" deferred: ${Math.max(0, Math.round(detail.remainingMs))} ms remain before the invocation deadline but it needs ${detail.requiredMs} ms; retrying next invocation`,
52
+ options,
53
+ )
54
+ this.name = 'WorkspaceRecoveryDeferred'
55
+ this.step = step
56
+ }
57
+ }
58
+
59
+ const CHAIN_BOUND = 16
60
+
61
+ function* causeChain(error: unknown): Generator<unknown> {
62
+ const seen = new Set<unknown>()
63
+ let current = error
64
+ for (let depth = 0; depth < CHAIN_BOUND && current !== undefined && current !== null; depth++) {
65
+ if (seen.has(current)) return
66
+ seen.add(current)
67
+ yield current
68
+ current = typeof current === 'object' ? (current as { cause?: unknown }).cause : undefined
69
+ }
70
+ }
71
+
72
+ function stepOf(value: unknown): WorkspaceRecoveryStep | undefined {
73
+ if (value instanceof WorkspaceRecoveryStepError || value instanceof WorkspaceRecoveryDeferred)
74
+ return value.step
75
+ if (typeof value !== 'object' || value === null) return undefined
76
+ const step = (value as { step?: unknown }).step
77
+ return value instanceof Error && STEPS.includes(step as WorkspaceRecoveryStep)
78
+ ? (step as WorkspaceRecoveryStep)
79
+ : undefined
80
+ }
81
+
82
+ /** The first recovery step named anywhere in the error's cause chain. */
83
+ export function recoveryStepOf(error: unknown): WorkspaceRecoveryStep | undefined {
84
+ for (const value of causeChain(error)) {
85
+ const step = stepOf(value)
86
+ if (step !== undefined) return step
87
+ }
88
+ return undefined
89
+ }
90
+
91
+ /** True when the cause chain holds a deadline deferral. */
92
+ export function isRecoveryDeferred(error: unknown): boolean {
93
+ for (const value of causeChain(error)) if (value instanceof WorkspaceRecoveryDeferred) return true
94
+ return false
95
+ }
96
+
97
+ /** Name the step an error happened in, unless its chain already names one
98
+ * (an inner `resume` failure stays `resume`). */
99
+ export function attributeRecoveryStep(step: WorkspaceRecoveryStep, error: unknown): unknown {
100
+ return recoveryStepOf(error) === undefined ? new WorkspaceRecoveryStepError(step, error) : error
101
+ }