@defrex/autobuild 1.11.1 → 1.12.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 (102) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +177 -54
  3. package/docs/answering-blocked-builds.md +10 -2
  4. package/docs/architecture.md +66 -6
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/configuration.md +13 -11
  7. package/docs/dispatcher.md +1 -1
  8. package/docs/integration-tree.md +28 -16
  9. package/docs/operator-api.md +4 -4
  10. package/docs/operator-surfaces.md +35 -0
  11. package/docs/optimization-nodes.md +3 -2
  12. package/docs/tickets.md +1 -1
  13. package/docs/troubleshooting.md +1 -1
  14. package/package.json +3 -3
  15. package/packages/core/src/cli/ambient-errors.ts +17 -0
  16. package/packages/core/src/cli/bounded-io.ts +174 -0
  17. package/packages/core/src/cli/dashboard/model.ts +81 -23
  18. package/packages/core/src/cli/dashboard/poll.ts +20 -31
  19. package/packages/core/src/cli/dashboard/render.ts +14 -37
  20. package/packages/core/src/cli/dashboard/row-text.ts +24 -7
  21. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  22. package/packages/core/src/cli/dashboard/vocabulary.ts +161 -20
  23. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  24. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  25. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  26. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  27. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  28. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  29. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  30. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  31. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  32. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  33. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  34. package/packages/core/src/cli/dispatch.ts +68 -5
  35. package/packages/core/src/cli/env.ts +2 -15
  36. package/packages/core/src/cli/help.ts +5 -4
  37. package/packages/core/src/cli/main.ts +4 -2
  38. package/packages/core/src/cli/production-store.ts +102 -0
  39. package/packages/core/src/cli/repo-state.ts +2 -3
  40. package/packages/core/src/cli/repository-status.ts +28 -22
  41. package/packages/core/src/cli/sessionless-store.ts +26 -0
  42. package/packages/core/src/cli/status.ts +169 -40
  43. package/packages/core/src/cli/store-opening.ts +15 -58
  44. package/packages/core/src/cli/store-ref.ts +6 -1
  45. package/packages/core/src/config/schema.ts +1 -1
  46. package/packages/core/src/distribution-packaging.ts +156 -18
  47. package/packages/core/src/events/catalog-identity.ts +28 -0
  48. package/packages/core/src/events/catalog.ts +3 -9
  49. package/packages/core/src/events/compatibility.ts +2 -30
  50. package/packages/core/src/events/payloads.ts +11 -0
  51. package/packages/core/src/events/policy.ts +3 -0
  52. package/packages/core/src/events/repository.ts +1 -1
  53. package/packages/core/src/events/sessions.ts +1 -1
  54. package/packages/core/src/events/validation-error.ts +12 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +9 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  59. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  60. package/packages/core/src/kernel/capacity-build.ts +21 -0
  61. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  62. package/packages/core/src/kernel/dispatch-capacity.ts +354 -147
  63. package/packages/core/src/kernel/engine.ts +2 -8
  64. package/packages/core/src/kernel/measurement.ts +24 -0
  65. package/packages/core/src/kernel/read-facts.ts +8 -370
  66. package/packages/core/src/kernel/reducer-registry.ts +40 -125
  67. package/packages/core/src/kernel/reducer-revisions.ts +3 -0
  68. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  69. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  70. package/packages/core/src/kernel/reducer.ts +57 -9
  71. package/packages/core/src/kernel/reopen-state.ts +10 -0
  72. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  73. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  74. package/packages/core/src/operator/presentation.ts +13 -0
  75. package/packages/core/src/operator/query.ts +40 -39
  76. package/packages/core/src/operator/registry.ts +3 -3
  77. package/packages/core/src/ports/workspace/fake.ts +15 -3
  78. package/packages/core/src/processes/dispatcher.ts +232 -75
  79. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  80. package/packages/core/src/store/local/capabilities.ts +115 -0
  81. package/packages/core/src/store/local/store.ts +86 -56
  82. package/packages/core/src/store/reduced-reads.ts +9 -1
  83. package/packages/core/src/store/reducer-value-read.ts +235 -0
  84. package/packages/core/src/store/reducer-value-shapes.json +1437 -1349
  85. package/packages/core/src/store/reducer-values.ts +36 -204
  86. package/packages/core/src/store/remote/released-clients.json +11 -0
  87. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  88. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  89. package/packages/core/src/store/rollup-lease.ts +41 -0
  90. package/packages/core/src/store/rollups.ts +7 -38
  91. package/packages/core/src/store/snapshots.ts +1 -1
  92. package/packages/core/src/testing/dispatch-read-budget.ts +265 -4
  93. package/packages/core/src/testing/import-graph.ts +78 -0
  94. package/packages/core/src/testing/reduced-read-budget.ts +221 -22
  95. package/packages/core/src/testing/slot-agreement.ts +52 -0
  96. package/packages/core/src/web/assets/app.js +5 -5
  97. package/skills/guide/SKILL.md +115 -44
  98. package/skills/guide/references/integration-tree.md +28 -16
  99. package/skills/guide/references/operator-api.md +4 -4
  100. package/skills/guide/references/optimization-nodes.md +3 -2
  101. package/skills/operate/SKILL.md +38 -20
  102. package/templates/hosted-service/package.json +2 -2
@@ -10,8 +10,17 @@ import {
10
10
  copyFile,
11
11
  chmod,
12
12
  symlink,
13
+ rm,
14
+ writeFile,
13
15
  } from 'node:fs/promises'
14
16
  import { dirname, join, relative, resolve, isAbsolute } from 'node:path'
17
+ import {
18
+ PACKAGE_CONCURRENCY,
19
+ TREE_IO_CONCURRENCY,
20
+ drainStack,
21
+ forEachBounded,
22
+ orderedPrefetch,
23
+ } from './bounded-io'
15
24
 
16
25
  export type Manifest = {
17
26
  name?: string
@@ -49,6 +58,23 @@ export async function installedPackage(name: string, start: string): Promise<str
49
58
  }
50
59
  }
51
60
 
61
+ /** Applies recorded directory modes deepest level first, so a read-only
62
+ * directory is restricted only after every descendant has been written. */
63
+ async function applyDirectoryModes(
64
+ directories: Array<{ target: string; mode: number; depth: number }>,
65
+ ): Promise<void> {
66
+ const levels = new Map<number, Array<{ target: string; mode: number }>>()
67
+ for (const directory of directories) {
68
+ const level = levels.get(directory.depth)
69
+ if (level) level.push(directory)
70
+ else levels.set(directory.depth, [directory])
71
+ }
72
+ for (const depth of [...levels.keys()].sort((a, b) => b - a))
73
+ await forEachBounded(levels.get(depth)!, TREE_IO_CONCURRENCY, ({ target, mode }) =>
74
+ chmod(target, mode),
75
+ )
76
+ }
77
+
52
78
  /** Independent bytes, never hardlinks. Package-internal links are normalized;
53
79
  * an escaping asset link is rejected rather than silently following a checkout. */
54
80
  export async function copySnapshotTree(
@@ -58,45 +84,182 @@ export async function copySnapshotTree(
58
84
  stack = new Set<string>(),
59
85
  exclusions = excludedSnapshotNames,
60
86
  ): Promise<void> {
61
- const actual = await realpath(source)
62
- if (!inside(boundary, actual))
63
- throw new Error(`snapshot link escapes package: ${source} -> ${actual}`)
64
- if (stack.has(actual)) throw new Error(`cyclic snapshot asset link: ${source}`)
65
- const sourceStat = await lstat(source)
66
- if (sourceStat.isSymbolicLink()) {
67
- const mapped = resolve(target, relative(source, actual))
68
- await mkdir(dirname(target), { recursive: true })
69
- await symlink(relative(dirname(target), mapped), target)
70
- return
87
+ type Item = { source: string; target: string; stack: Set<string>; depth: number }
88
+ const directories: Array<{ target: string; mode: number; depth: number }> = []
89
+ await drainStack<Item>(
90
+ [{ source, target, stack, depth: 0 }],
91
+ TREE_IO_CONCURRENCY,
92
+ async (item, push) => {
93
+ const actual = await realpath(item.source)
94
+ if (!inside(boundary, actual))
95
+ throw new Error(`snapshot link escapes package: ${item.source} -> ${actual}`)
96
+ if (item.stack.has(actual)) throw new Error(`cyclic snapshot asset link: ${item.source}`)
97
+ // A child's parent directory was created before the child was queued.
98
+ const root = item.depth === 0
99
+ const sourceStat = await lstat(item.source)
100
+ if (sourceStat.isSymbolicLink()) {
101
+ const mapped = resolve(item.target, relative(item.source, actual))
102
+ if (root) await mkdir(dirname(item.target), { recursive: true })
103
+ await symlink(relative(dirname(item.target), mapped), item.target)
104
+ return
105
+ }
106
+ const stat = await lstat(actual)
107
+ if (stat.isDirectory()) {
108
+ await mkdir(item.target, { recursive: true })
109
+ directories.push({ target: item.target, mode: stat.mode & 0o777, depth: item.depth })
110
+ const next = new Set(item.stack).add(actual)
111
+ const names = (await readdir(actual))
112
+ .sort()
113
+ .filter(
114
+ (name) =>
115
+ !exclusions.has(name) && !(exclusions.has('.env') && name.startsWith('.env.')),
116
+ )
117
+ for (let index = names.length - 1; index >= 0; index--)
118
+ push({
119
+ source: join(actual, names[index]!),
120
+ target: join(item.target, names[index]!),
121
+ stack: next,
122
+ depth: item.depth + 1,
123
+ })
124
+ } else if (stat.isFile()) {
125
+ if (root) await mkdir(dirname(item.target), { recursive: true })
126
+ await copyFile(actual, item.target)
127
+ await chmod(item.target, stat.mode & 0o777)
128
+ } else throw new Error(`unsupported snapshot asset: ${item.source}`)
129
+ },
130
+ )
131
+ await applyDirectoryModes(directories)
132
+ }
133
+
134
+ /** Metadata recorded for every node a verbatim copy created, after the copy
135
+ * finished writing it. `changed` is the greatest recorded change time. */
136
+ export interface TreeWitness {
137
+ entries: Array<{
138
+ path: string
139
+ ino: bigint
140
+ mode: bigint
141
+ size: bigint
142
+ mtimeNs: bigint
143
+ ctimeNs: bigint
144
+ }>
145
+ changed: bigint
146
+ }
147
+
148
+ async function witnessEntry(path: string): Promise<TreeWitness['entries'][number]> {
149
+ const { ino, mode, size, mtimeNs, ctimeNs } = await lstat(path, { bigint: true })
150
+ return { path, ino, mode, size, mtimeNs, ctimeNs }
151
+ }
152
+
153
+ /** Copies an already validated runtime tree: link strings verbatim, file bytes
154
+ * and permission bits. Every result is digested or import-checked by callers.
155
+ * The returned witness records each created node once it is final: files after
156
+ * their mode, directories after every child and mode, so any later change to
157
+ * bytes, modes, links or entries changes a recorded change time. */
158
+ export async function copyTreeVerbatim(source: string, target: string): Promise<TreeWitness> {
159
+ type Item = { source: string; target: string; depth: number }
160
+ const directories: Array<{ target: string; mode: number; depth: number }> = []
161
+ const entries: TreeWitness['entries'] = []
162
+ await drainStack<Item>(
163
+ [{ source, target, depth: 0 }],
164
+ TREE_IO_CONCURRENCY,
165
+ async (item, push) => {
166
+ const stat = await lstat(item.source)
167
+ if (stat.isSymbolicLink()) {
168
+ await symlink(await readlink(item.source), item.target)
169
+ entries.push(await witnessEntry(item.target))
170
+ } else if (stat.isDirectory()) {
171
+ await mkdir(item.target, { recursive: item.depth === 0 })
172
+ directories.push({ target: item.target, mode: stat.mode & 0o777, depth: item.depth })
173
+ for (const name of await readdir(item.source))
174
+ push({
175
+ source: join(item.source, name),
176
+ target: join(item.target, name),
177
+ depth: item.depth + 1,
178
+ })
179
+ } else if (stat.isFile()) {
180
+ await copyFile(item.source, item.target)
181
+ await chmod(item.target, stat.mode & 0o777)
182
+ entries.push(await witnessEntry(item.target))
183
+ } else throw new Error(`unsupported runtime tree entry: ${item.source}`)
184
+ },
185
+ )
186
+ await applyDirectoryModes(directories)
187
+ await forEachBounded(directories, TREE_IO_CONCURRENCY, async ({ target }) => {
188
+ entries.push(await witnessEntry(target))
189
+ })
190
+ let changed = 0n
191
+ for (const entry of entries) if (entry.ctimeNs > changed) changed = entry.ctimeNs
192
+ return { entries, changed }
193
+ }
194
+
195
+ const WITNESS_SEAL_LIMIT_MS = 1000
196
+
197
+ /** Waits until the filesystem clock has passed every recorded change time, so
198
+ * any later modification of a witnessed node carries a different change time
199
+ * even on coarse timestamps. Fails closed when the clock does not advance. */
200
+ export async function sealTreeWitness(witness: TreeWitness, barrier: string): Promise<void> {
201
+ const started = performance.now()
202
+ try {
203
+ for (;;) {
204
+ await writeFile(barrier, '')
205
+ if ((await lstat(barrier, { bigint: true })).ctimeNs > witness.changed) return
206
+ if (performance.now() - started > WITNESS_SEAL_LIMIT_MS)
207
+ throw new Error(
208
+ 'runtime dependency witness could not be sealed: filesystem clock did not advance',
209
+ )
210
+ await new Promise<void>((resolve) => setImmediate(resolve))
211
+ }
212
+ } finally {
213
+ await rm(barrier, { force: true })
71
214
  }
72
- const stat = await lstat(actual)
73
- if (stat.isDirectory()) {
74
- await mkdir(target, { recursive: true })
75
- const next = new Set(stack).add(actual)
76
- for (const name of (await readdir(actual)).sort()) {
77
- if (exclusions.has(name) || (exclusions.has('.env') && name.startsWith('.env.'))) continue
78
- await copySnapshotTree(join(actual, name), join(target, name), boundary, next, exclusions)
215
+ }
216
+
217
+ /** Proves a sealed tree still holds exactly the witnessed nodes. Userspace
218
+ * cannot set change times, so a write, chmod, relink or added or removed entry
219
+ * (which changes its parent directory) after sealing is refused. */
220
+ export async function assertTreeUnchanged(witness: TreeWitness, describe: string): Promise<void> {
221
+ await forEachBounded(witness.entries, TREE_IO_CONCURRENCY, async (entry) => {
222
+ let current: TreeWitness['entries'][number]
223
+ try {
224
+ current = await witnessEntry(entry.path)
225
+ } catch (error) {
226
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
227
+ throw new Error(`${describe} changed during import validation: ${entry.path}; retry dispatch`)
79
228
  }
80
- await chmod(target, stat.mode & 0o777)
81
- } else if (stat.isFile()) {
82
- await mkdir(dirname(target), { recursive: true })
83
- await copyFile(actual, target)
84
- await chmod(target, stat.mode & 0o777)
85
- } else throw new Error(`unsupported snapshot asset: ${source}`)
229
+ if (
230
+ current.ino !== entry.ino ||
231
+ current.mode !== entry.mode ||
232
+ current.size !== entry.size ||
233
+ current.mtimeNs !== entry.mtimeNs ||
234
+ current.ctimeNs !== entry.ctimeNs
235
+ )
236
+ throw new Error(`${describe} changed during import validation: ${entry.path}; retry dispatch`)
237
+ })
86
238
  }
87
239
 
88
- /** Digest includes names, executable bits, bytes and internal link topology. */
240
+ /** Digest includes names, executable bits, bytes and internal link topology.
241
+ * Metadata is gathered concurrently, then hashed in sorted pre-order with file
242
+ * bytes read through a bounded in-order window, so the digest is independent
243
+ * of completion order. */
89
244
  export async function treeDigest(
90
245
  root: string,
91
246
  exclude = new Set<string>(),
92
247
  allowedLink?: string,
93
248
  ): Promise<string> {
94
- const hash = createHash('sha256')
95
- async function walk(path: string): Promise<void> {
96
- const rel = relative(root, path)
249
+ type Node = {
250
+ path: string
251
+ mode: number
252
+ kind: 'link' | 'directory' | 'file'
253
+ link?: string
254
+ children?: Node[]
255
+ }
256
+ const top: Node = { path: root, mode: 0, kind: 'file' }
257
+ await drainStack([top], TREE_IO_CONCURRENCY, async (node, push) => {
258
+ const path = node.path
97
259
  const stat = await lstat(path)
98
- hash.update(JSON.stringify([rel, stat.mode & 0o111]))
260
+ node.mode = stat.mode
99
261
  if (stat.isSymbolicLink()) {
262
+ node.kind = 'link'
100
263
  const link = await readlink(path)
101
264
  if (
102
265
  !inside(root, resolve(dirname(path), link)) &&
@@ -106,17 +269,49 @@ export async function treeDigest(
106
269
  const actual = await realpath(path)
107
270
  if (!inside(root, actual) && actual !== allowedLink)
108
271
  throw new Error(`snapshot link escapes runtime: ${path}`)
109
- hash.update(`link:${relative(dirname(path), actual)}`)
272
+ node.link = relative(dirname(path), actual)
110
273
  } else if (stat.isDirectory()) {
111
- hash.update('directory')
112
- for (const name of (await readdir(path)).sort())
113
- if (!exclude.has(name)) await walk(join(path, name))
114
- } else if (stat.isFile()) {
115
- hash.update('file')
116
- hash.update(await readFile(path))
117
- } else throw new Error(`unsupported snapshot file: ${path}`)
274
+ node.kind = 'directory'
275
+ const children = (await readdir(path))
276
+ .sort()
277
+ .filter((name) => !exclude.has(name))
278
+ .map((name): Node => ({ path: join(path, name), mode: 0, kind: 'file' }))
279
+ node.children = children
280
+ for (let index = children.length - 1; index >= 0; index--) push(children[index]!)
281
+ } else if (stat.isFile()) node.kind = 'file'
282
+ else throw new Error(`unsupported snapshot file: ${path}`)
283
+ })
284
+ const order: Node[] = []
285
+ const pending = [top]
286
+ while (pending.length) {
287
+ const node = pending.pop()!
288
+ order.push(node)
289
+ const children = node.children ?? []
290
+ for (let index = children.length - 1; index >= 0; index--) pending.push(children[index]!)
291
+ }
292
+ const hash = createHash('sha256')
293
+ let emitted = 0
294
+ const emitThrough = (end: number) => {
295
+ for (; emitted < end; emitted++) {
296
+ const node = order[emitted]!
297
+ hash.update(JSON.stringify([relative(root, node.path), node.mode & 0o111]))
298
+ if (node.kind === 'link') hash.update(`link:${node.link}`)
299
+ else if (node.kind === 'directory') hash.update('directory')
300
+ }
118
301
  }
119
- await walk(root)
302
+ const files: number[] = []
303
+ for (const [index, node] of order.entries()) if (node.kind === 'file') files.push(index)
304
+ await orderedPrefetch(
305
+ files,
306
+ TREE_IO_CONCURRENCY,
307
+ (index) => readFile(order[index]!.path),
308
+ (bytes, index) => {
309
+ emitThrough(index + 1)
310
+ hash.update('file')
311
+ hash.update(bytes)
312
+ },
313
+ )
314
+ emitThrough(order.length)
120
315
  return hash.digest('hex')
121
316
  }
122
317
 
@@ -148,9 +343,17 @@ export async function scanDependencies(
148
343
  ...manifest.dependencies,
149
344
  ...manifest.optionalDependencies,
150
345
  }
151
- for (const name of Object.keys(names).sort()) {
152
- if (name === '@defrex/autobuild' && options.coreRoot) continue
153
- const found = await installedPackage(name, source)
346
+ const sorted = Object.keys(names)
347
+ .sort()
348
+ .filter((name) => !(name === '@defrex/autobuild' && options.coreRoot))
349
+ // Resolution is independent per edge; ids are still assigned in sorted
350
+ // depth-first order below, which the fingerprint encodes.
351
+ const resolved: Array<string | undefined> = []
352
+ await forEachBounded(sorted, TREE_IO_CONCURRENCY, async (name, index) => {
353
+ resolved[index] = await installedPackage(name, source)
354
+ })
355
+ for (const [index, name] of sorted.entries()) {
356
+ const found = resolved[index]
154
357
  if (!found) {
155
358
  if (
156
359
  Object.hasOwn(manifest.optionalDependencies ?? {}, name) ||
@@ -172,7 +375,7 @@ export async function scanDependencies(
172
375
  source: found,
173
376
  manifest: await readManifest(found),
174
377
  edges: {},
175
- digest: await treeDigest(found, dependencyExclusions),
378
+ digest: '',
176
379
  }
177
380
  packages.push(entry)
178
381
  entry.edges = await edges(found, entry.manifest)
@@ -182,6 +385,9 @@ export async function scanDependencies(
182
385
  return result
183
386
  }
184
387
  const roots = await edges(root, options.manifest ?? (await readManifest(root)), options.dev)
388
+ await forEachBounded(packages, PACKAGE_CONCURRENCY, async (entry) => {
389
+ entry.digest = await treeDigest(entry.source, dependencyExclusions)
390
+ })
185
391
  const fingerprint = createHash('sha256')
186
392
  .update(JSON.stringify({ roots, packages: packages.map(({ source: _, ...rest }) => rest) }))
187
393
  .digest('hex')
@@ -206,7 +412,7 @@ export async function copyDependencies(
206
412
  await symlink(relative(dirname(link), coreRoot), link)
207
413
  }
208
414
  }
209
- for (const [id, entry] of graph.packages.entries()) {
415
+ await forEachBounded(graph.packages, PACKAGE_CONCURRENCY, async (entry, id) => {
210
416
  await copySnapshotTree(
211
417
  entry.source,
212
418
  packagePath(id),
@@ -216,7 +422,8 @@ export async function copyDependencies(
216
422
  )
217
423
  if ((await treeDigest(packagePath(id), dependencyExclusions)) !== entry.digest)
218
424
  throw new Error(`installed dependency changed while copying: ${entry.source}; retry dispatch`)
219
- }
425
+ })
426
+ // Links are published only after every package copy has been verified.
220
427
  for (const [id, entry] of graph.packages.entries()) await links(packagePath(id), entry.edges)
221
428
  await links(target, graph.roots)
222
429
  }
@@ -40,6 +40,38 @@ export function validateUpgradeLockReceipt(
40
40
  throw new Error('installed integrity contradicts authoritative lock')
41
41
  }
42
42
 
43
+ /** Runtime staging consumes only the root package's production closure, so
44
+ * `--production --filter ./` skips development-only dependencies and
45
+ * workspaces. The lock stays frozen for every workspace and scripts stay off. */
46
+ export const SOURCE_INSTALL_ARGUMENTS = [
47
+ 'install',
48
+ '--frozen-lockfile',
49
+ '--ignore-scripts',
50
+ '--no-progress',
51
+ '--production',
52
+ '--filter',
53
+ './',
54
+ ] as const
55
+
56
+ export async function installSourceDependencies(
57
+ root: string,
58
+ env: Record<string, string | undefined>,
59
+ signal: AbortSignal,
60
+ ): Promise<void> {
61
+ // Require a committed lock explicitly: frozen-lockfile alone permits a missing lock.
62
+ await readFile(join(root, 'bun.lock'))
63
+ const child = Bun.spawn([process.execPath, ...SOURCE_INSTALL_ARGUMENTS], {
64
+ cwd: root,
65
+ env,
66
+ stdout: 'ignore',
67
+ stderr: 'pipe',
68
+ signal: AbortSignal.any([signal, AbortSignal.timeout(120_000)]),
69
+ })
70
+ const [code] = await Promise.all([child.exited, new Response(child.stderr).text()])
71
+ signal.throwIfAborted()
72
+ if (code !== 0) throw new Error('source dependency installation failed')
73
+ }
74
+
43
75
  export async function prepareUpgrade(input: {
44
76
  target: UpgradeTarget
45
77
  checkout: string
@@ -130,21 +162,7 @@ export async function prepareUpgrade(input: {
130
162
  return withSourceExport({ checkout, sha: target.sha!, signal }, async (root) => {
131
163
  const content = await sourceContent(root, target.source, signal)
132
164
  if (content.key !== target.key) throw new Error('source target changed during preparation')
133
- // Require a committed lock explicitly: frozen-lockfile alone permits a missing lock.
134
- await readFile(join(root, 'bun.lock'))
135
- const child = Bun.spawn(
136
- [process.execPath, 'install', '--frozen-lockfile', '--ignore-scripts', '--no-progress'],
137
- {
138
- cwd: root,
139
- env: input.env,
140
- stdout: 'ignore',
141
- stderr: 'pipe',
142
- signal: AbortSignal.any([signal, AbortSignal.timeout(120_000)]),
143
- },
144
- )
145
- const [code] = await Promise.all([child.exited, new Response(child.stderr).text()])
146
- signal.throwIfAborted()
147
- if (code !== 0) throw new Error('source dependency installation failed')
165
+ await installSourceDependencies(root, input.env, signal)
148
166
  const path = join(root, 'package.json')
149
167
  const manifest = JSON.parse(await readFile(path, 'utf8'))
150
168
  manifest.gitHead = target.sha
@@ -158,7 +176,9 @@ export async function prepareUpgrade(input: {
158
176
  upgradeKey: target.key,
159
177
  commit: target.sha!,
160
178
  },
161
- { provenance: 'source' },
179
+ // The export sits inside the checkout, so a dependency missing from
180
+ // it would otherwise resolve from the checkout's own node_modules.
181
+ { provenance: 'source', containDependencies: true },
162
182
  )
163
183
  if (captureRuntimeIdentity(runtime.root).commit !== target.sha)
164
184
  throw new Error('source runtime commit contradicts target')
@@ -12,7 +12,7 @@ import {
12
12
  readlink,
13
13
  } from 'node:fs/promises'
14
14
  import { join, resolve } from 'node:path'
15
- import { packageDistribution } from '../distribution-packaging'
15
+ import { packageDistribution, SCRATCH_ARCHIVE_GZIP_LEVEL } from '../distribution-packaging'
16
16
  import { parse as parseToml } from 'smol-toml'
17
17
  import { treeDigest, inside, type Manifest } from './dispatch-runtime-dependencies'
18
18
  import type { Exec } from '../ports/workspace/git-worktree'
@@ -290,7 +290,13 @@ async function packagedFingerprint(root: string, signal?: AbortSignal): Promise<
290
290
  try {
291
291
  await writeFile(
292
292
  join(stage, 'package.tgz'),
293
- await packageDistribution(root, undefined, signal ?? AbortSignal.timeout(120_000)),
293
+ await packageDistribution(
294
+ root,
295
+ undefined,
296
+ signal ?? AbortSignal.timeout(120_000),
297
+ undefined,
298
+ { gzipLevel: SCRATCH_ARCHIVE_GZIP_LEVEL },
299
+ ),
294
300
  )
295
301
  const extracted = join(stage, 'packed')
296
302
  await mkdir(extracted)
@@ -0,0 +1,82 @@
1
+ import type { UpgradeRun } from '../kernel/dispatch-upgrade'
2
+ import { readDispatchUpgrade } from '../store/reduced-reads'
3
+ import type { BuildStore } from '../store/types'
4
+
5
+ /** Cadence of the between-tick yield observation. Each step is one canonical
6
+ * reduced read of the repository upgrade value, which reads zero event rows
7
+ * while nothing changed, so the cost per step does not grow with log length,
8
+ * build count or project count. */
9
+ export const YIELD_OBSERVATION_INTERVAL_MS = 200
10
+
11
+ /** Hard step limit of one armed observation: about three minutes at the
12
+ * cadence above, which covers preflight's 120 s readiness deadline plus the
13
+ * launcher's successor spawn. The ordinary tick keeps checking afterwards. */
14
+ export const YIELD_OBSERVATION_LIMIT = 900
15
+
16
+ /** `requested`: durable state holds this run's matching request, or an
17
+ * acceptance not yet adopted. `settled`: nothing more can arrive for this
18
+ * preparation. `waiting`: the preparation is still outstanding. */
19
+ export type YieldObservation = 'waiting' | 'requested' | 'settled'
20
+
21
+ /** Classify one run's durable upgrade state for an armed preparation. The
22
+ * result only decides when to attempt acceptance; the attempt re-reads and
23
+ * validates durable state itself. */
24
+ export function classifyYieldObservation(
25
+ run: UpgradeRun | undefined,
26
+ correlation: string,
27
+ lineage: string,
28
+ ): YieldObservation {
29
+ if (!run || run.prepared?.payload.correlation !== correlation || run.completed) return 'settled'
30
+ if (run.handoff?.payload.correlation === correlation) return 'requested'
31
+ if (run.failure) return 'settled'
32
+ if (!run.request) return 'waiting'
33
+ return run.request.payload.correlation === correlation && run.request.payload.lineage === lineage
34
+ ? 'requested'
35
+ : 'settled'
36
+ }
37
+
38
+ /** One observation step: exactly one reduced read of the upgrade value. */
39
+ export async function observeYield(
40
+ store: Pick<BuildStore, 'getReducerValue'>,
41
+ repo: string,
42
+ run: string,
43
+ correlation: string,
44
+ lineage: string,
45
+ ): Promise<YieldObservation> {
46
+ const state = (await readDispatchUpgrade(store, repo)).value.runs[run]
47
+ return classifyYieldObservation(state, correlation, lineage)
48
+ }
49
+
50
+ /** Watch durable state at a bounded cadence and attempt acceptance at most
51
+ * once. A failed read counts as a step and is retried at the next one. A
52
+ * failed acceptance is left to the ordinary tick, which retries and reports
53
+ * it. `signal` must cover every source that interrupts `sleep`, so an
54
+ * interrupted sleep never turns into a back-to-back read. */
55
+ export async function watchForYieldRequest(opts: {
56
+ observe: () => Promise<YieldObservation>
57
+ accept: () => Promise<void>
58
+ sleep: (ms: number) => Promise<void>
59
+ signal: AbortSignal
60
+ intervalMs?: number
61
+ limit?: number
62
+ }): Promise<'accepted' | 'settled' | 'exhausted' | 'stopped'> {
63
+ const intervalMs = opts.intervalMs ?? YIELD_OBSERVATION_INTERVAL_MS
64
+ const limit = opts.limit ?? YIELD_OBSERVATION_LIMIT
65
+ for (let step = 0; step < limit; step++) {
66
+ if (opts.signal.aborted) return 'stopped'
67
+ await opts.sleep(intervalMs)
68
+ if (opts.signal.aborted) return 'stopped'
69
+ let observation: YieldObservation
70
+ try {
71
+ observation = await opts.observe()
72
+ } catch {
73
+ continue
74
+ }
75
+ if (observation === 'settled') return 'settled'
76
+ if (observation === 'requested') {
77
+ await opts.accept().catch(() => {})
78
+ return 'accepted'
79
+ }
80
+ }
81
+ return 'exhausted'
82
+ }
@@ -18,7 +18,6 @@ import { LocalAccountOwner, renewLocalAccounts } from '../accounts/local-owner'
18
18
  import { accountRedactor, redactAccountStore } from '../store/account-redaction'
19
19
  import { capturedBuildConfig } from '../processes/verify-cycle-config'
20
20
  import { ForgeRequestDeferred } from '../ports/forge-request-context'
21
- import { migrationIdentity } from '../kernel/ticket-migrations'
22
21
  import { recordRuntimeRollback } from './dispatch-handoff'
23
22
  import { syncRollbackRetention } from './dispatch-runtime-use'
24
23
  import { dirname as runtimeDirname } from 'node:path'
@@ -32,6 +31,7 @@ import { authorizeRemoteHandoffs, recoverDispatchDrain } from '../kernel/dispatc
32
31
  import { distributionRoot } from '../distribution'
33
32
  import { readDistributionIdentity } from './installation'
34
33
  import { launchContext } from './dispatch-launch-contract'
34
+ import { observeYield, watchForYieldRequest } from './dispatch-yield-observer'
35
35
  import { DispatchUpgradeController } from './dispatch-upgrade-controller'
36
36
  import { resolveUpgradeTarget } from './dispatch-upgrade-target'
37
37
  import { prepareUpgrade } from './dispatch-upgrade-install'
@@ -1510,6 +1510,8 @@ class DispatchLoop {
1510
1510
 
1511
1511
  private dispatcherTick(resumeCurrent: boolean): Promise<Awaited<ReturnType<Dispatcher['tick']>>> {
1512
1512
  return this.serialize(async () => {
1513
+ // The yield observer may have accepted while this tick was queued.
1514
+ if (this.retirement !== undefined) return emptyTickReport()
1513
1515
  // Refresh before every watch decision. The owner publishes atomically;
1514
1516
  // everything below captures the resulting one snapshot for this tick.
1515
1517
  await this.flushPendingTickFailure()
@@ -4315,10 +4317,6 @@ class DispatchLoop {
4315
4317
  buildSnapshot.capacityBuilds ?? [],
4316
4318
  configSnapshot.config.capacity,
4317
4319
  this.wiring.clock(),
4318
- migrationIdentity(
4319
- repositoryEvents.ticketMigrations,
4320
- configSnapshot.config.tickets.source,
4321
- ),
4322
4320
  {
4323
4321
  urgentClaims: urgentClaimDemand(repositoryEvents),
4324
4322
  openPrs: {
@@ -4829,6 +4827,16 @@ class DispatchLoop {
4829
4827
  request.lineage !== launch.lineage ||
4830
4828
  !this.currentConfig().config.upgrade.automatic
4831
4829
  ) {
4830
+ // A prepared target still awaiting its request: observe for it between
4831
+ // ticks. Arming reuses the read above and never accepts by itself.
4832
+ if (
4833
+ state?.prepared &&
4834
+ state.prepared.payload.lineage === launch.lineage &&
4835
+ !state.failure &&
4836
+ !state.handoff &&
4837
+ !state.request
4838
+ )
4839
+ this.armYieldObservation(state.prepared.payload.correlation, launch.lineage)
4832
4840
  this.abandonUpgradeYield()
4833
4841
  return false
4834
4842
  }
@@ -4938,6 +4946,59 @@ class DispatchLoop {
4938
4946
  return this.adoptUpgradeYield(accepted)
4939
4947
  }
4940
4948
 
4949
+ private yieldObservation?: { correlation: string; stop: AbortController }
4950
+ /** A preparation observed to its step limit is left to ordinary ticks, so
4951
+ * re-arming from a tick cannot extend the observation indefinitely. */
4952
+ private exhaustedYieldObservation?: string
4953
+
4954
+ /** While this run has a prepared target outstanding, observe durable state
4955
+ * for its yield request between ticks at a bounded cadence, and attempt
4956
+ * acceptance through the same serialization as ticks. The observation only
4957
+ * decides when to call `acceptUpgradeYield()`, which re-reads and validates
4958
+ * durable state; ordinary tick cadence is unchanged. */
4959
+ private armYieldObservation(correlation: string, lineage: string): void {
4960
+ if (
4961
+ this.opts.once === true ||
4962
+ this.watchStopped ||
4963
+ this.superseded ||
4964
+ this.retirement !== undefined
4965
+ )
4966
+ return
4967
+ if (
4968
+ this.yieldObservation?.correlation === correlation ||
4969
+ this.exhaustedYieldObservation === correlation
4970
+ )
4971
+ return
4972
+ this.yieldObservation?.stop.abort()
4973
+ const stop = new AbortController()
4974
+ const observation = { correlation, stop }
4975
+ this.yieldObservation = observation
4976
+ // The sleep and the cancellation listen to the same stop sources, so an
4977
+ // interrupted sleep never becomes a back-to-back read.
4978
+ const signals = [stop.signal, this.opts.signal, this.inputStop.signal].filter(
4979
+ (signal): signal is AbortSignal => signal !== undefined,
4980
+ )
4981
+ void watchForYieldRequest({
4982
+ observe: () =>
4983
+ observeYield(this.wiring.store, this.repoIdentity, this.runId, correlation, lineage),
4984
+ accept: () =>
4985
+ this.serialize(async () => {
4986
+ if (this.retirement !== undefined || this.watchStopped || this.superseded) return
4987
+ await this.refreshConfig()
4988
+ await this.acceptUpgradeYield()
4989
+ }),
4990
+ sleep: (ms) => interruptibleSleep(ms, signals),
4991
+ signal: AbortSignal.any(signals),
4992
+ })
4993
+ .then((outcome) => {
4994
+ if (outcome === 'exhausted') this.exhaustedYieldObservation = correlation
4995
+ })
4996
+ .catch(() => {})
4997
+ .finally(() => {
4998
+ if (this.yieldObservation === observation) this.yieldObservation = undefined
4999
+ })
5000
+ }
5001
+
4941
5002
  /** Repository authority may transfer only from a current holder. A record
4942
5003
  * naming another run, or no record, means a peer replaced us. An expired
4943
5004
  * lease that still names us is resolved like any other lapse. */
@@ -5245,6 +5306,7 @@ class DispatchLoop {
5245
5306
  type: 'dispatcher.target-prepared',
5246
5307
  payload: handoff,
5247
5308
  })
5309
+ this.armYieldObservation(handoff.correlation, launch.lineage!)
5248
5310
  return true
5249
5311
  }),
5250
5312
  })
@@ -5383,6 +5445,7 @@ class DispatchLoop {
5383
5445
  }
5384
5446
  } finally {
5385
5447
  this.localHarvestShutdown.abort()
5448
+ this.yieldObservation?.stop.abort()
5386
5449
  await this.upgradeController?.stop()
5387
5450
  await this.stopHooks()
5388
5451
  if (this.retirement) {