@defrex/autobuild 1.16.0 → 1.18.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 (97) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +132 -9
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +42 -3
  5. package/docs/configuration.md +44 -7
  6. package/docs/dispatcher-hosting.md +5 -3
  7. package/docs/operator-api.md +29 -6
  8. package/docs/plugin-authoring.md +30 -1
  9. package/docs/remote-store-protocol.md +13 -3
  10. package/docs/remote-ticket-protocol.md +37 -2
  11. package/docs/restacking.md +46 -1
  12. package/docs/setup.md +24 -9
  13. package/docs/ticket-sources.md +28 -1
  14. package/docs/troubleshooting.md +54 -2
  15. package/docs/workspaces.md +3 -1
  16. package/package.json +4 -4
  17. package/packages/core/src/cli/accounts.ts +3 -0
  18. package/packages/core/src/cli/binary-direct.ts +14 -1
  19. package/packages/core/src/cli/binary.ts +10 -7
  20. package/packages/core/src/cli/dashboard/refresh.ts +8 -0
  21. package/packages/core/src/cli/dispatch.ts +503 -334
  22. package/packages/core/src/cli/secrets.ts +2 -0
  23. package/packages/core/src/config/schema.ts +17 -3
  24. package/packages/core/src/events/payloads.ts +8 -5
  25. package/packages/core/src/events/repository.ts +37 -1
  26. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/d41044cb2e54809c.json +194 -0
  27. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e0f89f52e48cbf62.json +197 -0
  28. package/packages/core/src/kernel/engine.ts +118 -0
  29. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  30. package/packages/core/src/kernel/reducer-revisions.ts +5 -0
  31. package/packages/core/src/kernel/repository-read-facts.ts +9 -2
  32. package/packages/core/src/kernel/ticket-preparation.ts +10 -0
  33. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  34. package/packages/core/src/ontology.ts +1 -0
  35. package/packages/core/src/operator/index.ts +10 -0
  36. package/packages/core/src/operator/merged-builds.ts +51 -0
  37. package/packages/core/src/operator/registry.ts +254 -110
  38. package/packages/core/src/operator/repo-argument.ts +43 -0
  39. package/packages/core/src/operator/tickets.ts +139 -25
  40. package/packages/core/src/plugin-sdk/index.ts +4 -0
  41. package/packages/core/src/plugins/manifest.ts +1 -1
  42. package/packages/core/src/ports/tickets/completion.ts +71 -0
  43. package/packages/core/src/ports/tickets/contract.ts +73 -0
  44. package/packages/core/src/ports/tickets/github-fake.ts +8 -0
  45. package/packages/core/src/ports/tickets/github-issues.ts +1 -0
  46. package/packages/core/src/ports/tickets/github.ts +18 -6
  47. package/packages/core/src/ports/tickets/grants.ts +2 -0
  48. package/packages/core/src/ports/tickets/hosted-index.ts +8 -0
  49. package/packages/core/src/ports/tickets/linear.ts +18 -2
  50. package/packages/core/src/ports/tickets/remote-protocol.ts +37 -8
  51. package/packages/core/src/ports/tickets/remote.ts +43 -3
  52. package/packages/core/src/ports/tickets/tree.ts +11 -1
  53. package/packages/core/src/ports/types.ts +47 -4
  54. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  55. package/packages/core/src/ports/workspace/vercel-sandbox.ts +649 -160
  56. package/packages/core/src/processes/build-child.ts +15 -1
  57. package/packages/core/src/processes/build-runner.ts +349 -20
  58. package/packages/core/src/processes/dispatcher.ts +880 -283
  59. package/packages/core/src/processes/harvest-child.ts +21 -1
  60. package/packages/core/src/processes/harvest-runner.ts +82 -35
  61. package/packages/core/src/processes/pass-stages.ts +32 -6
  62. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  63. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  64. package/packages/core/src/processes/repo-view.ts +25 -4
  65. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  66. package/packages/core/src/store/adapter.ts +34 -5
  67. package/packages/core/src/store/build-feed.ts +148 -22
  68. package/packages/core/src/store/build-scope.ts +12 -3
  69. package/packages/core/src/store/caller-attribution.ts +170 -0
  70. package/packages/core/src/store/contract.ts +1038 -165
  71. package/packages/core/src/store/local/schema.ts +12 -1
  72. package/packages/core/src/store/local/store.ts +260 -25
  73. package/packages/core/src/store/memory.ts +156 -9
  74. package/packages/core/src/store/phase-session.ts +23 -3
  75. package/packages/core/src/store/reducer-value-shapes.json +8196 -8118
  76. package/packages/core/src/store/remote/client.ts +90 -11
  77. package/packages/core/src/store/remote/credentials.ts +2 -0
  78. package/packages/core/src/store/remote/index.ts +31 -5
  79. package/packages/core/src/store/remote/protocol.ts +45 -8
  80. package/packages/core/src/store/remote/released-clients.json +22 -0
  81. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  82. package/packages/core/src/store/remote/released-reducer-values/1.18.0.json +36436 -0
  83. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  84. package/packages/core/src/store/session-handle.ts +12 -3
  85. package/packages/core/src/store/types.ts +48 -3
  86. package/packages/core/src/testing/dispatch-read-budget.ts +143 -16
  87. package/packages/core/src/testing/index.ts +2 -0
  88. package/packages/core/src/testing/reduced-read-budget.ts +420 -6
  89. package/skills/guide/SKILL.md +67 -13
  90. package/skills/guide/references/operator-api.md +29 -6
  91. package/skills/guide/references/plugin-authoring.md +30 -1
  92. package/skills/guide/references/remote-store-protocol.md +13 -3
  93. package/skills/guide/references/remote-ticket-protocol.md +37 -2
  94. package/skills/guide/references/restacking.md +46 -1
  95. package/skills/guide/references/setup.md +24 -9
  96. package/skills/operate/SKILL.md +42 -4
  97. package/templates/hosted-service/package.json +2 -2
@@ -6,6 +6,7 @@ import { refineUniqueIssues } from './issue-links'
6
6
  import { holdsState } from './lifecycle'
7
7
  import { ticketPrioritySchema } from './priority'
8
8
  import { TICKET_SEARCH_MAX_LIMIT } from './search'
9
+ import { usesCompletionCriteria } from './completion'
9
10
 
10
11
  /** Explicit opt-in: released clients through 0.12 use strict decoders without revisions.
11
12
  * Source checkouts can share their release version, so version alone is insufficient. */
@@ -91,6 +92,18 @@ export const TICKET_PAGING_CAPABILITY = '1'
91
92
  export const TICKET_SEARCH_HEADER = 'x-autobuild-ticket-search'
92
93
  export const TICKET_SEARCH_CAPABILITY = '1'
93
94
 
95
+ /** Completion listing. A client sends it on every request; only then does a
96
+ * service answer tickets with `resolvedAt` and `targetTitle`, so released
97
+ * strict decoders never see them. Services that accept `list-page` completion
98
+ * criteria (`excludeLabels`, `since`, `until`, order `completed`) echo it on
99
+ * every ticket response, failures included, and a client sends those criteria
100
+ * only after a response carried it. A native completion query over more than
101
+ * its cap answers `409 {kind: 'conflict', code: 'completion-range-too-broad',
102
+ * error, limit}`; one the backing source cannot honour answers the existing
103
+ * `409` `paging-unsupported`. */
104
+ export const TICKET_COMPLETION_HEADER = 'x-autobuild-ticket-completion'
105
+ export const TICKET_COMPLETION_CAPABILITY = '1'
106
+
94
107
  /** The node id a client's `list-targeting` negotiation probe names. Hosted
95
108
  * readable ids are `<teamKey>-<n>` or legacy `ticket-<uuid>`, so it never
96
109
  * names a ticket and the probe is an indexed miss. */
@@ -127,6 +140,10 @@ export const ticketWireSchema = z.strictObject({
127
140
  blockedBy: z.array(z.string()).optional(),
128
141
  issueLinks: issueLinksWireSchema.optional(),
129
142
  priority: ticketPrioritySchema.optional(),
143
+ /** Only to clients sending `TICKET_COMPLETION_HEADER`. */
144
+ resolvedAt: z.string().datetime({ offset: true }).optional(),
145
+ /** Only to clients sending `TICKET_COMPLETION_HEADER`, beside `target`. */
146
+ targetTitle: z.string().optional(),
130
147
  })
131
148
  export const ticketListingWireSchema = z.strictObject({
132
149
  tickets: z.array(ticketWireSchema),
@@ -171,6 +188,12 @@ const criteriaSchema = z.strictObject({
171
188
  labels: z.array(z.string()).optional(),
172
189
  state: z.string().optional(),
173
190
  })
191
+ /** `list-page` criteria; released clients never send the completion keys. */
192
+ const pageCriteriaSchema = criteriaSchema.extend({
193
+ excludeLabels: z.array(z.string()).optional(),
194
+ since: z.string().datetime({ offset: true }).optional(),
195
+ until: z.string().datetime({ offset: true }).optional(),
196
+ })
174
197
  const idSchema = z.strictObject({ id: z.string().min(1) })
175
198
  const draftSchema = z.strictObject({
176
199
  kind: z.enum(['work', 'node']).optional(),
@@ -232,14 +255,20 @@ export const hostedTicketRequestSchemas = {
232
255
  'list-ready': envelope(criteriaSchema),
233
256
  'list-targeting': envelope(z.strictObject({ nodeId: z.string().min(1) })),
234
257
  'list-page': envelope(
235
- z.strictObject({
236
- criteria: criteriaSchema,
237
- page: z.strictObject({
238
- limit: z.number().int().nonnegative(),
239
- offset: z.number().int().nonnegative().optional(),
240
- order: z.enum(['oldest', 'newest']).optional(),
241
- }),
242
- }),
258
+ z
259
+ .strictObject({
260
+ criteria: pageCriteriaSchema,
261
+ page: z.strictObject({
262
+ limit: z.number().int().nonnegative(),
263
+ offset: z.number().int().nonnegative().optional(),
264
+ order: z.enum(['oldest', 'newest', 'completed']).optional(),
265
+ }),
266
+ })
267
+ .refine(
268
+ (value) =>
269
+ value.criteria.state !== undefined || !usesCompletionCriteria(value.criteria, value.page),
270
+ 'completion criteria require a state',
271
+ ),
243
272
  ),
244
273
  search: envelope(
245
274
  z.strictObject({
@@ -1,3 +1,4 @@
1
+ import { storeCallerHeaders } from '../../store/caller-attribution'
1
2
  import { normalizeTicket } from './tree'
2
3
  import { hostedRequestedIds } from './requested-id'
3
4
  import { TicketRevisionConflict } from './revision'
@@ -5,15 +6,20 @@ import { TicketIssueLinksUnsupported } from './issue-links'
5
6
  import { TicketPriorityUnsupported } from './priority'
6
7
  import { ticketLifecycle } from './lifecycle'
7
8
  import { TicketSearchCursorInvalid, TicketSearchUnsupported } from './search'
9
+ import {
10
+ TICKET_COMPLETION_SCAN_LIMIT,
11
+ TicketCompletionRangeTooBroad,
12
+ usesCompletionCriteria,
13
+ } from './completion'
8
14
  import type { TicketsConfig } from '../../config/schema'
9
15
  import type {
10
16
  DependencyState,
11
17
  Ticket,
12
18
  TicketCreateOptions,
13
19
  TicketDraft,
14
- TicketCriteria,
15
20
  TicketListing,
16
21
  TicketPage,
22
+ TicketPageCriteria,
17
23
  TicketPageListing,
18
24
  TicketPriority,
19
25
  TicketSearchPage,
@@ -61,6 +67,8 @@ import {
61
67
  TICKET_TARGETING_PROBE_NODE,
62
68
  TICKET_PAGING_HEADER,
63
69
  TICKET_PAGING_CAPABILITY,
70
+ TICKET_COMPLETION_HEADER,
71
+ TICKET_COMPLETION_CAPABILITY,
64
72
  TICKET_SEARCH_HEADER,
65
73
  TICKET_SEARCH_CAPABILITY,
66
74
  dependencyStatesWireSchema,
@@ -173,9 +181,11 @@ export class HostedTicketSource implements TicketSource {
173
181
  private readonly targeted = (nodeId: string) => this.targetedListing(nodeId)
174
182
  /** Unknown until a response settles it; see `noteCapabilities`. */
175
183
  private pagingSupport: boolean | undefined
176
- private readonly paged = (criteria: TicketCriteria, page: TicketPage) =>
184
+ private readonly paged = (criteria: TicketPageCriteria, page: TicketPage) =>
177
185
  this.pagedListing(criteria, page)
178
186
  /** Unknown until a response settles it; see `noteCapabilities`. */
187
+ private completionSupport: boolean | undefined
188
+ /** Unknown until a response settles it; see `noteCapabilities`. */
179
189
  private searchSupport: boolean | undefined
180
190
  private readonly searched = (query: TicketSearchQuery) => this.searchPage(query)
181
191
 
@@ -236,6 +246,12 @@ export class HostedTicketSource implements TicketSource {
236
246
  return this.pagingSupport === true ? this.paged : undefined
237
247
  }
238
248
 
249
+ /** True only once the service has advertised both `list-page` and its
250
+ * completion criteria; until then the operator filters `list-ready`. */
251
+ get completionPaging(): boolean {
252
+ return this.pagingSupport === true && this.completionSupport === true
253
+ }
254
+
239
255
  /** Present only once the service has positively advertised `search`; while
240
256
  * support is unknown or refused, callers refuse with `TicketSearchUnsupported`
241
257
  * before any request. There is never a listing fallback. */
@@ -273,6 +289,9 @@ export class HostedTicketSource implements TicketSource {
273
289
  if (response.headers.get(TICKET_SEARCH_HEADER) === TICKET_SEARCH_CAPABILITY)
274
290
  this.searchSupport = true
275
291
  else if (response.ok) this.searchSupport = false
292
+ if (response.headers.get(TICKET_COMPLETION_HEADER) === TICKET_COMPLETION_CAPABILITY)
293
+ this.completionSupport = true
294
+ else if (response.ok) this.completionSupport = false
276
295
  }
277
296
 
278
297
  private async send(
@@ -306,6 +325,8 @@ export class HostedTicketSource implements TicketSource {
306
325
  [TICKET_TARGETING_HEADER]: TICKET_TARGETING_CAPABILITY,
307
326
  [TICKET_PAGING_HEADER]: TICKET_PAGING_CAPABILITY,
308
327
  [TICKET_SEARCH_HEADER]: TICKET_SEARCH_CAPABILITY,
328
+ ...storeCallerHeaders(),
329
+ [TICKET_COMPLETION_HEADER]: TICKET_COMPLETION_CAPABILITY,
309
330
  [AUTOBUILD_VERSION_HEADER]: AUTOBUILD_VERSION,
310
331
  [REMOTE_STORE_PROTOCOL_VERSION_HEADER]: REMOTE_STORE_PROTOCOL_VERSION,
311
332
  },
@@ -410,6 +431,11 @@ export class HostedTicketSource implements TicketSource {
410
431
  ? body.error
411
432
  : 'ticket service cannot page this ticket source',
412
433
  )
434
+ if (body.code === 'completion-range-too-broad')
435
+ throw new TicketCompletionRangeTooBroad(
436
+ this.name,
437
+ typeof body.limit === 'number' ? body.limit : TICKET_COMPLETION_SCAN_LIMIT,
438
+ )
413
439
  if (body.code === 'search-unsupported') throw new TicketSearchUnsupported(this.name)
414
440
  if (body.code === 'search-cursor-invalid')
415
441
  throw new TicketSearchCursorInvalid(this.name, String(body.cursor ?? ''))
@@ -446,6 +472,7 @@ export class HostedTicketSource implements TicketSource {
446
472
  error instanceof TicketIssueLinksUnsupported ||
447
473
  error instanceof TicketPriorityUnsupported ||
448
474
  error instanceof HostedTicketPagingError ||
475
+ error instanceof TicketCompletionRangeTooBroad ||
449
476
  error instanceof TicketSearchUnsupported ||
450
477
  error instanceof TicketSearchCursorInvalid
451
478
  )
@@ -489,12 +516,19 @@ export class HostedTicketSource implements TicketSource {
489
516
  /** The service's native window: its order and total are canonical, so an
490
517
  * answer that contradicts the request fails rather than being repaired. */
491
518
  private async pagedListing(
492
- criteria: TicketCriteria,
519
+ criteria: TicketPageCriteria,
493
520
  page: TicketPage,
494
521
  ): Promise<TicketPageListing> {
495
522
  if (criteria.assignee !== undefined) {
496
523
  throw new Error('the hosted ticket source does not support an assignee gate')
497
524
  }
525
+ // A strict service predating completion criteria would refuse them, so
526
+ // they are sent only after a response echoed the completion capability.
527
+ if (usesCompletionCriteria(criteria, page) && this.completionSupport !== true)
528
+ throw new HostedTicketPagingError(
529
+ 'service-predates',
530
+ 'ticket service predates completion listing (since, until, excludeLabels, order completed); upgrade the service',
531
+ )
498
532
  const offset = page.offset ?? 0
499
533
  const listing = await this.request(
500
534
  'list-page',
@@ -502,6 +536,12 @@ export class HostedTicketSource implements TicketSource {
502
536
  criteria: {
503
537
  ...(criteria.labels !== undefined ? { labels: criteria.labels } : {}),
504
538
  ...(criteria.state !== undefined ? { state: criteria.state } : {}),
539
+ // Sent only when it excludes something, which the guard above
540
+ // has already negotiated; an empty list would trip an older
541
+ // service's strict request schema for no effect.
542
+ ...(criteria.excludeLabels?.length ? { excludeLabels: criteria.excludeLabels } : {}),
543
+ ...(criteria.since !== undefined ? { since: criteria.since } : {}),
544
+ ...(criteria.until !== undefined ? { until: criteria.until } : {}),
505
545
  },
506
546
  page: {
507
547
  limit: page.limit,
@@ -15,11 +15,21 @@ export function normalizeTicket(
15
15
  priority = true,
16
16
  assignees = true,
17
17
  ): Ticket {
18
- const { target, issueLinks: links, priority: level, assignees: assigned, ...rest } = ticket
18
+ const {
19
+ target,
20
+ targetTitle,
21
+ resolvedAt,
22
+ issueLinks: links,
23
+ priority: level,
24
+ assignees: assigned,
25
+ ...rest
26
+ } = ticket
19
27
  return {
20
28
  ...rest,
21
29
  kind: supported ? (ticket.kind ?? 'work') : 'work',
22
30
  ...(supported && target !== undefined ? { target } : {}),
31
+ ...(supported && target !== undefined && targetTitle !== undefined ? { targetTitle } : {}),
32
+ ...(ticket.resolved && resolvedAt !== undefined ? { resolvedAt } : {}),
23
33
  ...(issueLinks && links !== undefined ? { issueLinks: links } : {}),
24
34
  // Normal is the absence of the field, so strict wire schemas never see it.
25
35
  ...(priority && ticketPriority({ priority: level }) !== 'normal' ? { priority: level } : {}),
@@ -69,6 +69,9 @@ export interface Ticket {
69
69
  kind?: TicketKind
70
70
  /** Canonical source-local node ticket id; absent means the baseBranch root. */
71
71
  target?: string
72
+ /** The target node's title when the source answered it in the same read. A
73
+ * listing-time fact, not part of `revision`; present only alongside `target`. */
74
+ targetTitle?: string
72
75
  /** Opaque source version of title, body, labels, state and blockers. */
73
76
  revision: string
74
77
  /** Complete history oldest first when exposed by this read. Absent means
@@ -85,6 +88,10 @@ export interface Ticket {
85
88
  state?: string
86
89
  /** Native completion fact, identical to DependencyState.resolved. */
87
90
  resolved: boolean
91
+ /** ISO-8601 time the ticket entered its completed state, when the source
92
+ * knows it. A listing-time fact, not part of `revision`; present only when
93
+ * `resolved`. */
94
+ resolvedAt?: string
88
95
  labels: string[]
89
96
  /** Listing-time source fact that all declared blockers are resolved. Only
90
97
  * true permits skipping dependency reads; consumers fall back when absent. */
@@ -129,11 +136,25 @@ export interface TicketCriteria {
129
136
  assignee?: string
130
137
  }
131
138
 
139
+ /** `listPage` criteria: the dispatch criteria plus completion filters, which
140
+ * a source honours only when it declares `completionPaging`. */
141
+ export interface TicketPageCriteria extends TicketCriteria {
142
+ /** Omit every ticket carrying any of these labels. */
143
+ excludeLabels?: string[]
144
+ /** Completion range, half-open: `since <= resolvedAt < until`, both
145
+ * ISO-8601. A ticket without `resolvedAt` never matches. Completion criteria
146
+ * require `state`. A native source may refuse a range too broad for its
147
+ * per-request cap with `TicketCompletionRangeTooBroad`. */
148
+ since?: string
149
+ until?: string
150
+ }
151
+
132
152
  export interface TicketPage {
133
153
  limit: number
134
154
  offset?: number
135
- /** Dispatch order or newest filed first; see `TicketSource.listPage`. */
136
- order?: 'oldest' | 'newest'
155
+ /** Dispatch order, newest filed first, or most recently completed first;
156
+ * see `TicketSource.listPage`. */
157
+ order?: 'oldest' | 'newest' | 'completed'
137
158
  }
138
159
 
139
160
  export interface TicketPageListing extends TicketListing {
@@ -444,8 +465,15 @@ export interface TicketSource {
444
465
  * Arguments are nonnegative integers; zero limit returns no tickets with the
445
466
  * full matching total. Diagnostics
446
467
  * and failures match listReady; a failure must not trigger a full-read fallback.
447
- * listReady and listAll remain exhaustive. */
448
- listPage?(criteria: TicketCriteria, page: TicketPage): Promise<TicketPageListing>
468
+ * listReady and listAll remain exhaustive. `completed` (only sent to
469
+ * sources declaring `completionPaging`) puts tickets with `resolvedAt`
470
+ * first, most recent first, ties newest filed first; the rest follow newest
471
+ * filed first. */
472
+ listPage?(criteria: TicketPageCriteria, page: TicketPage): Promise<TicketPageListing>
473
+ /** Opt in only when `listPage` honours `excludeLabels`, `since`, `until`
474
+ * and order `completed`. Callers send them only to sources declaring it;
475
+ * the rest are filtered over the exhaustive `listReady` listing. */
476
+ readonly completionPaging?: boolean
449
477
  /** Optional text search over every lifecycle state (or `query.state`).
450
478
  * A ticket matches when every whitespace-separated term of `query.text`
451
479
  * occurs, case-insensitively, in its title or body (each term may hit either
@@ -677,6 +705,14 @@ export interface WorkspaceRecovery {
677
705
  reap(handle: WorkspaceHandle): Promise<WorkspaceReapOutcome>
678
706
  }
679
707
 
708
+ /** The provisioning stage a provider is about to run, such as
709
+ * `{ stage: 'system provisioning step', step: 'browser-deps' }`. Process-local
710
+ * teardown diagnostics only; never persisted as state. */
711
+ export interface WorkspaceProvisionProgress {
712
+ stage: string
713
+ step?: string
714
+ }
715
+
680
716
  export interface WorkspaceProvider {
681
717
  /** Local adapters may provide the same boundary capability without becoming
682
718
  * a remote-publication provider. */
@@ -764,6 +800,13 @@ export interface WorkspaceProvider {
764
800
  * `baseBranch` and keeps the old tip under a private ref (#1261).
765
801
  * Providers that cannot honor it rely on claim-time deduplication. */
766
802
  fresh?: { owner: string }
803
+ /** The invocation's teardown token: abort in-flight provisioning
804
+ * promptly. The dispatcher records the abandonment; the provider must
805
+ * not record a failure. Providers that ignore it may still complete. */
806
+ signal?: AbortSignal
807
+ /** Report the stage about to run, for teardown diagnostics; must never
808
+ * block or throw into provisioning. */
809
+ onProgress?: (progress: WorkspaceProvisionProgress) => void
767
810
  }): Promise<WorkspaceProvisionResult>
768
811
  release(handle: WorkspaceHandle): Promise<void>
769
812
  }
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Pure formatting for failed Vercel sandbox guest commands (#1399): the
3
+ * redacted argv, the stage, and bounded stderr/stdout tails an operator needs
4
+ * to see why a command failed without opening the sandbox. No SDK import, no
5
+ * IO. The first line keeps the `sandbox command <cmd> exited <n>` prefix
6
+ * operators already grep for.
7
+ */
8
+
9
+ export const REDACTED = '[REDACTED]'
10
+
11
+ const SECRET_KEY = /(token|password|passwd|secret|credential|api[_-]?key|auth)/i
12
+ /** A credential-bearing flag name, optionally prefixed (`--github-token`). */
13
+ const SECRET_FLAG_NAME =
14
+ '--?(?:[A-Za-z0-9]+[-_])*(?:token|password|passwd|secret|api[-_]?key|auth|credentials?)'
15
+ const SECRET_FLAG = new RegExp(`^${SECRET_FLAG_NAME}$`, 'i')
16
+ /** One value as a shell command line spells it: double- or single-quoted
17
+ * (spaces included), or a bare word. */
18
+ const VALUE = String.raw`(?:"(?:[^"\\]|\\.)*"|'[^']*'|[^\s"'&;|]+)`
19
+
20
+ /** Redact explicit secret values plus the credential shapes a command line
21
+ * or its output commonly carries. Works on whole shell command strings too
22
+ * (`sh -c "installer --password x"`), so flag and quoted values inside one
23
+ * argv element are covered. */
24
+ export function redactSandboxText(text: string, secrets: readonly string[] = []): string {
25
+ let redacted = text
26
+ for (const secret of [...secrets]
27
+ .filter((value) => value.trim() !== '')
28
+ .sort((left, right) => right.length - left.length)) {
29
+ redacted = redacted.split(secret).join(REDACTED)
30
+ }
31
+ return (
32
+ redacted
33
+ // URL userinfo: scheme://user:pass@host
34
+ .replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+@/gi, `$1${REDACTED}@`)
35
+ // Authorization headers, including git's http[.<url>].extraheader values.
36
+ .replace(
37
+ new RegExp(`(authorization\\s*[:=]\\s*)(?:(basic|bearer)\\s+)?${VALUE}`, 'gi'),
38
+ (_match, head: string, scheme: string | undefined) =>
39
+ scheme === undefined ? `${head}${REDACTED}` : `${head}${scheme} ${REDACTED}`,
40
+ )
41
+ .replace(/\b(bearer|basic)\s+(?!\[REDACTED\])[A-Za-z0-9._~+/=-]+/gi, `$1 ${REDACTED}`)
42
+ // A credential flag followed by its value, inside one command string.
43
+ .replace(
44
+ new RegExp(`(^|[\\s"'])(${SECRET_FLAG_NAME})(\\s+|=)${VALUE}`, 'gi'),
45
+ (_match, lead: string, flag: string, separator: string) =>
46
+ `${lead}${flag}${separator}${REDACTED}`,
47
+ )
48
+ // key=value where the key names a credential; quoted values whole.
49
+ .replace(
50
+ new RegExp(`([A-Za-z0-9_.-]*)=(${VALUE})`, 'g'),
51
+ (match, key: string, value: string) =>
52
+ SECRET_KEY.test(key) && value !== REDACTED ? `${key}=${REDACTED}` : match,
53
+ )
54
+ )
55
+ }
56
+
57
+ /** Redact each argv element, plus the value following a credential flag. */
58
+ export function redactArgv(argv: readonly string[], secrets: readonly string[] = []): string[] {
59
+ return argv.map((arg, index) =>
60
+ index > 0 && SECRET_FLAG.test(argv[index - 1]!) ? REDACTED : redactSandboxText(arg, secrets),
61
+ )
62
+ }
63
+
64
+ /** The trailing `maxLines` lines of `text`, at most `maxChars` characters,
65
+ * marked when truncated; `(empty)` for whitespace-only output. */
66
+ export function outputTail(
67
+ text: string,
68
+ opts: { maxLines?: number; maxChars?: number } = {},
69
+ ): string {
70
+ const maxLines = opts.maxLines ?? 20
71
+ const maxChars = opts.maxChars ?? 2_000
72
+ const trimmed = text.replace(/\s+$/, '')
73
+ if (trimmed.trim() === '') return '(empty)'
74
+ const lines = trimmed.split(/\r?\n/)
75
+ let kept = lines.slice(-maxLines).join('\n')
76
+ const omitted = lines.length - Math.min(lines.length, maxLines)
77
+ let charsCut = false
78
+ if (kept.length > maxChars) {
79
+ kept = kept.slice(kept.length - maxChars)
80
+ charsCut = true
81
+ }
82
+ if (omitted > 0) return `…(${omitted} earlier lines omitted)\n${charsCut ? '…' : ''}${kept}`
83
+ return charsCut ? `…${kept}` : kept
84
+ }
85
+
86
+ export type SandboxCommandOutcome =
87
+ | { kind: 'exit'; code: number }
88
+ | { kind: 'no-status' }
89
+ | { kind: 'timeout'; timeoutMs: number; elapsedMs: number }
90
+ | { kind: 'error'; message: string }
91
+
92
+ export interface SandboxCommandFailure {
93
+ cmd: string
94
+ args?: readonly string[]
95
+ cwd?: string
96
+ stage?: string
97
+ secrets?: readonly string[]
98
+ outcome: SandboxCommandOutcome
99
+ stdout?: string
100
+ stderr?: string
101
+ /** Why the output could not be read; replaces both tails. */
102
+ outputUnavailable?: string
103
+ }
104
+
105
+ const seconds = (ms: number): string => `${Math.max(0, Math.round(ms / 1000))}s`
106
+
107
+ function quoteArg(arg: string): string {
108
+ return arg === '' || /\s|"/.test(arg) ? JSON.stringify(arg) : arg
109
+ }
110
+
111
+ /** The multi-line diagnostic for one failed sandbox command. A timeout header
112
+ * says `timeout` (and avoids provider-limit vocabulary) so infrastructure
113
+ * classification records it as one. */
114
+ export function formatSandboxCommandFailure(input: SandboxCommandFailure): string {
115
+ const secrets = input.secrets ?? []
116
+ const outcome = input.outcome
117
+ const header =
118
+ outcome.kind === 'exit'
119
+ ? `exited ${outcome.code}`
120
+ : outcome.kind === 'no-status'
121
+ ? 'did not return an exit status'
122
+ : outcome.kind === 'timeout'
123
+ ? `exceeded its ${seconds(outcome.timeoutMs)} provisioning timeout after ${seconds(outcome.elapsedMs)}`
124
+ : `failed: ${redactSandboxText(outcome.message, secrets)}`
125
+ const lines = [`sandbox command ${input.cmd} ${header}`]
126
+ if (input.stage !== undefined) lines.push(`stage: ${input.stage}`)
127
+ lines.push(
128
+ `argv: ${redactArgv([input.cmd, ...(input.args ?? [])], secrets)
129
+ .map(quoteArg)
130
+ .join(' ')}`,
131
+ )
132
+ if (input.cwd !== undefined) lines.push(`cwd: ${input.cwd}`)
133
+ if (input.outputUnavailable !== undefined) {
134
+ lines.push(`output: unavailable (${redactSandboxText(input.outputUnavailable, secrets)})`)
135
+ } else {
136
+ lines.push(
137
+ 'stderr (tail):',
138
+ outputTail(redactSandboxText(input.stderr ?? '', secrets)),
139
+ 'stdout (tail):',
140
+ outputTail(redactSandboxText(input.stdout ?? '', secrets)),
141
+ )
142
+ }
143
+ return lines.join('\n')
144
+ }