@defrex/autobuild 1.0.0-beta.3 → 1.0.0-beta.4

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 (130) hide show
  1. package/SPEC.md +317 -20
  2. package/bin/ab-dispatch-generation.ts +93 -0
  3. package/docs/answering-blocked-builds.md +21 -3
  4. package/docs/architecture.md +166 -7
  5. package/docs/configuration.md +173 -5
  6. package/docs/integration-tree.md +87 -2
  7. package/docs/integration.md +54 -0
  8. package/docs/operator-api.md +58 -5
  9. package/docs/remote-store-protocol.md +4 -1
  10. package/docs/restacking.md +4 -1
  11. package/docs/setup.md +20 -0
  12. package/docs/spec-standard.md +23 -5
  13. package/package.json +3 -3
  14. package/packages/core/src/cli/artifact.ts +5 -4
  15. package/packages/core/src/cli/attention.ts +2 -0
  16. package/packages/core/src/cli/binary-direct.ts +190 -0
  17. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  18. package/packages/core/src/cli/binary.ts +24 -210
  19. package/packages/core/src/cli/build-control.ts +105 -2
  20. package/packages/core/src/cli/context.ts +41 -1
  21. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  22. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  23. package/packages/core/src/cli/dashboard/integration-detail.ts +3 -0
  24. package/packages/core/src/cli/dashboard/model.ts +34 -10
  25. package/packages/core/src/cli/dashboard/render.ts +24 -2
  26. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  27. package/packages/core/src/cli/dispatch-args.ts +53 -0
  28. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  29. package/packages/core/src/cli/dispatch-frontend.ts +52 -5
  30. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  31. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  32. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  33. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  34. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  35. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  36. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  37. package/packages/core/src/cli/dispatch-process.ts +22 -90
  38. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  39. package/packages/core/src/cli/dispatch-repository-feed.ts +5 -1
  40. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  41. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  42. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  43. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  44. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  45. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  46. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  47. package/packages/core/src/cli/dispatch.ts +604 -60
  48. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  49. package/packages/core/src/cli/harvest.ts +28 -11
  50. package/packages/core/src/cli/help.ts +6 -3
  51. package/packages/core/src/cli/installation.ts +5 -3
  52. package/packages/core/src/cli/main-checkout.ts +59 -0
  53. package/packages/core/src/cli/main.ts +15 -45
  54. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  55. package/packages/core/src/cli/repo-state.ts +3 -58
  56. package/packages/core/src/cli/repository-status.ts +67 -3
  57. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  58. package/packages/core/src/cli/status.ts +57 -3
  59. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  60. package/packages/core/src/cli/wait.ts +3 -0
  61. package/packages/core/src/cli/watch.ts +7 -0
  62. package/packages/core/src/config/live.ts +1 -0
  63. package/packages/core/src/config/schema.ts +8 -4
  64. package/packages/core/src/distribution-packaging.ts +116 -0
  65. package/packages/core/src/events/catalog.ts +6 -0
  66. package/packages/core/src/events/payloads.ts +53 -9
  67. package/packages/core/src/events/policy.ts +25 -0
  68. package/packages/core/src/events/repository.ts +184 -4
  69. package/packages/core/src/events/runtime.ts +16 -0
  70. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +2515 -78
  71. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  72. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  73. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  74. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  75. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  76. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  77. package/packages/core/src/kernel/harvest.ts +98 -4
  78. package/packages/core/src/kernel/integration-attention.ts +20 -0
  79. package/packages/core/src/kernel/integration-state.ts +80 -11
  80. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  81. package/packages/core/src/kernel/mixed-version.ts +34 -0
  82. package/packages/core/src/kernel/node-polling.ts +160 -0
  83. package/packages/core/src/kernel/read-facts.ts +40 -5
  84. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  85. package/packages/core/src/kernel/reducer.ts +75 -14
  86. package/packages/core/src/kernel/service-facts.ts +11 -4
  87. package/packages/core/src/operator/presentation.ts +7 -0
  88. package/packages/core/src/operator/query.ts +6 -2
  89. package/packages/core/src/operator/registry.ts +1 -1
  90. package/packages/core/src/plugins/load.ts +4 -1
  91. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  92. package/packages/core/src/ports/forge/contract.ts +29 -0
  93. package/packages/core/src/ports/forge/github.ts +189 -61
  94. package/packages/core/src/ports/forge-failure.ts +1 -0
  95. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  96. package/packages/core/src/ports/runner/session-env.ts +1 -0
  97. package/packages/core/src/ports/types.ts +10 -0
  98. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  99. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  100. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  101. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  102. package/packages/core/src/processes/build-child-exit.ts +5 -26
  103. package/packages/core/src/processes/build-runner.ts +81 -11
  104. package/packages/core/src/processes/dispatcher.ts +254 -23
  105. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  106. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  107. package/packages/core/src/processes/execution-settlement.ts +16 -7
  108. package/packages/core/src/processes/harvest-runner.ts +328 -292
  109. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  110. package/packages/core/src/runtime-identity.ts +22 -3
  111. package/packages/core/src/store/contract.ts +153 -0
  112. package/packages/core/src/store/local/store.ts +197 -72
  113. package/packages/core/src/store/reduced-reads.ts +8 -0
  114. package/packages/core/src/store/reducer-value-shapes.json +5783 -3305
  115. package/packages/core/src/store/remote/client.ts +43 -0
  116. package/packages/core/src/store/repo-state-events.ts +20 -3
  117. package/packages/core/src/store/types.ts +7 -0
  118. package/skills/guide/SKILL.md +231 -23
  119. package/skills/guide/references/integration-tree.md +87 -2
  120. package/skills/guide/references/operator-api.md +53 -4
  121. package/skills/guide/references/plugin-authoring.md +45 -4
  122. package/skills/guide/references/remote-store-protocol.md +4 -1
  123. package/skills/guide/references/restacking.md +4 -1
  124. package/skills/guide/references/setup.md +20 -0
  125. package/skills/guide/references/spec-standard.md +23 -5
  126. package/skills/harvest/SKILL.md +4 -0
  127. package/skills/harvest-review/SKILL.md +4 -0
  128. package/skills/operate/SKILL.md +78 -8
  129. package/skills/spec/SKILL.md +19 -1
  130. package/skills/tickets/SKILL.md +19 -0
@@ -1,3 +1,5 @@
1
+ import { advancePollingActivity } from './node-polling'
2
+ import { integrationFailed } from './integration-state'
1
3
  import {
2
4
  advanceCompatibility,
3
5
  initialCompatibility,
@@ -179,7 +181,17 @@ export interface AutoMergeProjection {
179
181
 
180
182
  export type ObservationRecord = EventPayload<'observation.recorded'>
181
183
 
184
+ export interface DrainExecution {
185
+ correlations?: string[]
186
+ relaunch?: EventPayload<'execution.relaunch-requested'>
187
+ authorization?: EventPayload<'execution.drain-authorized'>
188
+ correlation: string
189
+ ended?: true
190
+ suspended?: true
191
+ }
192
+
182
193
  export interface BuildState {
194
+ drainingExecutions?: Record<string, DrainExecution>
183
195
  compatibility: CompatibilityState
184
196
  compatibilityDeferredBoundary?: number
185
197
  kind?: 'work' | 'node'
@@ -190,6 +202,8 @@ export interface BuildState {
190
202
  nodeOpened?: EventPayload<'node.opened'>
191
203
  nodeRestack?: NodeRestackState
192
204
  integration?: IntegrationState
205
+ pollingActivity?: Record<string, string>
206
+ nodePolling?: EventPayload<'node.poll-checked'> & { checkedAt: string }
193
207
  nodeComparison?: EventPayload<'node.compared'>
194
208
 
195
209
  /**
@@ -261,11 +275,11 @@ export interface BuildState {
261
275
  * `spec.revised` that carries `assets` (§6.3). Empty for historical logs. */
262
276
  pinnedAssets: PinnedAsset[]
263
277
  /** Latest spec artifact rev — `spec.imported`/`spec.authored` set it,
264
- * `spec.revised` bumps it (§6.3: rev N+1 restarts the build from plan). */
278
+ * `spec.revised` bumps it (§6.3: rev N+1 restarts leaves from plan and nodes from collection). */
265
279
  specRev?: number
266
280
  /** seq of the latest `spec.revised`, else 0 — the restart boundary (§6.3).
267
- * Rev N+1 restarts the build from plan, so every approval and result at or
268
- * before this seq describes a spec that no longer exists. Mirrors
281
+ * Rev N+1 restarts leaves from plan and nodes from collection; earlier
282
+ * approvals and results describe the previous spec revision. Mirrors
269
283
  * engine.ts's `restartSeq` (engine.ts:126). */
270
284
  restartSince: number
271
285
  /** `approved` ≡ the latest `plan-review.verdict` is 'approve' (§10);
@@ -365,6 +379,8 @@ export function discardInFlight(state: Pick<BuildState, 'discardRequest'>): bool
365
379
  * trip through `JSON.stringify` — the foundation for incremental advancement
366
380
  * and cached state. */
367
381
  export interface BuildAcc {
382
+ endedExecutionInstances: Record<string, true>
383
+ drainingExecutions: Record<string, DrainExecution>
368
384
  compatibility: CompatibilityState
369
385
  compatibilityDeferredBoundary: number
370
386
  kind?: 'work' | 'node'
@@ -375,6 +391,8 @@ export interface BuildAcc {
375
391
  nodeOpened?: EventPayload<'node.opened'>
376
392
  nodeRestack?: NodeRestackState
377
393
  integration?: IntegrationState
394
+ pollingActivity?: Record<string, string>
395
+ nodePolling?: EventPayload<'node.poll-checked'> & { checkedAt: string }
378
396
  nodeComparison?: EventPayload<'node.compared'>
379
397
 
380
398
  attached: boolean
@@ -430,10 +448,12 @@ export interface BuildAcc {
430
448
  }
431
449
 
432
450
  /** Bump when `BuildAcc`'s shape or the fold's semantics change. */
433
- export const BUILD_REDUCER_VERSION = 18
451
+ export const BUILD_REDUCER_VERSION = 21
434
452
 
435
453
  function initialBuildAcc(): BuildAcc {
436
454
  return {
455
+ endedExecutionInstances: {},
456
+ drainingExecutions: {},
437
457
  compatibility: initialCompatibility(),
438
458
  compatibilityDeferredBoundary: 0,
439
459
  attached: false,
@@ -479,9 +499,47 @@ function initialBuildAcc(): BuildAcc {
479
499
  function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
480
500
  advanceCompatibility(acc.compatibility, events)
481
501
  events = projectEvents(events)
482
- for (const event of events)
502
+ for (const event of events) {
483
503
  if (event.type === 'build.compatibility-deferred')
484
504
  acc.compatibilityDeferredBoundary = event.payload.boundary
505
+ if (event.type === 'execution.drain-authorized') {
506
+ const previous = acc.drainingExecutions[event.payload.instance]
507
+ if (
508
+ previous?.correlation === event.payload.correlation ||
509
+ previous?.correlations?.includes(event.payload.correlation)
510
+ )
511
+ continue
512
+ acc.drainingExecutions[event.payload.instance] = {
513
+ ...previous,
514
+ correlations: [
515
+ ...(previous?.correlations ?? []),
516
+ ...(previous ? [previous.correlation] : []),
517
+ ],
518
+ correlation: event.payload.correlation,
519
+ ...(acc.endedExecutionInstances[event.payload.instance]
520
+ ? { ended: true as const }
521
+ : { authorization: event.payload }),
522
+ }
523
+ }
524
+ if (event.type === 'execution.relaunch-requested') {
525
+ const entry = acc.drainingExecutions[event.payload.instance]
526
+ if (entry?.authorization?.correlation === event.payload.correlation && !entry.ended)
527
+ entry.relaunch = event.payload
528
+ }
529
+ if (event.type === 'session.suspended' && event.payload.cause === 'shutdown')
530
+ for (const entry of Object.values(acc.drainingExecutions))
531
+ if (entry.authorization && !entry.ended) entry.suspended = true
532
+ if (event.type === 'execution.ended') acc.endedExecutionInstances[event.payload.instance] = true
533
+ if (event.type === 'execution.ended' && acc.drainingExecutions[event.payload.instance]) {
534
+ const entry = acc.drainingExecutions[event.payload.instance]!
535
+ entry.ended = true
536
+ delete entry.authorization
537
+ }
538
+ if (event.type === 'execution.drain-settled') {
539
+ const entry = acc.drainingExecutions[event.payload.instance]
540
+ if (entry?.correlation === event.payload.correlation) delete entry.authorization
541
+ }
542
+ }
485
543
  let attached = acc.attached
486
544
  let pausedFlag = acc.pausedFlag
487
545
  let terminal = acc.terminal
@@ -543,6 +601,8 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
543
601
 
544
602
  let lastEvent = acc.lastEvent
545
603
  for (const event of events) {
604
+ acc.pollingActivity ??= {}
605
+ advancePollingActivity(acc.pollingActivity, event)
546
606
  acc.landing ??= {}
547
607
  if (event.type === 'build.janitor-attempt-failed')
548
608
  acc.janitor = {
@@ -580,6 +640,9 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
580
640
  case 'node.opened':
581
641
  acc.nodeOpened = event.payload
582
642
  break
643
+ case 'node.poll-checked':
644
+ acc.nodePolling = { ...event.payload, checkedAt: event.ts }
645
+ break
583
646
  case 'node.compared':
584
647
  acc.nodeComparison = event.payload
585
648
  break
@@ -738,7 +801,7 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
738
801
  case 'spec.revised':
739
802
  specRev = event.payload.artifact.rev
740
803
  if (event.payload.assets !== undefined) pinnedAssets = event.payload.assets
741
- // §6.3: rev N+1 restarts the build from plan. The restart boundary
804
+ // §6.3: rev N+1 restarts leaves from plan and nodes from collection. The restart boundary
742
805
  // invalidates every approval and result at or before it, so it is also
743
806
  // a verify cycle boundary. Finalize post-steps remain in full-log
744
807
  // history; consumers use this boundary to select the current spec,
@@ -1146,14 +1209,7 @@ function finishBuild(acc: BuildAcc): BuildState {
1146
1209
  terminal ??
1147
1210
  (pausedFlag
1148
1211
  ? 'paused'
1149
- : acc.openEscalations.length > 0 ||
1150
- (acc.integration?.cycle &&
1151
- acc.nodeComparison?.headSha === acc.integration.cycle.head &&
1152
- acc.nodeComparison?.parentSha === acc.integration.cycle.parent &&
1153
- acc.verify.results.some(
1154
- (result) =>
1155
- result.restackId === acc.integration!.cycle!.id && result.outcome === 'fail',
1156
- ))
1212
+ : acc.openEscalations.length > 0 || integrationFailed(acc)
1157
1213
  ? 'blocked'
1158
1214
  : acc.kind === 'node' && acc.nodeOpened !== undefined
1159
1215
  ? 'collecting'
@@ -1171,6 +1227,8 @@ function finishBuild(acc: BuildAcc): BuildState {
1171
1227
  mergedSha: acc.mergedSha,
1172
1228
  nodeOpened: acc.nodeOpened,
1173
1229
  integration: acc.integration,
1230
+ pollingActivity: acc.pollingActivity,
1231
+ nodePolling: acc.nodePolling,
1174
1232
  nodeComparison: acc.nodeComparison,
1175
1233
  nodeRestack: acc.nodeRestack,
1176
1234
  status,
@@ -1193,6 +1251,9 @@ function finishBuild(acc: BuildAcc): BuildState {
1193
1251
  lastSeq: Math.max(lastEvent?.seq ?? 0, acc.compatibility.lastSeq),
1194
1252
  compatibility: structuredClone(acc.compatibility),
1195
1253
  compatibilityDeferredBoundary: acc.compatibilityDeferredBoundary,
1254
+ ...(Object.keys(acc.drainingExecutions).length
1255
+ ? { drainingExecutions: structuredClone(acc.drainingExecutions) }
1256
+ : {}),
1196
1257
  pinnedAssets: acc.pinnedAssets,
1197
1258
  specRev: acc.specRev,
1198
1259
  restartSince: acc.restartSince,
@@ -48,7 +48,7 @@ export interface BuildDelegationFacts {
48
48
  export interface HarvestDelegationFacts {
49
49
  lastSeq: number
50
50
  runs: Record<string, true>
51
- sessions: Record<string, Record<string, SessionFacts>>
51
+ sessions: Record<string, Record<string, SessionFacts & { suspended?: true }>>
52
52
  authorizations: Record<string, Record<string, { seq: number; leaseHolder: string }>>
53
53
  releases: Record<string, string[]>
54
54
  endings: Record<string, EndingFact[]>
@@ -82,7 +82,7 @@ export const harvestDelegationReducer = defineReducer<
82
82
  RepositoryEvent,
83
83
  HarvestDelegationFacts
84
84
  >({
85
- version: 1,
85
+ version: 2,
86
86
  initial: () => ({
87
87
  lastSeq: 0,
88
88
  runs: {},
@@ -104,7 +104,11 @@ export const harvestDelegationReducer = defineReducer<
104
104
  leaseHolder: event.payload.leaseHolder,
105
105
  }
106
106
  }
107
- if (event.type === 'harvest.session.started' || event.type === 'harvest.session.ended') {
107
+ if (
108
+ event.type === 'harvest.session.started' ||
109
+ event.type === 'harvest.session.ended' ||
110
+ event.type === 'harvest.session.suspended'
111
+ ) {
108
112
  const runKey = delegationFactKey(event.payload.run)
109
113
  acc.sessions[runKey] ??= {}
110
114
  const run = acc.sessions[runKey]!
@@ -112,7 +116,10 @@ export const harvestDelegationReducer = defineReducer<
112
116
  run[sessionKey] ??= { starts: [], endings: [] }
113
117
  const session = run[sessionKey]!
114
118
  if (event.type === 'harvest.session.started') session.starts.push(event.seq)
115
- else session.endings.push({ seq: event.seq, at: event.ts })
119
+ else {
120
+ session.endings.push({ seq: event.seq, at: event.ts })
121
+ if (event.type === 'harvest.session.suspended') session.suspended = true
122
+ }
116
123
  }
117
124
  if (event.type === 'harvest.execution.released' || event.type === 'harvest.execution.ended') {
118
125
  const key = delegationFactKey(event.payload.execution)
@@ -26,3 +26,10 @@ export type {
26
26
 
27
27
  export type { IntegrationDetail, IntegrationChild } from '../cli/dashboard/integration-detail'
28
28
  export { displayText } from '../cli/dashboard/cells'
29
+
30
+ export { formatHandoff } from '../cli/dashboard/handoff'
31
+ export type { DashboardHandoff } from '../cli/dashboard/handoff'
32
+
33
+ export { formatRollback } from '../cli/dashboard/rollback'
34
+ export type { DashboardRollback } from '../cli/dashboard/rollback'
35
+ export { handPushedLabel, handPushedText } from '../cli/dashboard/hand-pushed'
@@ -1,4 +1,5 @@
1
1
  import { migrationIdentity } from '../kernel/ticket-migrations'
2
+ import { enrichDrainingRow, projectHandoffs } from '../cli/dashboard/handoff'
2
3
  import { enrichIntegrationRows } from '../cli/dashboard/integration-row'
3
4
  import { dispatchCapacity, type CapacityBuild } from '../kernel/dispatch-capacity'
4
5
  import { forgeReadinessWarnings } from '../kernel/dispatch-status'
@@ -278,7 +279,7 @@ export async function getOperatorBuild(opts: {
278
279
  const record = await requireBuild(opts.store, opts.repo, opts.slug)
279
280
  const facts = (await readBuildFacts(opts.store, opts.slug)).value
280
281
  const state = facts.state
281
- const { config } = await effectiveConfig(opts.store, opts.repo)
282
+ const { config, repositoryEvents } = await effectiveConfig(opts.store, opts.repo)
282
283
  let dashboardRow: DashboardBuild | null = null
283
284
  if (!projectsNoDashboardRow(state)) {
284
285
  const pinned = await readPinnedConfig(opts.store, opts.slug, config)
@@ -286,7 +287,10 @@ export async function getOperatorBuild(opts: {
286
287
  // Implied by the gate; kept as an explicit check (not an assertion) so the
287
288
  // code never lies if `effectiveStatus` and `projectBuild` ever drift.
288
289
  if (row !== null) {
289
- dashboardRow = decorateWithPinnedMeta(row, pinned)
290
+ dashboardRow = enrichDrainingRow(
291
+ decorateWithPinnedMeta(row, pinned),
292
+ projectHandoffs(repositoryEvents.upgrades).draining,
293
+ )
290
294
  if (row.integrationDetail) {
291
295
  const records = await opts.store.listBuildsForRepo(opts.repo)
292
296
  const digests = await readBuildDigests(opts.store, opts.repo)
@@ -625,7 +625,7 @@ export const TOOLS: readonly ToolEntry[] = [
625
625
  ),
626
626
  defineTool(
627
627
  'builds.answer',
628
- 'Answer a blocked build’s open escalations: guidance text, a bare retry, a dismissal of the cited findings, a review-round ceiling, or a spec revision (destructive — replaces the spec and restarts from plan).',
628
+ 'Answer a blocked build’s open escalations: guidance text, a bare retry, a dismissal of the cited findings, a review-round ceiling, or a spec revision (destructive — replaces the spec). Leaves require an escalation and restart from plan; idle collecting or verification-failed nodes may revise without an escalation and recollect for verification.',
629
629
  buildsAnswerInput,
630
630
  'The controlBuild answer result: {kind: "answered", slug, count, resolution, resumed, …} describing how many escalations were answered and with what.',
631
631
  async (raw, ctx) => {
@@ -1,3 +1,4 @@
1
+ import { snapshotPlugin } from './runtime-snapshot'
1
2
  import { existsSync } from 'node:fs'
2
3
  import { dirname, isAbsolute, join, resolve } from 'node:path'
3
4
  import { pathToFileURL } from 'node:url'
@@ -241,7 +242,9 @@ export async function attemptPlugin(
241
242
  const located = { ...initial, resolved, ...(resolvedFrom !== undefined ? { resolvedFrom } : {}) }
242
243
  let namespace: Record<string, unknown>
243
244
  try {
244
- namespace = (await import(importUrl(resolved))) as Record<string, unknown>
245
+ namespace = (await import(
246
+ importUrl(await snapshotPlugin(resolved, resolutionKind === 'repo-path'))
247
+ )) as Record<string, unknown>
245
248
  } catch (error) {
246
249
  return failed(
247
250
  located,
@@ -0,0 +1,128 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { renameSync } from 'node:fs'
3
+ import { mkdir, mkdtemp, realpath, rm, writeFile, readFile, stat, copyFile } from 'node:fs/promises'
4
+ import { existsSync } from 'node:fs'
5
+ import { dirname, join, relative } from 'node:path'
6
+ import { distributionRoot } from '../distribution'
7
+ import {
8
+ cachedRuntime,
9
+ RUNTIME_CONFIG,
10
+ validateCoreConfigs,
11
+ withCacheLock,
12
+ } from '../cli/dispatch-runtime-cache'
13
+ import { claimRuntimeForProcess, pruneRuntimes } from '../cli/dispatch-runtime-use'
14
+ import {
15
+ copyDependencies,
16
+ copySnapshotTree,
17
+ excludedSnapshotNames,
18
+ readManifest,
19
+ scanDependencies,
20
+ standalonePluginManifest,
21
+ treeDigest,
22
+ } from '../cli/dispatch-runtime-dependencies'
23
+
24
+ const loaded = new Map<string, Promise<string>>()
25
+ /** Selection remains repository-first. Only evaluation relocates, giving native
26
+ * ESM and CommonJS one canonical SDK without loader hooks or source rewriting. */
27
+ export async function snapshotPlugin(resolved: string, local: boolean): Promise<string> {
28
+ const core = await cachedRuntime(distributionRoot())
29
+ if (!core) return resolved
30
+ claimRuntimeForProcess(core.root)
31
+ // Short-lived phase CLIs reclaim dead users during a resident generation.
32
+ pruneRuntimes(dirname(dirname(core.root)))
33
+ const key = `${core.root}:${resolved}`
34
+ let pending = loaded.get(key)
35
+ if (!pending) {
36
+ pending = prepare(resolved, local, core.root)
37
+ loaded.set(key, pending)
38
+ pending.catch(() => loaded.delete(key))
39
+ }
40
+ return pending
41
+ }
42
+ async function prepare(selected: string, local: boolean, core: string): Promise<string> {
43
+ selected = await realpath(selected)
44
+ let boundary = dirname(selected)
45
+ while (!existsSync(join(boundary, 'package.json'))) {
46
+ const parent = dirname(boundary)
47
+ if (parent === boundary) {
48
+ boundary = dirname(selected)
49
+ break
50
+ }
51
+ boundary = parent
52
+ }
53
+ // A standalone module has no declared edges; never invent a surrounding
54
+ // monorepo as its package boundary.
55
+ const standalone =
56
+ !existsSync(join(boundary, 'package.json')) ||
57
+ (local && (existsSync(join(boundary, 'autobuild.toml')) || existsSync(join(boundary, '.git'))))
58
+ const hasManifest = !standalone
59
+ const cache = dirname(dirname(core))
60
+ const extensions = join(cache, 'extensions')
61
+ await mkdir(extensions, { recursive: true })
62
+ const stage = await mkdtemp(join(extensions, '.preparing-'))
63
+ try {
64
+ const tree = join(stage, 'distribution')
65
+ const root = join(tree, 'package')
66
+ const files = new Set<string>()
67
+ const manifest = hasManifest
68
+ ? undefined
69
+ : await standalonePluginManifest(selected, boundary, files)
70
+ const fingerprint = async () => {
71
+ if (!manifest) return treeDigest(boundary, excludedSnapshotNames)
72
+ const hash = createHash('sha256')
73
+ const current = new Set<string>()
74
+ await standalonePluginManifest(selected, boundary, current)
75
+ for (const file of [...current].sort()) {
76
+ hash.update(JSON.stringify([relative(boundary, file), (await stat(file)).mode & 0o111]))
77
+ hash.update(await readFile(file))
78
+ }
79
+ return hash.digest('hex')
80
+ }
81
+ const before = await fingerprint()
82
+ const scan = () =>
83
+ scanDependencies(boundary, {
84
+ dev: local && !manifest,
85
+ coreRoot: core,
86
+ ...(manifest ? { manifest } : {}),
87
+ })
88
+ const graph = await scan()
89
+ if (manifest) {
90
+ await mkdir(root, { recursive: true })
91
+ for (const file of files) {
92
+ const target = join(root, relative(boundary, file))
93
+ await mkdir(dirname(target), { recursive: true })
94
+ await copyFile(file, target)
95
+ }
96
+ } else await copySnapshotTree(boundary, root)
97
+ await writeFile(join(tree, 'tsconfig.json'), RUNTIME_CONFIG)
98
+ await writeFile(join(root, 'tsconfig.json'), RUNTIME_CONFIG)
99
+ if (manifest) await writeFile(join(root, 'package.json'), JSON.stringify(manifest))
100
+ if (hasManifest) {
101
+ const manifest = await readManifest(root)
102
+ if (manifest.name === '@defrex/autobuild') {
103
+ manifest.name = 'autobuild-local-plugin-snapshot'
104
+ delete manifest.exports
105
+ await writeFile(join(root, 'package.json'), JSON.stringify(manifest))
106
+ }
107
+ }
108
+ await validateCoreConfigs(root, ['.'])
109
+ await copyDependencies(graph, root, core)
110
+ if (before !== (await fingerprint()) || graph.fingerprint !== (await scan()).fingerprint)
111
+ throw new Error(`plugin changed while preparing snapshot: ${selected}`)
112
+ const digest = await treeDigest(tree, new Set(), core)
113
+ const destination = join(extensions, digest)
114
+ await writeFile(join(stage, 'extension.json'), JSON.stringify({ version: 1, core, digest }))
115
+ claimRuntimeForProcess(core, destination)
116
+ if (
117
+ existsSync(destination) &&
118
+ (await treeDigest(join(destination, 'distribution'), new Set(), core)) !== digest
119
+ )
120
+ throw new Error(`corrupt plugin snapshot: ${destination}`)
121
+ withCacheLock(cache, () => {
122
+ if (!existsSync(destination)) renameSync(stage, destination)
123
+ })
124
+ return join(destination, 'distribution', 'package', relative(boundary, selected))
125
+ } finally {
126
+ await rm(stage, { recursive: true, force: true })
127
+ }
128
+ }
@@ -90,6 +90,35 @@ async function pushAndOpen(harness: ForgeContractHarness): Promise<{
90
90
  */
91
91
  export function describeForgeContract(name: string, factory: ForgeContractFactory): void {
92
92
  describe(`Forge contract: ${name}`, () => {
93
+ test('optional observation scope preserves concurrent reads and fresh mutation readback', async () => {
94
+ await withForge(
95
+ factory,
96
+ undefined,
97
+ async ({ forge, workspacePath, head, base, title, body }) => {
98
+ if (!forge.withReadScope || !forge.closePr) return
99
+ const pr = await forge.openPr({ workspacePath, head, base, title, body })
100
+ await forge.withReadScope(async () => {
101
+ const states = await Promise.all([
102
+ forge.getPrState(workspacePath, pr.number),
103
+ forge.getPrState(workspacePath, pr.number),
104
+ ])
105
+ expect(states[0]).toEqual(states[1])
106
+ await forge.closePr!(workspacePath, pr.number)
107
+ expect((await forge.getPrState(workspacePath, pr.number)).state).toBe('closed')
108
+ })
109
+ await forge.withReadScope(async () => {
110
+ expect((await forge.getPrState(workspacePath, pr.number)).state).toBe('closed')
111
+ })
112
+ await expect(
113
+ forge.withReadScope(async () => {
114
+ throw new Error('scope teardown')
115
+ }),
116
+ ).rejects.toThrow('scope teardown')
117
+ expect((await forge.getPrState(workspacePath, pr.number)).state).toBe('closed')
118
+ },
119
+ )
120
+ })
121
+
93
122
  test('optional request observation registers and disposes without requiring legacy adapters', async () => {
94
123
  await withForge(factory, undefined, async ({ forge }) => {
95
124
  if (!forge.observeRequests) return