@defrex/autobuild 1.11.1 → 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 (213) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +601 -203
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +32 -2
  5. package/docs/architecture.md +188 -57
  6. package/docs/assets/headline-wide.png +0 -0
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +120 -23
  9. package/docs/dispatcher.md +19 -8
  10. package/docs/integration-overview.md +1 -1
  11. package/docs/integration-tree.md +33 -18
  12. package/docs/merge-policy.md +7 -2
  13. package/docs/operating.md +5 -3
  14. package/docs/operator-api.md +48 -25
  15. package/docs/operator-surfaces.md +39 -3
  16. package/docs/optimization-nodes.md +10 -8
  17. package/docs/plugin-authoring.md +46 -18
  18. package/docs/remote-store-protocol.md +51 -12
  19. package/docs/remote-ticket-protocol.md +85 -38
  20. package/docs/restacking.md +48 -3
  21. package/docs/setup.md +2 -1
  22. package/docs/ticket-migration.md +2 -2
  23. package/docs/ticket-sources.md +23 -8
  24. package/docs/tickets.md +4 -4
  25. package/docs/troubleshooting.md +17 -2
  26. package/docs/verification.md +3 -1
  27. package/package.json +3 -3
  28. package/packages/core/src/cli/ambient-errors.ts +17 -0
  29. package/packages/core/src/cli/bounded-io.ts +174 -0
  30. package/packages/core/src/cli/build-control.ts +72 -6
  31. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  32. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  33. package/packages/core/src/cli/dashboard/model.ts +93 -29
  34. package/packages/core/src/cli/dashboard/poll.ts +231 -34
  35. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  36. package/packages/core/src/cli/dashboard/render.ts +14 -37
  37. package/packages/core/src/cli/dashboard/row-text.ts +26 -8
  38. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  39. package/packages/core/src/cli/dashboard/vocabulary.ts +165 -20
  40. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  41. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  42. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  43. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  44. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  45. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  46. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  47. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  48. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  49. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  50. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  51. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  52. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  53. package/packages/core/src/cli/dispatch.ts +595 -149
  54. package/packages/core/src/cli/env.ts +2 -15
  55. package/packages/core/src/cli/help.ts +43 -28
  56. package/packages/core/src/cli/main.ts +11 -7
  57. package/packages/core/src/cli/production-store.ts +102 -0
  58. package/packages/core/src/cli/publication-settlement.ts +4 -0
  59. package/packages/core/src/cli/remote-poll.ts +22 -5
  60. package/packages/core/src/cli/repo-state.ts +2 -3
  61. package/packages/core/src/cli/repository-status.ts +44 -28
  62. package/packages/core/src/cli/sessionless-store.ts +26 -0
  63. package/packages/core/src/cli/status.ts +188 -47
  64. package/packages/core/src/cli/store-opening.ts +26 -57
  65. package/packages/core/src/cli/store-ref.ts +6 -1
  66. package/packages/core/src/cli/ticket-start.ts +3 -3
  67. package/packages/core/src/cli/ticket.ts +12 -11
  68. package/packages/core/src/cli/wait.ts +8 -28
  69. package/packages/core/src/cli/watch.ts +113 -50
  70. package/packages/core/src/config/reference-metadata.ts +7 -1
  71. package/packages/core/src/config/reference.ts +5 -2
  72. package/packages/core/src/config/schema.ts +51 -16
  73. package/packages/core/src/distribution-packaging.ts +156 -18
  74. package/packages/core/src/events/catalog-identity.ts +28 -0
  75. package/packages/core/src/events/catalog.ts +3 -9
  76. package/packages/core/src/events/compatibility.ts +2 -30
  77. package/packages/core/src/events/payloads.ts +85 -14
  78. package/packages/core/src/events/policy.ts +3 -0
  79. package/packages/core/src/events/repository.ts +15 -4
  80. package/packages/core/src/events/sessions.ts +1 -1
  81. package/packages/core/src/events/validation-error.ts +12 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +36 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  92. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  93. package/packages/core/src/kernel/capacity-build.ts +21 -0
  94. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  95. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +578 -235
  97. package/packages/core/src/kernel/done-escalations.ts +269 -0
  98. package/packages/core/src/kernel/engine.ts +30 -17
  99. package/packages/core/src/kernel/integration-landing.ts +24 -4
  100. package/packages/core/src/kernel/integration-stack.ts +39 -0
  101. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  102. package/packages/core/src/kernel/log-index-value.ts +3 -0
  103. package/packages/core/src/kernel/log-index.ts +41 -2
  104. package/packages/core/src/kernel/measurement.ts +24 -0
  105. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  106. package/packages/core/src/kernel/read-facts.ts +8 -370
  107. package/packages/core/src/kernel/reducer-registry.ts +43 -125
  108. package/packages/core/src/kernel/reducer-revisions.ts +18 -0
  109. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  110. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  111. package/packages/core/src/kernel/reducer.ts +84 -16
  112. package/packages/core/src/kernel/reopen-state.ts +10 -0
  113. package/packages/core/src/kernel/repository-attention.ts +14 -5
  114. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  115. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  116. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  117. package/packages/core/src/kernel/verify-stages.ts +46 -7
  118. package/packages/core/src/operator/attention.ts +28 -3
  119. package/packages/core/src/operator/done-escalations.ts +38 -0
  120. package/packages/core/src/operator/presentation.ts +14 -1
  121. package/packages/core/src/operator/protocol.ts +8 -5
  122. package/packages/core/src/operator/query.ts +72 -57
  123. package/packages/core/src/operator/registry.ts +19 -15
  124. package/packages/core/src/operator/ticket-start.ts +8 -7
  125. package/packages/core/src/operator/tickets.ts +28 -9
  126. package/packages/core/src/plugin-sdk/index.ts +10 -0
  127. package/packages/core/src/plugins/manifest.ts +14 -1
  128. package/packages/core/src/ports/forge/create.ts +8 -0
  129. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  130. package/packages/core/src/ports/forge/github.ts +3 -0
  131. package/packages/core/src/ports/tickets/contract.ts +147 -76
  132. package/packages/core/src/ports/tickets/create.ts +47 -7
  133. package/packages/core/src/ports/tickets/fake.ts +8 -4
  134. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  135. package/packages/core/src/ports/tickets/file.ts +7 -3
  136. package/packages/core/src/ports/tickets/github.ts +1 -0
  137. package/packages/core/src/ports/tickets/grants.ts +11 -3
  138. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  139. package/packages/core/src/ports/tickets/linear.ts +28 -9
  140. package/packages/core/src/ports/tickets/migration.ts +4 -4
  141. package/packages/core/src/ports/tickets/operations.ts +4 -2
  142. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  143. package/packages/core/src/ports/tickets/priority.ts +127 -21
  144. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  145. package/packages/core/src/ports/tickets/remote.ts +104 -11
  146. package/packages/core/src/ports/tickets/revision.ts +5 -3
  147. package/packages/core/src/ports/tickets/search.ts +9 -0
  148. package/packages/core/src/ports/tickets/tree.ts +8 -6
  149. package/packages/core/src/ports/types.ts +30 -15
  150. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  151. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  152. package/packages/core/src/ports/workspace/create.ts +16 -3
  153. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  154. package/packages/core/src/ports/workspace/fake.ts +15 -3
  155. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  156. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  157. package/packages/core/src/processes/build-execution-state.ts +4 -0
  158. package/packages/core/src/processes/build-runner.ts +14 -1
  159. package/packages/core/src/processes/dispatcher.ts +777 -288
  160. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  161. package/packages/core/src/processes/execution-settlement.ts +1 -0
  162. package/packages/core/src/processes/harvest-runner.ts +12 -7
  163. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  164. package/packages/core/src/processes/invocation-budget.ts +176 -0
  165. package/packages/core/src/processes/publication-loss.ts +38 -3
  166. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  167. package/packages/core/src/store/contract.ts +81 -3
  168. package/packages/core/src/store/event-reads.ts +30 -1
  169. package/packages/core/src/store/local/capabilities.ts +115 -0
  170. package/packages/core/src/store/local/store.ts +86 -56
  171. package/packages/core/src/store/reduced-reads.ts +32 -1
  172. package/packages/core/src/store/reducer-value-read.ts +235 -0
  173. package/packages/core/src/store/reducer-value-shapes.json +6722 -6475
  174. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  175. package/packages/core/src/store/reducer-values.ts +36 -204
  176. package/packages/core/src/store/remote/client.ts +169 -29
  177. package/packages/core/src/store/remote/compatibility.ts +113 -56
  178. package/packages/core/src/store/remote/credentials.ts +4 -1
  179. package/packages/core/src/store/remote/protocol.ts +3 -0
  180. package/packages/core/src/store/remote/released-clients.json +22 -0
  181. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  182. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  183. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  184. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  185. package/packages/core/src/store/remote/retry.ts +406 -0
  186. package/packages/core/src/store/rollup-lease.ts +41 -0
  187. package/packages/core/src/store/rollups.ts +7 -38
  188. package/packages/core/src/store/snapshots.ts +1 -1
  189. package/packages/core/src/testing/dispatch-read-budget.ts +409 -14
  190. package/packages/core/src/testing/import-graph.ts +78 -0
  191. package/packages/core/src/testing/index.ts +2 -0
  192. package/packages/core/src/testing/invocation-budget.ts +42 -0
  193. package/packages/core/src/testing/reduced-read-budget.ts +602 -40
  194. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  195. package/packages/core/src/testing/slot-agreement.ts +52 -0
  196. package/packages/core/src/web/assets/app.js +5 -5
  197. package/packages/core/src/web/overview-source.ts +19 -6
  198. package/skills/guide/SKILL.md +245 -103
  199. package/skills/guide/references/integration-tree.md +33 -18
  200. package/skills/guide/references/merge-policy.md +7 -2
  201. package/skills/guide/references/operator-api.md +48 -25
  202. package/skills/guide/references/optimization-nodes.md +10 -8
  203. package/skills/guide/references/plugin-authoring.md +46 -18
  204. package/skills/guide/references/remote-store-protocol.md +51 -12
  205. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  206. package/skills/guide/references/restacking.md +48 -3
  207. package/skills/guide/references/setup.md +2 -1
  208. package/skills/guide/references/ticket-migration.md +2 -2
  209. package/skills/operate/SKILL.md +114 -65
  210. package/skills/plan/SKILL.md +4 -3
  211. package/skills/spec/SKILL.md +9 -5
  212. package/skills/tickets/SKILL.md +25 -17
  213. package/templates/hosted-service/package.json +2 -2
@@ -76,23 +76,31 @@ function stepSection<T, C, S = string[]>(
76
76
  label: string,
77
77
  stepsSchema: z.ZodType<S>,
78
78
  tableSchema: z.ZodType<T>,
79
- compose: (steps: S, stepConfigs: Record<string, T>, afterReconcile: boolean) => C,
80
- allowAfterReconcile = false,
79
+ compose: (steps: S, stepConfigs: Record<string, T>, policies: VerifyPolicies) => C,
80
+ allowVerifyPolicies = false,
81
81
  ) {
82
82
  const afterReconcileSchema = z.boolean().default(true)
83
+ const afterCleanRestackSchema = z.boolean().optional()
83
84
  const schema = z
84
85
  .unknown()
85
86
  .transform((input, ctx): C => {
86
87
  const stepConfigs: Record<string, T> = Object.create(null)
87
88
  let steps = stepsSchema.parse(undefined)
88
- let afterReconcile = afterReconcileSchema.parse(undefined)
89
+ const policies: VerifyPolicies = { afterReconcile: afterReconcileSchema.parse(undefined) }
89
90
  for (const [key, raw] of ownEntries(input, label, ctx)) {
90
- if (key === 'afterReconcile' && allowAfterReconcile) {
91
+ if (key === 'afterReconcile' && allowVerifyPolicies) {
91
92
  const parsed = afterReconcileSchema.safeParse(raw)
92
- if (parsed.success) afterReconcile = parsed.data
93
+ if (parsed.success) policies.afterReconcile = parsed.data
93
94
  else forwardIssues(parsed.error.issues, ctx, [key])
94
95
  continue
95
96
  }
97
+ if (key === 'afterCleanRestack' && allowVerifyPolicies) {
98
+ const parsed = afterCleanRestackSchema.safeParse(raw)
99
+ if (parsed.success) {
100
+ if (parsed.data !== undefined) policies.afterCleanRestack = parsed.data
101
+ } else forwardIssues(parsed.error.issues, ctx, [key])
102
+ continue
103
+ }
96
104
  if (key === 'steps') {
97
105
  const parsed = stepsSchema.safeParse(raw)
98
106
  if (parsed.success) steps = parsed.data
@@ -102,18 +110,18 @@ function stepSection<T, C, S = string[]>(
102
110
  const table = parseEntry(tableSchema, raw, key, ctx)
103
111
  if (table.ok) defineEntry(stepConfigs, key, table.value)
104
112
  }
105
- return compose(steps, stepConfigs, afterReconcile)
113
+ return compose(steps, stepConfigs, policies)
106
114
  })
107
115
  .prefault({})
108
116
  documentSchema(stepsSchema, {
109
- ...(allowAfterReconcile
117
+ ...(allowVerifyPolicies
110
118
  ? {
111
119
  constraints:
112
120
  'Each name is nonempty; each grouped stage contains at least one nonempty name. Names must be unique within and across stages.',
113
121
  }
114
122
  : {}),
115
123
  description:
116
- (allowAfterReconcile
124
+ (allowVerifyPolicies
117
125
  ? 'Ordered verify stages: a name is a singleton stage; a nonempty array runs its members concurrently. Names must be unique within and across stages. '
118
126
  : 'Ordered names of the configured step tables. ') +
119
127
  'Names contain only ASCII letters, digits, ., _ and -, excluding "." and "..". Every listed step must have a table and every table must be listed.',
@@ -126,16 +134,30 @@ function stepSection<T, C, S = string[]>(
126
134
  description:
127
135
  'Whether verification runs after reconciliation. A step override takes precedence.',
128
136
  })
137
+ documentSchema(afterCleanRestackSchema, {
138
+ default: 'false (omission is preserved)',
139
+ description:
140
+ 'Whether verification re-runs on the restacked head after a clean awaiting-landing restack of a root-targeting leaf, before it lands. A step override takes precedence.',
141
+ })
129
142
  return documentSchema(schema, {
130
143
  structure: {
131
144
  kind: 'steps',
132
145
  steps: stepsSchema,
133
146
  table: tableSchema,
134
- ...(allowAfterReconcile ? { afterReconcile: afterReconcileSchema } : {}),
147
+ ...(allowVerifyPolicies
148
+ ? { afterReconcile: afterReconcileSchema, afterCleanRestack: afterCleanRestackSchema }
149
+ : {}),
135
150
  },
136
151
  })
137
152
  }
138
153
 
154
+ /** Repository-wide verify policy scalars parsed beside `steps`. */
155
+ interface VerifyPolicies {
156
+ afterReconcile: boolean
157
+ /** Present only when the source sets it, preserving configuration identity. */
158
+ afterCleanRestack?: boolean
159
+ }
160
+
139
161
  // ── [pr] / [pr.imageHost] ────────────────────────────────────────────────────
140
162
 
141
163
  /** Optional public GitHub release used for review-window image copies.
@@ -220,6 +242,8 @@ export const vercelSandboxConfigSchema = z
220
242
  timeoutSeconds: z.number().int().min(60).max(86_400),
221
243
  /** Deadline for each provider acknowledgement; distinct from VM lifetime. */
222
244
  operationTimeoutMs: z.number().int().min(1_000).max(300_000).default(30_000),
245
+ /** Budget for one stopped-sandbox recovery: explicit resume plus guest git. */
246
+ recoveryTimeoutMs: z.number().int().min(1_000).max(600_000).default(120_000),
223
247
  /** Billing safety net: snapshots created for this environment expire after
224
248
  * this duration instead of the provider's 30-day default. Absent means the
225
249
  * provider default. */
@@ -308,6 +332,8 @@ documentFields(vercelSandboxConfigSchema, {
308
332
  'VM/session lifetime in seconds and abrupt-orphan bound. Provider plan limits also apply.',
309
333
  operationTimeoutMs:
310
334
  'Deadline in milliseconds for each provider acknowledgement, independent of session lifetime.',
335
+ recoveryTimeoutMs:
336
+ 'Budget in milliseconds for one stopped-sandbox recovery: an explicit cold resume plus the guest git work that follows it, including a push. Any invocation deadline bounds it further. Separate from operationTimeoutMs.',
311
337
  snapshotExpirationSeconds:
312
338
  'Snapshot expiration in seconds. Omission uses the provider expiration policy.',
313
339
  region: 'Primary region; omission uses the provider region selection.',
@@ -334,9 +360,10 @@ type NormalizedVercelSandboxConfig = z.infer<typeof vercelSandboxConfigSchema>
334
360
  * production config always materializes operationTimeoutMs. */
335
361
  export type VercelSandboxConfig = Omit<
336
362
  NormalizedVercelSandboxConfig,
337
- 'operationTimeoutMs' | 'provisioning' | 'runtimeProvisioning'
363
+ 'operationTimeoutMs' | 'recoveryTimeoutMs' | 'provisioning' | 'runtimeProvisioning'
338
364
  > & {
339
365
  operationTimeoutMs?: number
366
+ recoveryTimeoutMs?: number
340
367
  /** Optional only for source compatibility with direct adapter construction;
341
368
  * schema-loaded repository configuration always materializes this list. */
342
369
  provisioning?: VercelProvisioningStep[]
@@ -486,6 +513,7 @@ const verifyApplicabilityShape = {
486
513
  default: 'false (omission is preserved)',
487
514
  }),
488
515
  afterReconcile: z.boolean().optional(),
516
+ afterCleanRestack: z.boolean().optional(),
489
517
  /** Any-match positive path selectors; absent means unconditional. */
490
518
  paths: z
491
519
  .array(pathSelectorSchema)
@@ -510,6 +538,8 @@ documentFields(verifyCheckStepSchema, {
510
538
  'Name of an existing command in [commands]; required for check steps and forbidden for agent steps.',
511
539
  afterReconcile:
512
540
  'Step override wins over `[verify].afterReconcile`; false skips this step after reconciliation only.',
541
+ afterCleanRestack:
542
+ 'Step override wins over `[verify].afterCleanRestack`; true re-runs this step on the restacked head after a clean awaiting-landing restack of a root-targeting leaf, false records it skipped.',
513
543
  failFast: 'Cancel unfinished members of this stage when this step fails. Defaults to false.',
514
544
  paths: 'Apply only when at least one changed path matches. Available to both variants.',
515
545
  always:
@@ -528,6 +558,8 @@ documentFields(verifyAgentStepSchema, {
528
558
  skill: 'Exact installed skill name; required for agent steps and forbidden for check steps.',
529
559
  afterReconcile:
530
560
  'Step override wins over `[verify].afterReconcile`; false skips this step after reconciliation only.',
561
+ afterCleanRestack:
562
+ 'Step override wins over `[verify].afterCleanRestack`; true re-runs this step on the restacked head after a clean awaiting-landing restack of a root-targeting leaf, false records it skipped.',
531
563
  failFast: 'Cancel unfinished members of this stage when this step fails. Defaults to false.',
532
564
  paths: 'Apply only when at least one changed path matches. Available to both variants.',
533
565
  always:
@@ -542,6 +574,8 @@ export type VerifyStepConfig = z.infer<typeof verifyStepConfigSchema>
542
574
 
543
575
  export interface VerifyConfig {
544
576
  afterReconcile: boolean
577
+ /** Repository default for clean-restack re-verification; absent means false. */
578
+ afterCleanRestack?: boolean
545
579
  /** Step order — each entry names a `verify:<step>` phase (§15.2.1). */
546
580
  steps: string[]
547
581
  /** Present only when the source contains grouped entries. */
@@ -551,7 +585,7 @@ export interface VerifyConfig {
551
585
  }
552
586
 
553
587
  /**
554
- * [verify] mixes known scalars (`steps`, `afterReconcile`) with per-step
588
+ * [verify] mixes known scalars (`steps`, `afterReconcile`, `afterCleanRestack`) with per-step
555
589
  * subtables, so it cannot be a strictObject; every other key is
556
590
  * validated as a step table — nothing passes through loosely, and no step name
557
591
  * is lost to the prototype chain (see `stepSection`).
@@ -567,10 +601,11 @@ export const verifySectionSchema = stepSection(
567
601
  )
568
602
  .default([]),
569
603
  verifyStepConfigSchema,
570
- (entries, stepConfigs, afterReconcile): VerifyConfig => ({
604
+ (entries, stepConfigs, { afterReconcile, afterCleanRestack }): VerifyConfig => ({
571
605
  steps: entries.flat(),
572
606
  stepConfigs,
573
607
  afterReconcile,
608
+ ...(afterCleanRestack !== undefined ? { afterCleanRestack } : {}),
574
609
  ...(entries.some(Array.isArray)
575
610
  ? {
576
611
  stages: entries.map((entry) => (typeof entry === 'string' ? [entry] : entry)),
@@ -808,7 +843,7 @@ export const policySchema = z.strictObject({
808
843
  nodeIdlePollSeconds: z.number().int().positive().default(120),
809
844
  janitorBackoffMaxSeconds: z.number().int().positive().default(300),
810
845
  harvestMaxDrift: z.number().int().nonnegative().default(3),
811
- /** Open unmerged root PRs at which normal-priority intake pauses; unset disables backpressure. */
846
+ /** Open unmerged root PRs at which high, normal and low intake pauses; unset disables backpressure. */
812
847
  maxOpenPrs: z.number().int().positive().optional(),
813
848
  /** Open unmerged root PRs at or below which paused intake resumes; defaults to `maxOpenPrs - 1`. */
814
849
  resumeOpenPrs: z.number().int().nonnegative().optional(),
@@ -847,9 +882,9 @@ documentFields(policySchema, {
847
882
  harvestMaxDrift:
848
883
  'Other builds merged after the oldest unclaimed observation needed to start a run; `0` disables drift.',
849
884
  maxOpenPrs:
850
- 'Open unmerged root build PRs (leaves and integration nodes) at which the dispatcher stops ordinary ready-queue claims of `normal`-priority tickets. In-flight work, reconciles, landings, `urgent` claims and every `ab start` (`tickets.start`) request continue, subject to capacity and repository pause. Unset disables open-PR backpressure.',
885
+ 'Open unmerged root build PRs (leaves and integration nodes) at which the dispatcher stops ordinary ready-queue claims of `high`, `normal` and `low` tickets. In-flight work, reconciles, landings, `urgent` claims and every `ab start` (`tickets.start`) request continue, subject to capacity and repository pause. Unset disables open-PR backpressure.',
851
886
  resumeOpenPrs:
852
- 'Open root PR count at or below which paused `normal` intake resumes; defaults to `maxOpenPrs - 1`. Reaching `maxOpenPrs` takes precedence, so when this equals `maxOpenPrs` intake stays paused at that count and resumes once the count falls below `maxOpenPrs`. Inert without `maxOpenPrs`.',
887
+ 'Open root PR count at or below which paused high, normal and low intake resumes; defaults to `maxOpenPrs - 1`. Reaching `maxOpenPrs` takes precedence, so when this equals `maxOpenPrs` intake stays paused at that count and resumes once the count falls below `maxOpenPrs`. Inert without `maxOpenPrs`.',
853
888
  excludeHeldOpenPrs:
854
889
  'Leave PRs whose active landing command is `hold` out of the open-PR backpressure count. Inert without `maxOpenPrs`.',
855
890
  })
@@ -1440,7 +1475,7 @@ documentFields(configRootSchema, {
1440
1475
  'Named observe-only hooks: the dispatcher delivers each matching watch record to a command or URL, in order and at least once.',
1441
1476
  baseBranch: 'Branch used to cut builds, target PRs, and merge during reconciliation.',
1442
1477
  capacity:
1443
- 'Builds running work at once for this repository. A build that finished its pipeline holds no slot while it waits for a merge decision, nor does a build waiting on other tickets; either is admitted ahead of normal ticket claims when it must run again, urgent work first (see [slot admission order](dispatcher.md#slot-admission-order)). Other unfinished paused and blocked work retains slots. Node reconcile and verification exclude their own blocked/paused descendants at admission; new claims use total occupancy. See [integration capacity](integration-tree.md).',
1478
+ 'Slots for this repository. A build holds one from admission (a ticket claim, a start request or an admitted slot request) until it waits on a human, another ticket, the forge or its children, or ends. A build whose outside wait ends is admitted again ahead of ticket claims at its level, higher levels first (see [slot admission order](dispatcher.md#slot-admission-order)). Occupancy never exceeds capacity.',
1444
1479
  ticketScanIntervalSeconds:
1445
1480
  'Ticket-source ready scan cadence; tick spacing is the effective minimum.',
1446
1481
  forge:
@@ -1,6 +1,19 @@
1
- import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
1
+ import { constants } from 'node:fs'
2
+ import {
3
+ chmod,
4
+ copyFile,
5
+ cp,
6
+ lstat,
7
+ mkdir,
8
+ mkdtemp,
9
+ readdir,
10
+ readFile,
11
+ rm,
12
+ writeFile,
13
+ } from 'node:fs/promises'
2
14
  import { tmpdir } from 'node:os'
3
- import { dirname, join } from 'node:path'
15
+ import { dirname, isAbsolute, join, relative, sep } from 'node:path'
16
+ import { drainStack, forEachBounded, TREE_IO_CONCURRENCY } from './cli/bounded-io'
4
17
 
5
18
  async function spawnExec(cmd: string[], options: { cwd: string; signal?: AbortSignal }) {
6
19
  const child = Bun.spawn(cmd, {
@@ -62,12 +75,134 @@ async function execOrThrow(
62
75
  * while the repo manifest keeps it for workspace installs. */
63
76
  const packedManifestOmittedFields = ['patchedDependencies', 'devDependencies'] as const
64
77
 
78
+ /** Gzip level for an archive that is extracted at once and discarded, never
79
+ * stored or sent anywhere (the packaged source fingerprint). Its compressed
80
+ * bytes are pure overhead: level 0 keeps valid gzip framing for `tar -xzf`
81
+ * while spending no CPU on deflate, which at Bun's default level 9 dominates
82
+ * the pack. */
83
+ export const SCRATCH_ARCHIVE_GZIP_LEVEL = 0
84
+
85
+ /** Gzip level for a locally prepared runtime archive, kept under `.autobuild`
86
+ * and possibly uploaded to a guest. Level 2 packs in well under half the time
87
+ * of the default level 9 for an archive only slightly larger, so dispatcher
88
+ * starts and upgrade handoffs stop paying maximum deflate effort. Its own
89
+ * digest is taken from the bytes it produces. */
90
+ export const RUNTIME_ARCHIVE_GZIP_LEVEL = 2
91
+
92
+ /** The filesystem operations {@link stageDistributionFiles} uses, with the
93
+ * `node:fs/promises` signatures it calls them with. */
94
+ export interface StagingFilesystem {
95
+ lstat(path: string): Promise<{
96
+ mode: number
97
+ isDirectory(): boolean
98
+ isFile(): boolean
99
+ }>
100
+ readdir(path: string): Promise<string[]>
101
+ mkdir(path: string, options?: { recursive?: boolean }): Promise<unknown>
102
+ copyFile(source: string, target: string, mode: number): Promise<void>
103
+ chmod(path: string, mode: number): Promise<void>
104
+ cp(source: string, target: string, options: typeof stagingCopyOptions): Promise<void>
105
+ }
106
+
107
+ const nodeStagingFilesystem: StagingFilesystem = {
108
+ lstat,
109
+ readdir: (path) => readdir(path),
110
+ mkdir,
111
+ copyFile,
112
+ chmod,
113
+ cp,
114
+ }
115
+
116
+ const stagingCopyOptions = { recursive: true, errorOnExist: true, force: false } as const
117
+
118
+ function entriesOverlap(staging: string, entries: readonly string[]): boolean {
119
+ const normalized = entries.map((entry) => relative(staging, join(staging, entry)))
120
+ if (normalized.some((path) => path === '' || path.startsWith('..') || isAbsolute(path)))
121
+ return true
122
+ for (const a of normalized)
123
+ for (const b of normalized)
124
+ if (a !== b ? b.startsWith(a + sep) : normalized.indexOf(a) !== normalized.lastIndexOf(a))
125
+ return true
126
+ return false
127
+ }
128
+
129
+ /** Copies each positive `files` entry of `root` to the same relative path under
130
+ * a fresh `staging` directory, with the result `cp(source, target, { recursive:
131
+ * true, errorOnExist: true, force: false })` per entry produces.
132
+ *
133
+ * Disjoint entries are walked by one bounded pool: directory children are
134
+ * queued as plain items, so at most `limit` filesystem operations are in flight
135
+ * across and within entries however many files they hold. The walker creates
136
+ * directories and copies regular files itself, giving each file its source
137
+ * mode (`& 0o7777`) and, after every copy has finished, each directory its
138
+ * source mode deepest level first so a read-only directory is restricted only
139
+ * once its descendants exist. Every other entry kind (symlinks, FIFOs,
140
+ * sockets, devices) is handed to `cp` with the same options, keeping its
141
+ * semantics exactly. Overlapping, duplicate, empty or escaping entries keep
142
+ * the serial per-entry `cp` loop in manifest order, so merges and overlap
143
+ * errors behave as before.
144
+ *
145
+ * After the first failure no operation starts, and the promise settles only
146
+ * once every started operation has settled, so the caller can remove staging
147
+ * without racing an outstanding write. */
148
+ export async function stageDistributionFiles(
149
+ root: string,
150
+ staging: string,
151
+ entries: readonly string[],
152
+ fs: StagingFilesystem = nodeStagingFilesystem,
153
+ limit = TREE_IO_CONCURRENCY,
154
+ ): Promise<void> {
155
+ if (entriesOverlap(staging, entries)) {
156
+ for (const entry of entries) {
157
+ const target = join(staging, entry)
158
+ await fs.mkdir(dirname(target), { recursive: true })
159
+ await fs.cp(join(root, entry), target, stagingCopyOptions)
160
+ }
161
+ return
162
+ }
163
+ type Item = { source: string; target: string; depth: number }
164
+ const directories: Array<Array<{ target: string; mode: number }>> = []
165
+ await drainStack<Item>(
166
+ entries.map((entry) => ({ source: join(root, entry), target: join(staging, entry), depth: 0 })),
167
+ limit,
168
+ async ({ source, target, depth }, push) => {
169
+ const status = await fs.lstat(source)
170
+ if (depth === 0) await fs.mkdir(dirname(target), { recursive: true })
171
+ if (status.isDirectory()) {
172
+ await fs.mkdir(target)
173
+ const level = directories[depth] ?? []
174
+ directories[depth] = level
175
+ level.push({ target, mode: status.mode & 0o7777 })
176
+ for (const name of await fs.readdir(source))
177
+ push({ source: join(source, name), target: join(target, name), depth: depth + 1 })
178
+ } else if (status.isFile()) {
179
+ await fs.copyFile(source, target, constants.COPYFILE_EXCL)
180
+ await fs.chmod(target, status.mode & 0o7777)
181
+ } else {
182
+ await fs.cp(source, target, stagingCopyOptions)
183
+ }
184
+ },
185
+ )
186
+ for (let depth = directories.length - 1; depth >= 0; depth--)
187
+ await forEachBounded(directories[depth] ?? [], limit, ({ target, mode }) =>
188
+ fs.chmod(target, mode),
189
+ )
190
+ }
191
+
192
+ /** Packs `root`'s `files` set with `bun pm pack`. `options.gzipLevel` (an
193
+ * integer 0–9) sets the archive's deflate effort; omitted, Bun's default
194
+ * applies and the command is unchanged. The level changes compressed bytes
195
+ * only, never the extracted contents. */
65
196
  export async function packageDistribution(
66
197
  root: string,
67
198
  exec: PackagingExec = spawnExec,
68
199
  signal?: AbortSignal,
69
200
  filesystem: { mkdtemp(prefix: string): Promise<string>; rm: typeof rm } = { mkdtemp, rm },
201
+ options: { gzipLevel?: number } = {},
70
202
  ): Promise<Uint8Array> {
203
+ const { gzipLevel } = options
204
+ if (gzipLevel !== undefined && (!Number.isInteger(gzipLevel) || gzipLevel < 0 || gzipLevel > 9))
205
+ throw new Error('gzip level must be an integer from 0 to 9')
71
206
  const staging = await filesystem.mkdtemp(join(tmpdir(), 'autobuild-pack-staging-'))
72
207
  let destination: string | undefined
73
208
  let failure: unknown
@@ -88,25 +223,28 @@ export async function packageDistribution(
88
223
  'Autobuild packaging requires the root package.json to list its files as an array of paths',
89
224
  )
90
225
  }
91
- for (const entry of files as string[]) {
92
- // npm `files` entries may be negated globs (for example
93
- // `!packages/core/src/**/*.test.ts`, which keeps test files out of the
94
- // published package). Only positive entries name a path to stage: the
95
- // negations stay in the staged manifest and `bun pm pack` applies them,
96
- // so the packed set still excludes those paths.
97
- if (entry.startsWith('!')) continue
98
- const target = join(staging, entry)
99
- await mkdir(dirname(target), { recursive: true })
100
- await cp(join(root, entry), target, {
101
- recursive: true,
102
- errorOnExist: true,
103
- force: false,
104
- })
105
- }
226
+ // npm `files` entries may be negated globs (for example
227
+ // `!packages/core/src/**/*.test.ts`, which keeps test files out of the
228
+ // published package). Only positive entries name a path to stage: the
229
+ // negations stay in the staged manifest and `bun pm pack` applies them,
230
+ // so the packed set still excludes those paths.
231
+ await stageDistributionFiles(
232
+ root,
233
+ staging,
234
+ (files as string[]).filter((entry) => !entry.startsWith('!')),
235
+ )
106
236
  for (const field of packedManifestOmittedFields) delete manifest[field]
107
237
  await writeFile(join(staging, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`)
108
238
  await execOrThrow(
109
- ['bun', 'pm', 'pack', '--ignore-scripts', '--destination', destination],
239
+ [
240
+ 'bun',
241
+ 'pm',
242
+ 'pack',
243
+ '--ignore-scripts',
244
+ ...(gzipLevel === undefined ? [] : ['--gzip-level', String(gzipLevel)]),
245
+ '--destination',
246
+ destination,
247
+ ],
110
248
  staging,
111
249
  exec,
112
250
  signal,
@@ -0,0 +1,28 @@
1
+ /** The read catalog identity, kept free of payload schemas so stores can name
2
+ * it without initializing the decoders. `./compatibility` re-exports it. */
3
+ import { buildEventPolicy, repositoryEventPolicy } from './policy'
4
+
5
+ /** Change this revision whenever projection semantics change without new types. */
6
+ // Revision 3 retains optional billing-account descriptors in session/attempt projections.
7
+ // Revision 4 retains the optional effective prompt in session projections.
8
+ // Revision 5 retains the optional preparation creation key.
9
+ // Revision 6 retains the optional role profile on build creation and session starts.
10
+ // Revision 7 retains the optional abort destination and hand-back report fields.
11
+ // Revision 8 retains the optional landed head on accepted attempt settlements.
12
+ // Revision 9 retains the optional stream and provider substitution on judge session starts.
13
+ // Revision 10 retains the optional hold reason.
14
+ // Revision 11 retains optional forge rate-limit snapshots on tick telemetry
15
+ // and the optional continued marker on forge degradation.
16
+ // Revision 12 retains the optional build priority and urgent scan demand.
17
+ export const READ_DECODER_REVISION = 12
18
+ export function catalogIdentity(
19
+ build: Record<string, string> = buildEventPolicy,
20
+ repository: Record<string, string> = repositoryEventPolicy,
21
+ ): string {
22
+ const sorted = (catalog: Record<string, string>) =>
23
+ Object.entries(catalog).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
24
+ return new Bun.CryptoHasher('sha256')
25
+ .update(JSON.stringify([READ_DECODER_REVISION, sorted(build), sorted(repository)]))
26
+ .digest('hex')
27
+ }
28
+ export const READ_CATALOG_IDENTITY = catalogIdentity()
@@ -64,6 +64,7 @@ export const allowedActorKinds: Record<EventType, readonly ActorKind[]> = {
64
64
  'landing.native-applied': ['dispatcher', 'kernel'],
65
65
  'target.distance': ['dispatcher'],
66
66
  'pipeline.settled': ['dispatcher'],
67
+ 'slot.admitted': ['dispatcher'],
67
68
  'target.rewritten': ['dispatcher', 'kernel'],
68
69
  'target.rewrite-cleared': ['dispatcher', 'kernel'],
69
70
  'target.moved': ['dispatcher', 'kernel'],
@@ -270,15 +271,8 @@ export const allowedActorKinds: Record<EventType, readonly ActorKind[]> = {
270
271
  * wrong and what would be accepted, so the in-session correction loop is
271
272
  * immediate and cheap.
272
273
  */
273
- export class EventValidationError extends Error {
274
- constructor(
275
- message: string,
276
- readonly issues?: unknown,
277
- ) {
278
- super(message)
279
- this.name = 'EventValidationError'
280
- }
281
- }
274
+ import { EventValidationError } from './validation-error'
275
+ export { EventValidationError }
282
276
 
283
277
  /**
284
278
  * The single validation gate. Every store adapter MUST pass writes through
@@ -4,12 +4,7 @@ import type { Actor } from './envelope'
4
4
  import type { AbEvent } from './catalog'
5
5
  import { eventPayloadSchemas } from './payloads'
6
6
  import { repositoryEventPayloadSchemas, type RepositoryEvent } from './repository'
7
- import {
8
- buildEventPolicy,
9
- repositoryEventPolicy,
10
- compatibilityMetadataSchema,
11
- type CompatibilityMetadata,
12
- } from './policy'
7
+ import { compatibilityMetadataSchema, type CompatibilityMetadata } from './policy'
13
8
 
14
9
  export interface StoredEvent {
15
10
  build?: string
@@ -22,30 +17,7 @@ export interface StoredEvent {
22
17
  compatibility?: CompatibilityMetadata
23
18
  }
24
19
 
25
- /** Change this revision whenever projection semantics change without new types. */
26
- // Revision 3 retains optional billing-account descriptors in session/attempt projections.
27
- // Revision 4 retains the optional effective prompt in session projections.
28
- // Revision 5 retains the optional preparation creation key.
29
- // Revision 6 retains the optional role profile on build creation and session starts.
30
- // Revision 7 retains the optional abort destination and hand-back report fields.
31
- // Revision 8 retains the optional landed head on accepted attempt settlements.
32
- // Revision 9 retains the optional stream and provider substitution on judge session starts.
33
- // Revision 10 retains the optional hold reason.
34
- // Revision 11 retains optional forge rate-limit snapshots on tick telemetry
35
- // and the optional continued marker on forge degradation.
36
- // Revision 12 retains the optional build priority and urgent scan demand.
37
- export const READ_DECODER_REVISION = 12
38
- export function catalogIdentity(
39
- build: Record<string, string> = buildEventPolicy,
40
- repository: Record<string, string> = repositoryEventPolicy,
41
- ): string {
42
- const sorted = (catalog: Record<string, string>) =>
43
- Object.entries(catalog).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
44
- return new Bun.CryptoHasher('sha256')
45
- .update(JSON.stringify([READ_DECODER_REVISION, sorted(build), sorted(repository)]))
46
- .digest('hex')
47
- }
48
- export const READ_CATALOG_IDENTITY = catalogIdentity()
20
+ export { READ_DECODER_REVISION, catalogIdentity, READ_CATALOG_IDENTITY } from './catalog-identity'
49
21
 
50
22
  /** Remove only keys reported as unknown by the original schema, then run that
51
23
  * schema again. Its required fields, enums and refinements remain authoritative. */