@defrex/autobuild 1.0.0-beta.2 → 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 (145) hide show
  1. package/SPEC.md +342 -23
  2. package/bin/ab-dispatch-generation.ts +93 -0
  3. package/docs/answering-blocked-builds.md +21 -3
  4. package/docs/architecture.md +170 -7
  5. package/docs/configuration.md +173 -5
  6. package/docs/integration-tree.md +91 -4
  7. package/docs/integration.md +54 -0
  8. package/docs/operator-api.md +58 -5
  9. package/docs/remote-store-protocol.md +9 -1
  10. package/docs/remote-ticket-protocol.md +5 -0
  11. package/docs/restacking.md +4 -1
  12. package/docs/setup.md +24 -0
  13. package/docs/spec-standard.md +94 -5
  14. package/docs/ticket-migration.md +50 -4
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/artifact.ts +5 -4
  17. package/packages/core/src/cli/attention.ts +2 -0
  18. package/packages/core/src/cli/binary-direct.ts +190 -0
  19. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  20. package/packages/core/src/cli/binary.ts +24 -210
  21. package/packages/core/src/cli/build-control.ts +108 -5
  22. package/packages/core/src/cli/context.ts +41 -1
  23. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  24. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  25. package/packages/core/src/cli/dashboard/integration-detail.ts +11 -6
  26. package/packages/core/src/cli/dashboard/integration-row.ts +15 -8
  27. package/packages/core/src/cli/dashboard/model.ts +41 -10
  28. package/packages/core/src/cli/dashboard/render.ts +24 -2
  29. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  30. package/packages/core/src/cli/dispatch-args.ts +53 -0
  31. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  32. package/packages/core/src/cli/dispatch-frontend.ts +57 -5
  33. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  34. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  35. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  36. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  38. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  39. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  40. package/packages/core/src/cli/dispatch-process.ts +22 -90
  41. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +6 -1
  43. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  44. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  45. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  46. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  47. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  48. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  49. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  50. package/packages/core/src/cli/dispatch.ts +609 -60
  51. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  52. package/packages/core/src/cli/harvest.ts +28 -11
  53. package/packages/core/src/cli/help.ts +7 -3
  54. package/packages/core/src/cli/installation.ts +5 -3
  55. package/packages/core/src/cli/main-checkout.ts +59 -0
  56. package/packages/core/src/cli/main.ts +26 -53
  57. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  58. package/packages/core/src/cli/repo-state.ts +3 -58
  59. package/packages/core/src/cli/repository-status.ts +74 -4
  60. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  61. package/packages/core/src/cli/status.ts +57 -3
  62. package/packages/core/src/cli/ticket.ts +35 -11
  63. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  64. package/packages/core/src/cli/wait.ts +3 -0
  65. package/packages/core/src/cli/watch.ts +7 -0
  66. package/packages/core/src/config/live.ts +1 -0
  67. package/packages/core/src/config/schema.ts +8 -4
  68. package/packages/core/src/distribution-packaging.ts +116 -0
  69. package/packages/core/src/events/catalog.ts +6 -0
  70. package/packages/core/src/events/payloads.ts +55 -9
  71. package/packages/core/src/events/policy.ts +26 -0
  72. package/packages/core/src/events/repository.ts +205 -4
  73. package/packages/core/src/events/runtime.ts +16 -0
  74. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +6537 -4053
  75. package/packages/core/src/kernel/change-presence.ts +7 -1
  76. package/packages/core/src/kernel/dispatch-capacity.ts +12 -4
  77. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  78. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  79. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  80. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  81. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  82. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  83. package/packages/core/src/kernel/harvest.ts +98 -4
  84. package/packages/core/src/kernel/integration-attention.ts +20 -0
  85. package/packages/core/src/kernel/integration-completeness.ts +54 -16
  86. package/packages/core/src/kernel/integration-state.ts +80 -11
  87. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  88. package/packages/core/src/kernel/mixed-version.ts +34 -0
  89. package/packages/core/src/kernel/node-parent.ts +35 -10
  90. package/packages/core/src/kernel/node-polling.ts +160 -0
  91. package/packages/core/src/kernel/read-facts.ts +47 -5
  92. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  93. package/packages/core/src/kernel/reducer.ts +75 -14
  94. package/packages/core/src/kernel/service-facts.ts +11 -4
  95. package/packages/core/src/kernel/ticket-migrations.ts +139 -0
  96. package/packages/core/src/operator/presentation.ts +7 -0
  97. package/packages/core/src/operator/query.ts +13 -3
  98. package/packages/core/src/operator/registry.ts +1 -1
  99. package/packages/core/src/operator/tickets.ts +30 -26
  100. package/packages/core/src/plugins/load.ts +4 -1
  101. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  102. package/packages/core/src/ports/forge/contract.ts +29 -0
  103. package/packages/core/src/ports/forge/github.ts +189 -61
  104. package/packages/core/src/ports/forge-failure.ts +1 -0
  105. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  106. package/packages/core/src/ports/runner/session-env.ts +1 -0
  107. package/packages/core/src/ports/tickets/linear.ts +180 -12
  108. package/packages/core/src/ports/tickets/migration.ts +92 -9
  109. package/packages/core/src/ports/types.ts +17 -0
  110. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  111. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  112. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  113. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  114. package/packages/core/src/processes/build-child-exit.ts +5 -26
  115. package/packages/core/src/processes/build-runner.ts +81 -11
  116. package/packages/core/src/processes/dispatcher.ts +418 -59
  117. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  118. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  119. package/packages/core/src/processes/execution-settlement.ts +16 -7
  120. package/packages/core/src/processes/harvest-runner.ts +328 -292
  121. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  122. package/packages/core/src/runtime-identity.ts +22 -3
  123. package/packages/core/src/store/contract.ts +183 -0
  124. package/packages/core/src/store/local/store.ts +197 -72
  125. package/packages/core/src/store/reduced-reads.ts +8 -0
  126. package/packages/core/src/store/reducer-value-shapes.json +8915 -6344
  127. package/packages/core/src/store/remote/client.ts +43 -0
  128. package/packages/core/src/store/repo-state-events.ts +21 -3
  129. package/packages/core/src/store/types.ts +7 -0
  130. package/packages/core/src/testing/dispatch-read-budget.ts +3 -2
  131. package/skills/guide/SKILL.md +234 -24
  132. package/skills/guide/references/integration-tree.md +91 -4
  133. package/skills/guide/references/operator-api.md +53 -4
  134. package/skills/guide/references/plugin-authoring.md +45 -4
  135. package/skills/guide/references/remote-store-protocol.md +9 -1
  136. package/skills/guide/references/remote-ticket-protocol.md +5 -0
  137. package/skills/guide/references/restacking.md +4 -1
  138. package/skills/guide/references/setup.md +24 -0
  139. package/skills/guide/references/spec-standard.md +94 -5
  140. package/skills/guide/references/ticket-migration.md +50 -4
  141. package/skills/harvest/SKILL.md +4 -0
  142. package/skills/harvest-review/SKILL.md +4 -0
  143. package/skills/operate/SKILL.md +78 -8
  144. package/skills/spec/SKILL.md +35 -5
  145. package/skills/tickets/SKILL.md +19 -0
@@ -1,3 +1,6 @@
1
+ import { migrationIdentity } from '../kernel/ticket-migrations'
2
+ import { dispatchUpgradeReducer, type DispatchUpgradeState } from '../kernel/dispatch-upgrade'
3
+ import { formatRuntimeIdentity } from '../events/runtime'
1
4
  import {
2
5
  dispatchCapacity,
3
6
  type DispatchCapacity,
@@ -29,6 +32,8 @@ import { withSessionlessStore, type StoreOpener } from './store-opening'
29
32
  /** Script-facing projection returned by `ab repository status`. */
30
33
  export interface RepositoryStatus extends DispatchSettings {
31
34
  repo: string
35
+ upgrades: DispatchUpgradeState
36
+ rollbackHold?: DispatchUpgradeState['lastRollback']
32
37
  capacity?: DispatchCapacity
33
38
  warningLines?: string[]
34
39
  dispatcher: DispatcherLiveness
@@ -109,6 +114,8 @@ export function projectRepositoryStatus(
109
114
  : {}),
110
115
  ...(active === undefined ? {} : { ticketSourceDegradation: active }),
111
116
  repo,
117
+ upgrades: dispatchUpgradeReducer.reduce(events),
118
+ rollbackHold: effectiveRollbackHold(dispatchUpgradeReducer.reduce(events), dispatcher),
112
119
  ...(warningLines.length ? { warningLines } : {}),
113
120
  dispatcher,
114
121
  ...(() => {
@@ -141,6 +148,8 @@ export function repositoryStatusFromFacts(
141
148
  const warningLines = facts.status ? forgeReadinessWarnings(facts.status) : []
142
149
  return {
143
150
  repo,
151
+ upgrades: facts.upgrades,
152
+ rollbackHold: effectiveRollbackHold(facts.upgrades, dispatcher),
144
153
  ...(warningLines.length ? { warningLines } : {}),
145
154
  dispatcher,
146
155
  ...(() => {
@@ -175,6 +184,18 @@ export function repositoryStatusFromFacts(
175
184
  }
176
185
  }
177
186
 
187
+ function effectiveRollbackHold(upgrades: DispatchUpgradeState, dispatcher: DispatcherLiveness) {
188
+ const run = dispatcher.holder ?? dispatcher.expiredHolder ?? dispatcher.latestRun
189
+ const lineage = run && upgrades.lineages[run.run]
190
+ return lineage ? upgrades.holds[lineage] : undefined
191
+ }
192
+
193
+ function formatRepositoryDispatcherIdentity(
194
+ run: NonNullable<DispatcherLiveness['latestRun']>,
195
+ ): string {
196
+ return `${formatDispatcherIdentity(run)}; ${formatRuntimeIdentity(run.runtime)}`
197
+ }
198
+
178
199
  export function renderRepositoryStatus(status: RepositoryStatus): string[] {
179
200
  const tick = (
180
201
  status.dispatcher.holder ??
@@ -186,8 +207,50 @@ export function renderRepositoryStatus(status: RepositoryStatus): string[] {
186
207
  const setting = (enabled: boolean): string => (enabled ? 'ON' : 'OFF')
187
208
  const active = status.ticketSourceDegradation
188
209
  return [
210
+ ...(status.upgrades.lastRollback
211
+ ? [
212
+ `runtime rollback: ${status.upgrades.lastRollback.payload.failed.version} → ${status.upgrades.lastRollback.payload.restored.version}; ${status.upgrades.lastRollback.payload.reason}`,
213
+ ]
214
+ : []),
215
+ ...(status.rollbackHold
216
+ ? [
217
+ `held runtime: ${status.rollbackHold.payload.failed.version}; target ${status.rollbackHold.payload.target.key}`,
218
+ ]
219
+ : []),
220
+ ...Object.entries(status.upgrades.runs).flatMap(([run, state]) => {
221
+ const event =
222
+ state.completed ??
223
+ state.failure ??
224
+ state.handoff ??
225
+ state.request ??
226
+ state.prepared ??
227
+ state.detected
228
+ const resolved = state.resolved?.payload.target
229
+ const lines = resolved
230
+ ? [
231
+ `resolved target ${run}: ${resolved.mode}; base ${resolved.base ?? '-'}; source ${resolved.source}${resolved.sha ? ` at ${resolved.sha}` : ''}`,
232
+ ]
233
+ : []
234
+ if (!event) return lines
235
+ const target = event.payload.target
236
+ const overlap =
237
+ state.handoff && state.request && !state.completed
238
+ ? [
239
+ `handoff ${run} (${state.handoff.payload.from.version}) → ${state.request.payload.successor} (${state.handoff.payload.to.version}): ${state.request.payload.mode}; ${state.takeover ? 'taken over' : 'awaiting takeover'}; draining ${
240
+ Object.entries(state.outstanding)
241
+ .map(([slug, instance]) => `${slug} (${instance})`)
242
+ .join(', ') || 'none'
243
+ }; deadline ${state.deadline ?? 'unknown'}`,
244
+ ]
245
+ : []
246
+ return [
247
+ ...lines,
248
+ ...overlap,
249
+ `upgrade ${run}: ${event.type.slice('dispatcher.'.length)}; ${target.mode} ${target.version ?? target.source}; source ${target.source}${target.sha ? ` at ${target.sha}` : ''}${event.type === 'dispatcher.upgrade-failed' ? `; ${event.payload.reason}` : ''}`,
250
+ ]
251
+ }),
189
252
  requests
190
- ? `forge requests: ${requests.total} (${requests.unattributed} unattributed)${hotspot ? `; hotspot ${hotspot}` : ''}`
253
+ ? `forge requests: ${requests.total}${requests.restPrimary === undefined ? '' : `; REST primary ${requests.restPrimary}`}${requests.restNotModified === undefined ? '' : `; REST 304 ${requests.restNotModified}`}${requests.graphql === undefined ? '' : `; GraphQL ${requests.graphql}`} (${requests.unattributed} unattributed)${hotspot ? `; hotspot ${hotspot}` : ''}`
191
254
  : 'forge requests: unavailable',
192
255
  ...(status.forgeDegradation
193
256
  ? [
@@ -206,9 +269,11 @@ export function renderRepositoryStatus(status: RepositoryStatus): string[] {
206
269
  ]
207
270
  : []),
208
271
  ...(status.warningLines ?? []),
209
- `dispatcher: ${status.dispatcher.state}${status.dispatcher.holder ? ` — ${formatDispatcherIdentity(status.dispatcher.holder)}` : ' — no dispatcher holds the repository'}`,
272
+ `dispatcher: ${status.dispatcher.state}${status.dispatcher.holder ? ` — ${formatRepositoryDispatcherIdentity(status.dispatcher.holder)}` : ' — no dispatcher holds the repository'}`,
210
273
  ...(status.dispatcher.expiredHolder
211
- ? [`expired dispatcher: ${formatDispatcherIdentity(status.dispatcher.expiredHolder)}`]
274
+ ? [
275
+ `expired dispatcher: ${formatRepositoryDispatcherIdentity(status.dispatcher.expiredHolder)}`,
276
+ ]
212
277
  : []),
213
278
  ...[status.dispatcher.holder ?? status.dispatcher.expiredHolder].flatMap((run) =>
214
279
  run
@@ -266,7 +331,12 @@ export async function readRepositoryCapacity(
266
331
  provisioning: build.provisionMarker !== undefined,
267
332
  })
268
333
  }
269
- return dispatchCapacity(builds, config.capacity, now)
334
+ return dispatchCapacity(
335
+ builds,
336
+ config.capacity,
337
+ now,
338
+ migrationIdentity(facts.ticketMigrations, config.tickets.source),
339
+ )
270
340
  }
271
341
  }
272
342
  return undefined
@@ -0,0 +1,16 @@
1
+ import { distributionRoot } from '../distribution'
2
+ import { ownCachedRuntime } from './dispatch-runtime-use'
3
+ /** Every cached Bun entry pins compiler resolution before evaluating any JS. */
4
+ export function bunRuntimeArguments(entry: string, args: string[] = []): string[] {
5
+ const root = distributionRoot()
6
+ return ownCachedRuntime(root)
7
+ ? [
8
+ process.execPath,
9
+ '--no-install',
10
+ '--tsconfig-override',
11
+ `${root}/tsconfig.json`,
12
+ entry,
13
+ ...args,
14
+ ]
15
+ : [process.execPath, entry, ...args]
16
+ }
@@ -1,3 +1,7 @@
1
+ import { nodeActivityKey, nodePollingSchedule } from '../kernel/node-polling'
2
+ import { buildReadFactsReducer } from '../kernel/read-facts'
3
+ import { formatRuntimeIdentity } from '../events/runtime'
4
+ import { projectHandPushed, handPushedText, type HandPushedChange } from './dashboard/hand-pushed'
1
5
  import { compatibilityDiagnostic } from '../kernel/mixed-version'
2
6
  import { indexLog } from '../kernel/log-index'
3
7
  import { projectTree, type TreeProjection } from './dashboard/tree'
@@ -104,6 +108,7 @@ export interface BuildSummary {
104
108
  target?: string
105
109
  integration?: ReturnType<typeof buildVocabulary>['integration']
106
110
  integrationState?: BuildState['integration']
111
+ handPushedCommits?: HandPushedChange[]
107
112
  nodeRestack?: BuildState['nodeRestack']
108
113
  slug: string
109
114
  ticket?: TicketRef
@@ -150,6 +155,8 @@ export type BuildDecisionProjection =
150
155
  | { kind: 'unavailable'; diagnostic: string }
151
156
 
152
157
  export interface BuildDetail extends BuildSummary {
158
+ nodePolling?: { mode: 'active' | 'idle'; intervalSeconds: number; lastChecked?: string }
159
+ runnerAttaches: import('../kernel/read-facts').RunnerAttach[]
153
160
  tree?: TreeProjection
154
161
  /** Immutable policy provenance and durable command/native application state. */
155
162
  landing?: BuildState['landing']
@@ -246,7 +253,9 @@ export function summarizeFrom(record: BuildRecord, state: BuildState, now: Date)
246
253
  slug: record.slug,
247
254
  ...buildVocabulary(state),
248
255
  ...(state.kind === 'node' ? { integrationState: state.integration } : {}),
249
- ...(state.kind === 'node' ? { nodeRestack: state.nodeRestack } : {}),
256
+ ...(state.kind === 'node'
257
+ ? { nodeRestack: state.nodeRestack, handPushedCommits: projectHandPushed(state.nodeRestack) }
258
+ : {}),
250
259
  // record.ticket is a TicketRef already carrying id/title/url — no artifact
251
260
  // read and no ticket-provider call (live ticket state is out of scope).
252
261
  ...(record.ticket !== undefined ? { ticket: record.ticket } : {}),
@@ -303,6 +312,7 @@ export function detail(
303
312
  record,
304
313
  {
305
314
  state: reduceBuild(events),
315
+ runnerAttaches: buildReadFactsReducer.reduce(events).runnerAttaches,
306
316
  log: indexLog(events),
307
317
  observations: events
308
318
  .filter((event) => event.type === 'observation.recorded')
@@ -319,7 +329,9 @@ export function detail(
319
329
  export function detailFromFacts(
320
330
  record: BuildRecord,
321
331
  facts: Pick<BuildFacts, 'state' | 'open'> &
322
- Partial<Pick<BuildFacts, 'log'>> & { observations: BuildState['observations'] },
332
+ Partial<Pick<BuildFacts, 'log' | 'runnerAttaches'>> & {
333
+ observations: BuildState['observations']
334
+ },
323
335
  now: Date,
324
336
  events?: AbEvent[],
325
337
  decision?: BuildDecisionProjection,
@@ -354,6 +366,7 @@ export function detailFromFacts(
354
366
  }))
355
367
  return {
356
368
  ...summary,
369
+ runnerAttaches: facts.runnerAttaches ?? [],
357
370
  ...(facts.log ? { tree: projectTree(record, state, facts.log.restack) } : {}),
358
371
  autoMerge: autoMergeDisplay(state),
359
372
  ...(state.landing && Object.keys(state.landing).length ? { landing: state.landing } : {}),
@@ -550,6 +563,14 @@ export function renderSummaries(summaries: BuildSummary[], now: Date, emptyNote:
550
563
  /** Labeled sections, each omitted when absent ("when each is available"). */
551
564
  export function renderDetail(d: BuildDetail, now: Date): string[] {
552
565
  const lines: string[] = [`build ${d.slug}`]
566
+ if (d.nodePolling)
567
+ lines.push(
568
+ ` node polling: ${d.nodePolling.mode === 'idle' ? `idle; polled every ${d.nodePolling.intervalSeconds} seconds` : 'active; polled every tick'}; last checked: ${d.nodePolling.lastChecked ?? 'unrecorded'}`,
569
+ )
570
+ for (const attach of d.runnerAttaches)
571
+ lines.push(
572
+ ` runner attach #${attach.seq}: ${attach.instance}; host ${attach.host}; ${attach.ts}; ${formatRuntimeIdentity(attach.runtime)}`,
573
+ )
553
574
  if (d.compatibility)
554
575
  lines.push(
555
576
  ` newer facts: ${d.compatibility.unknownFacts} (${d.compatibility.decisiveFacts} decisive)`,
@@ -576,6 +597,8 @@ export function renderDetail(d: BuildDetail, now: Date): string[] {
576
597
  if (d.integration === 'verification failed')
577
598
  lines.push(' repair: file a child ticket targeting this node')
578
599
  }
600
+ if (d.kind === 'integration')
601
+ lines.push(` hand-pushed changes (node-owned): ${handPushedText(d.handPushedCommits)}`)
579
602
  if (d.nodeRestack) {
580
603
  const node = d.nodeRestack
581
604
  const move = node.parentRequest ?? node.parentChange
@@ -587,7 +610,6 @@ export function renderDetail(d: BuildDetail, now: Date): string[] {
587
610
  if (node.inventory) {
588
611
  lines.push(` node head: ${node.inventory.head}`)
589
612
  lines.push(` build changes: ${node.inventory.builds.join(', ') || 'none'}`)
590
- lines.push(` foreign changes (node-owned): ${node.inventory.foreign.join(', ') || 'none'}`)
591
613
  }
592
614
  if (!node.active && node.observedParent && node.observedParent.sha !== node.contributionBase)
593
615
  lines.push(` node restack pending: parent ${node.observedParent.sha}`)
@@ -1086,8 +1108,40 @@ export async function abBuildStatus(opts: AbBuildStatusOpts): Promise<void> {
1086
1108
  )
1087
1109
  const configMeta =
1088
1110
  configArtifact !== null ? parseBuildConfigMetadata(configArtifact) : undefined
1111
+ let nodePolling: BuildDetail['nodePolling']
1112
+ if (
1113
+ facts.state.kind === 'node' &&
1114
+ facts.state.status !== 'done' &&
1115
+ facts.state.status !== 'aborted' &&
1116
+ facts.state.prState !== 'closed' &&
1117
+ facts.state.prState !== 'merged'
1118
+ ) {
1119
+ const children: { slug: string; state: BuildState }[] = []
1120
+ for (const child of await context.store.listBuilds()) {
1121
+ if (child.repo !== record.repo) continue
1122
+ const state = (await readBuildFacts(context.store, child.slug)).value.state
1123
+ if (state.target?.build === record.slug) children.push({ slug: child.slug, state })
1124
+ }
1125
+ // The checkpoint records the dispatcher's hot policy. A held node's
1126
+ // launch artifact can predate later policy changes.
1127
+ const policy = {
1128
+ nodeIdleAfterSeconds: facts.state.nodePolling?.nodeIdleAfterSeconds ?? 600,
1129
+ nodeIdlePollSeconds: facts.state.nodePolling?.nodeIdlePollSeconds ?? 120,
1130
+ }
1131
+ nodePolling = nodePollingSchedule(
1132
+ facts.state,
1133
+ nodeActivityKey(facts.state, children),
1134
+ policy,
1135
+ now,
1136
+ facts.open !== null ||
1137
+ facts.publication.pending() ||
1138
+ facts.publication.abandonedPending() ||
1139
+ undefined,
1140
+ )
1141
+ }
1089
1142
  const d: BuildDetail = {
1090
1143
  ...projected,
1144
+ ...(nodePolling ? { nodePolling } : {}),
1091
1145
  ...(configMeta?.revision !== undefined ? { effectiveConfigRev: configMeta.revision } : {}),
1092
1146
  ...(configMeta?.pipelineSource !== undefined
1093
1147
  ? { pipelineSource: configMeta.pipelineSource }
@@ -1,9 +1,10 @@
1
+ import { recordTicketMigration, readTicketMigrations } from '../kernel/ticket-migrations'
1
2
  import { readTicketTree } from '../operator/tickets'
2
3
  import { updateTicketTarget } from '../kernel/node-parent'
3
4
  import { createForge } from '../ports/forge/create'
4
5
  import { compatibleTicketSource, type TicketTreeEntry } from '../ports/tickets/tree'
5
6
  import { readBuildFacts } from '../store/reduced-reads'
6
- import { exportTickets, importTickets } from '../ports/tickets/migration'
7
+ import { exportTickets, importTickets, directMigration } from '../ports/tickets/migration'
7
8
  import { composeTicketAssets } from '../store/ticket-assets'
8
9
  import { editTicket, type TicketEditorRunner } from './ticket-editor'
9
10
  /**
@@ -174,6 +175,7 @@ type TicketCommandName =
174
175
  | 'tree'
175
176
  | 'export'
176
177
  | 'import'
178
+ | 'migration'
177
179
  | 'states'
178
180
  | 'state create'
179
181
  | 'create'
@@ -787,6 +789,7 @@ const STATE_CREATE_USAGE = 'usage: ab ticket state create <name> [--about <text>
787
789
  export const TICKET_USAGE = [
788
790
  'usage: ab ticket export <dir> [--store <ref>]',
789
791
  'usage: ab ticket import <dir> [--store <ref>]',
792
+ 'usage: ab ticket migration record <dir> [--store <ref>]',
790
793
  'usage: ab ticket tree [--json]',
791
794
  CREATE_USAGE,
792
795
  'usage: ab ticket edit <id> (§8.8)',
@@ -811,6 +814,7 @@ function commaList(value: string): string[] {
811
814
  }
812
815
 
813
816
  interface TicketCliOpts extends TicketCommandOpts {
817
+ signal?: AbortSignal
814
818
  /** Required because the `list` subcommand can produce record diagnostics. */
815
819
  stderr: (line: string) => void
816
820
  }
@@ -820,22 +824,42 @@ interface TicketCliOpts extends TicketCommandOpts {
820
824
  export async function abTicket(argv: string[], opts: TicketCliOpts): Promise<void> {
821
825
  const [command, ...args] = argv
822
826
  switch (command) {
827
+ case 'migration':
823
828
  case 'export':
824
829
  case 'import': {
825
- const parsed = parseArgs(args, { store: 'value' }, TICKET_USAGE)
830
+ const tail = command === 'migration' ? args.slice(1) : args
831
+ if (command === 'migration' && args[0] !== 'record') throw new Error(TICKET_USAGE)
832
+ const parsed = parseArgs(tail, { store: 'value' }, TICKET_USAGE)
826
833
  const [dir, ...extra] = parsed.positionals
827
834
  if (!dir?.trim() || extra.length) throw new Error(TICKET_USAGE)
828
835
  const migrationOpts = { ...opts, storeRef: stringFlag(parsed, 'store') ?? opts.storeRef }
829
836
  const { source } = await resolveTicketCommand(migrationOpts, command)
830
- await withTicketAssets(migrationOpts, source, ({ store, repo }) =>
831
- (command === 'export' ? exportTickets : importTickets)({
832
- source,
833
- assets: store,
834
- repo,
835
- dir,
836
- print: opts.stdout,
837
- }),
838
- )
837
+ await withTicketAssets(migrationOpts, source, async ({ store, buildStore, repo }) => {
838
+ const input = { source, assets: store, repo, dir, print: opts.stdout, signal: opts.signal }
839
+ if (command === 'export') return exportTickets(input)
840
+ await buildStore.ensureRepo(repo)
841
+ await readTicketMigrations(buildStore, repo)
842
+ const result =
843
+ command === 'import' ? await importTickets(input) : await directMigration(input)
844
+ try {
845
+ await recordTicketMigration(
846
+ buildStore,
847
+ repo,
848
+ {
849
+ kind: 'human',
850
+ user: opts.env.USER?.trim() || opts.env.USERNAME?.trim() || 'operator',
851
+ },
852
+ result,
853
+ )
854
+ } catch (error) {
855
+ throw new Error(
856
+ `Tickets imported/validated but continuity was not recorded: ${error instanceof Error ? error.message : error}. Rerun the same command to retry safely.`,
857
+ )
858
+ }
859
+ opts.stdout(
860
+ `recorded ticket migration ${result.from} → ${result.to}: ${Object.keys(result.mapping).length} tickets`,
861
+ )
862
+ })
839
863
  return
840
864
  }
841
865
 
@@ -0,0 +1,25 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+ import { loadConfig } from '../config/load'
4
+
5
+ /** Describes future adoption, never claims that a skill merge upgraded a process. */
6
+ export async function upgradeFollowup(checkout: string): Promise<string> {
7
+ const config = await loadConfig(join(checkout, 'autobuild.toml'))
8
+ if (!config.upgrade.automatic)
9
+ return 'Automatic dispatcher upgrades are off; restart dispatchers after updating their installation.'
10
+ let manifest: {
11
+ dependencies?: Record<string, unknown>
12
+ devDependencies?: Record<string, unknown>
13
+ } = {}
14
+ try {
15
+ manifest = JSON.parse(await readFile(join(checkout, 'package.json'), 'utf8'))
16
+ } catch (error) {
17
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
18
+ }
19
+ const pinned =
20
+ manifest.dependencies?.['@defrex/autobuild'] !== undefined ||
21
+ manifest.devDependencies?.['@defrex/autobuild'] !== undefined
22
+ return pinned
23
+ ? `Dispatchers check every 60 seconds and adopt the pinned version once this commit reaches ${config.baseBranch}. This command never pushes.`
24
+ : 'The dispatcher on this machine checks its original installation every 60 seconds and adopts a changed version automatically. Skill merges alone do not change that version. This command never pushes.'
25
+ }
@@ -1,3 +1,4 @@
1
+ import { integrationFailed } from '../kernel/integration-state'
1
2
  import { awaitsConsent } from '../kernel/landing-readiness'
2
3
  import { leafRestackReducer, type LeafRestackState } from '../kernel/leaf-restack-state'
3
4
  import { consentReady, consentIdentity } from './attention'
@@ -215,6 +216,7 @@ function stateSatisfies(
215
216
  return !!state.nodeRestack?.conflict || !!(restack.active && restack.replay?.conflicted)
216
217
  case 'attention':
217
218
  return (
219
+ (state.kind === 'node' && integrationFailed(state)) ||
218
220
  state.janitor?.attention === true ||
219
221
  awaitsConsent(state, restack) ||
220
222
  !!state.nodeRestack?.conflict ||
@@ -501,6 +503,7 @@ export async function abWait(opts: AbWaitOpts): Promise<number> {
501
503
  event.type === 'escalation.raised' ||
502
504
  event.type === 'phase.deferral-escalated' ||
503
505
  event.type === 'integration.landed' ||
506
+ event.type === 'integration.verification-failed' ||
504
507
  event.type === 'node.item-conflicted' ||
505
508
  (event.type === 'restack.replayed' && event.payload.conflicted)
506
509
  )
@@ -109,6 +109,7 @@ export const BUILD_ATTENTION_EVENTS = [
109
109
  'escalation.raised',
110
110
  'phase.deferral-escalated',
111
111
  'integration.landed',
112
+ 'integration.verification-failed',
112
113
  'node.item-conflicted',
113
114
  ] as const satisfies readonly EventType[]
114
115
 
@@ -409,6 +410,8 @@ const SUMMARY_MAX = 200
409
410
  */
410
411
  export function summarizeEvent(event: AbEvent | RepositoryEvent, state: BuildState | null): string {
411
412
  switch (event.type) {
413
+ case 'integration.verification-failed':
414
+ return `verification failed: ${event.payload.steps.join(', ')}; head ${event.payload.head}; parent ${event.payload.parent}; ${event.payload.guidance}`
412
415
  case 'build.janitor-failing':
413
416
  return `Janitor failing: ${singleLine(event.payload.message)}`
414
417
  case 'dispatcher.forge-degraded':
@@ -466,6 +469,10 @@ export function summarizeEvent(event: AbEvent | RepositoryEvent, state: BuildSta
466
469
  return `dispatcher tick failed: ${singleLine(event.payload.error)}`
467
470
  case 'dispatcher.forge-readiness-failed':
468
471
  return singleLine(formatReadinessFailure(event.payload))
472
+ case 'dispatcher.runtime-rolled-back':
473
+ return `dispatcher runtime rolled back ${event.payload.failed.version} → ${event.payload.restored.version}: ${singleLine(event.payload.reason)}`
474
+ case 'dispatcher.upgrade-failed':
475
+ return `dispatcher upgrade failed (${event.payload.target.mode} ${event.payload.target.version ?? event.payload.target.source}): ${singleLine(event.payload.reason)}`
469
476
  case 'dispatcher.config-rejected':
470
477
  return `dispatcher config rejected: ${singleLine(event.payload.error)}`
471
478
  case 'dispatcher.harvest-runner-failed':
@@ -13,6 +13,7 @@ export const DISPATCHER_CONFIG_ARTIFACT = 'dispatcher-config'
13
13
  */
14
14
  export const CONFIG_RELOAD_CLASSIFICATION = {
15
15
  store: 'restart',
16
+ upgrade: 'hot',
16
17
  baseBranch: 'hot',
17
18
  capacity: 'hot',
18
19
  ticketScanIntervalSeconds: 'hot',
@@ -509,6 +509,7 @@ export type RoleConfig = z.infer<typeof roleSchema>
509
509
  // ── [policy] ─────────────────────────────────────────────────────────────────
510
510
 
511
511
  export const policySchema = z.strictObject({
512
+ upgradeDrainSeconds: z.number().int().positive().default(900),
512
513
  /** Wall-clock bound for an agent phase session; roles may override it. */
513
514
  sessionBudgetSeconds: z.number().int().positive().default(3600),
514
515
  /** Same-finding survival threshold before auto-escalate (§10, §15.4). */
@@ -527,6 +528,8 @@ export const policySchema = z.strictObject({
527
528
  harvestThreshold: z.number().int().positive().default(5),
528
529
  /** Merged builds after the oldest observation that start harvest; zero disables drift. */
529
530
  janitorFailureAttentionSeconds: z.number().int().positive().default(600),
531
+ nodeIdleAfterSeconds: z.number().int().positive().default(600),
532
+ nodeIdlePollSeconds: z.number().int().positive().default(120),
530
533
  janitorBackoffMaxSeconds: z.number().int().positive().default(300),
531
534
  harvestMaxDrift: z.number().int().nonnegative().default(3),
532
535
  })
@@ -715,12 +718,12 @@ const ORCHESTRATOR_APPROVAL_ENTRY = /^[a-z][a-z0-9_.]*(:[a-z0-9_-]+)?$/
715
718
 
716
719
  /** The attention set a new session's wake settings inherit when the
717
720
  * repository does not override `wake`: the build events an operator or agent
718
- * must wake up for (the same set `ab watch` filters on by default) plus the
719
- * repository-journal attention events (the same set `ab watch`
720
- * follows), spelled as literal globs. Both halves of the attention set can
721
- * wake a session. */
721
+ * must wake up for, spelled as literal globs. These legacy hosted defaults
722
+ * remain independent of CLI watch defaults; failed node verification belongs
723
+ * to both. Repository-journal attention can also wake a session. */
722
724
  export const defaultOrchestratorWakeGlobs: readonly string[] = [
723
725
  'escalation.raised',
726
+ 'integration.verification-failed',
724
727
  'phase.deferral-escalated',
725
728
  'phase.failed',
726
729
  'infrastructure.failed',
@@ -810,6 +813,7 @@ export const storeSchema = z.strictObject({
810
813
  })
811
814
  const configRootSchema = z.strictObject({
812
815
  store: storeSchema.optional(),
816
+ upgrade: z.strictObject({ automatic: z.boolean().default(true) }).prefault({}),
813
817
  /** Base branch builds cut from and target (§16.1). */
814
818
  baseBranch: z.string().min(1).default('main'),
815
819
  /** Concurrent builds for this repository (§16.1). */
@@ -0,0 +1,116 @@
1
+ import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { dirname, join } from 'node:path'
4
+
5
+ async function spawnExec(cmd: string[], options: { cwd: string; signal?: AbortSignal }) {
6
+ const child = Bun.spawn(cmd, {
7
+ cwd: options.cwd,
8
+ stdout: 'pipe',
9
+ stderr: 'pipe',
10
+ signal: options.signal,
11
+ })
12
+ const [exitCode, stdout, stderr] = await Promise.all([
13
+ child.exited,
14
+ new Response(child.stdout).text(),
15
+ new Response(child.stderr).text(),
16
+ ])
17
+ return { exitCode, stdout, stderr }
18
+ }
19
+
20
+ type PackagingExec = typeof spawnExec
21
+
22
+ async function execOrThrow(
23
+ cmd: string[],
24
+ cwd: string,
25
+ exec: PackagingExec,
26
+ signal?: AbortSignal,
27
+ ): Promise<string> {
28
+ const result = await exec(cmd, { cwd, signal })
29
+ if (result.exitCode !== 0) {
30
+ throw new Error(
31
+ `${cmd.join(' ')} exited ${result.exitCode}: ${result.stderr.trim() || result.stdout.trim()}`,
32
+ )
33
+ }
34
+ return result.stdout.trim()
35
+ }
36
+
37
+ /** Manifest fields that name repo-local packaging state and must never reach
38
+ * the packed distribution manifest. `patchedDependencies` entries are resolved
39
+ * by bun against the consuming project's root, and bun 1.4.0 panics
40
+ * (`Option::unwrap`, exit 134) when a consumed manifest declares a patch for a
41
+ * package the consumer tree contains — so a packed manifest carrying the
42
+ * repo's better-auth patch declaration breaks any consumer that installs
43
+ * autobuild next to better-auth. The packed artifact ships no patched
44
+ * package, so the declaration is stripped from the packed manifest while the
45
+ * repo manifest keeps it for workspace installs. The strip is an enforced
46
+ * invariant, not a local detail: the `patchedDependencies` rule in
47
+ * `tools/workspace-manifest-check.ts` rejects a root manifest whose packed
48
+ * dependency set contains a patched package, and the negative control in
49
+ * `packages/core/src/plugin-sdk/package.test.ts` (the packed-distribution
50
+ * better-auth canary) pins the consumed-manifest failure shape this strip
51
+ * guards, so removing the field from this list fails the suite loudly.
52
+ *
53
+ * `devDependencies` is stripped for two reasons. First, the workspace link
54
+ * specifiers it may carry (for example the root's
55
+ * `@defrex/autobuild-postgres-store: workspace:*`) cannot be resolved in the
56
+ * staging tree — it stages only the manifest's `files` set, with no
57
+ * `bun.lock`, no `node_modules`, and no workspace packages — so `bun pm pack`
58
+ * fails there with "Failed to resolve workspace version". Second, the guest
59
+ * installs the distribution with `bun install --production --ignore-scripts`,
60
+ * which ignores devDependencies entirely; the packed artifact ships no
61
+ * dev-only tooling, so the declaration is dead weight in the packed manifest
62
+ * while the repo manifest keeps it for workspace installs. */
63
+ const packedManifestOmittedFields = ['patchedDependencies', 'devDependencies'] as const
64
+
65
+ export async function packageDistribution(
66
+ root: string,
67
+ exec: PackagingExec = spawnExec,
68
+ signal?: AbortSignal,
69
+ ): Promise<Uint8Array> {
70
+ const staging = await mkdtemp(join(tmpdir(), 'autobuild-pack-staging-'))
71
+ const destination = await mkdtemp(join(tmpdir(), 'autobuild-pack-'))
72
+ try {
73
+ // Pack from a staging copy of the repo's `files` set rather than the repo
74
+ // root: the packed manifest must differ from the repo manifest (above), and
75
+ // rewriting the repo manifest in place would leave a window where tracked
76
+ // files are dirty.
77
+ const manifestPath = join(root, 'package.json')
78
+ const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as Record<string, unknown>
79
+ const files = manifest.files
80
+ if (!Array.isArray(files) || files.some((entry) => typeof entry !== 'string')) {
81
+ throw new Error(
82
+ 'Autobuild packaging requires the root package.json to list its files as an array of paths',
83
+ )
84
+ }
85
+ for (const entry of files as string[]) {
86
+ // npm `files` entries may be negated globs (for example
87
+ // `!packages/core/src/**/*.test.ts`, which keeps test files out of the
88
+ // published package). Only positive entries name a path to stage: the
89
+ // negations stay in the staged manifest and `bun pm pack` applies them,
90
+ // so the packed set still excludes those paths.
91
+ if (entry.startsWith('!')) continue
92
+ const target = join(staging, entry)
93
+ await mkdir(dirname(target), { recursive: true })
94
+ await cp(join(root, entry), target, {
95
+ recursive: true,
96
+ errorOnExist: true,
97
+ force: false,
98
+ })
99
+ }
100
+ for (const field of packedManifestOmittedFields) delete manifest[field]
101
+ await writeFile(join(staging, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`)
102
+ await execOrThrow(
103
+ ['bun', 'pm', 'pack', '--ignore-scripts', '--destination', destination],
104
+ staging,
105
+ exec,
106
+ signal,
107
+ )
108
+ const archives = (await readdir(destination)).filter((name) => name.endsWith('.tgz'))
109
+ if (archives.length !== 1)
110
+ throw new Error('Autobuild packaging did not produce exactly one archive')
111
+ return new Uint8Array(await readFile(join(destination, archives[0]!)))
112
+ } finally {
113
+ await rm(staging, { recursive: true, force: true })
114
+ await rm(destination, { recursive: true, force: true })
115
+ }
116
+ }
@@ -67,6 +67,7 @@ export const allowedActorKinds: Record<EventType, readonly ActorKind[]> = {
67
67
  'integration.prepared': ['kernel', 'dispatcher'],
68
68
  'integration.landing-intended': ['kernel', 'dispatcher'],
69
69
  'integration.landed': ['kernel', 'dispatcher'],
70
+ 'integration.verification-failed': ['kernel', 'dispatcher'],
70
71
  'integration.audited': ['kernel', 'dispatcher'],
71
72
  'node.restack-requested': ['dispatcher', 'human'],
72
73
  'node.restack-satisfied': ['kernel', 'dispatcher'],
@@ -89,15 +90,20 @@ export const allowedActorKinds: Record<EventType, readonly ActorKind[]> = {
89
90
  'node.contribution-recorded': ['kernel', 'dispatcher'],
90
91
  'node.inventory': ['kernel', 'dispatcher'],
91
92
  'node.opened': ['dispatcher'],
93
+ 'node.poll-checked': ['dispatcher'],
92
94
  'node.compared': ['dispatcher'],
93
95
  'pr.opened': ['dispatcher'],
94
96
  'build.created': ['dispatcher', 'human'],
95
97
  'build.completed': ['dispatcher'],
98
+ 'runner.runtime-recorded': ['kernel'],
96
99
  'runner.attached': ['kernel'],
97
100
  'runner.setup-failed': ['kernel'],
98
101
  'workspace.provisioned': ['dispatcher', 'kernel'],
99
102
  'workspace.provision-started': ['dispatcher'],
100
103
  'workspace.released': ['dispatcher', 'kernel'],
104
+ 'execution.relaunch-requested': ['kernel'],
105
+ 'execution.drain-authorized': ['dispatcher'],
106
+ 'execution.drain-settled': ['dispatcher'],
101
107
  'execution.started': ['dispatcher'],
102
108
  'execution.ended': ['dispatcher'],
103
109
  'infrastructure.failed': ['dispatcher'],