@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,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 }
@@ -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'],
@@ -1,3 +1,5 @@
1
+ import { runtimeIdentitySchema } from './runtime'
2
+ import { viaSchema } from './envelope'
1
3
  import { nativeSessionHandleSchema } from './native-session'
2
4
  /**
3
5
  * The event vocabulary (SPEC §15.3), frozen as schemas — this closes open
@@ -454,6 +456,16 @@ export const eventPayloadSchemas = {
454
456
  )
455
457
  .optional(),
456
458
  }),
459
+ 'integration.verification-failed': z.strictObject({
460
+ id: z.string().trim().min(1),
461
+ head: z.string().trim().min(1),
462
+ parent: z.string().trim().min(1),
463
+ steps: z
464
+ .array(z.string().trim().min(1))
465
+ .min(1)
466
+ .refine((steps) => new Set(steps).size === steps.length, 'failed steps must be unique'),
467
+ guidance: z.string().trim().min(1),
468
+ }),
457
469
  'integration.prepared': z.strictObject({
458
470
  id: z.string().min(1),
459
471
  head: z.string().min(1),
@@ -489,6 +501,12 @@ export const eventPayloadSchemas = {
489
501
  landedTree: z.string().min(1),
490
502
  identities: z.array(z.string()),
491
503
  }),
504
+ 'node.poll-checked': z.strictObject({
505
+ activityKey: z.string().min(1),
506
+ unchangedSince: z.iso.datetime(),
507
+ nodeIdleAfterSeconds: z.number().int().positive(),
508
+ nodeIdlePollSeconds: z.number().int().positive(),
509
+ }),
492
510
  'node.compared': z.strictObject({
493
511
  parentSha: z.string().min(1),
494
512
  headSha: z.string().min(1),
@@ -502,6 +520,11 @@ export const eventPayloadSchemas = {
502
520
  }),
503
521
  }),
504
522
  'build.completed': z.strictObject({ outcome: buildOutcomeSchema }),
523
+ 'runner.runtime-recorded': z.strictObject({
524
+ instance: z.string().min(1),
525
+ attachedSeq: z.number().int().positive(),
526
+ runtime: runtimeIdentitySchema,
527
+ }),
505
528
  'runner.attached': z.strictObject({
506
529
  instance: z.string().min(1),
507
530
  host: z.string().min(1),
@@ -548,6 +571,23 @@ export const eventPayloadSchemas = {
548
571
  }),
549
572
  /** Dispatcher-owned identity and provider lifecycle evidence. These facts do
550
573
  * not carry pipeline progress; they make disposable execution observable. */
574
+ 'execution.relaunch-requested': z.strictObject({
575
+ instance: z.string().min(1),
576
+ correlation: z.string().min(1),
577
+ from: runtimeIdentitySchema,
578
+ to: runtimeIdentitySchema,
579
+ }),
580
+ 'execution.drain-authorized': z.strictObject({
581
+ targetRuntime: runtimeIdentitySchema.optional(),
582
+ correlation: z.string().min(1),
583
+ run: z.string().min(1),
584
+ runtime: runtimeIdentitySchema,
585
+ instance: z.string().min(1),
586
+ }),
587
+ 'execution.drain-settled': z.strictObject({
588
+ correlation: z.string().min(1),
589
+ instance: z.string().min(1),
590
+ }),
551
591
  'execution.started': z.strictObject({
552
592
  provider: z.string().min(1),
553
593
  workspaceRef: z.string().min(1),
@@ -563,7 +603,7 @@ export const eventPayloadSchemas = {
563
603
  'execution.ended': z.strictObject({
564
604
  instance: z.string().min(1),
565
605
  workspaceRef: z.string().min(1),
566
- outcome: z.enum(['completed', 'stopped', 'lost']),
606
+ outcome: z.enum(['completed', 'stopped', 'lost', 'relaunch']),
567
607
  exitCode: z.number().int().nullable().optional(),
568
608
  }),
569
609
  'infrastructure.failed': z.strictObject({
@@ -750,14 +790,18 @@ export const eventPayloadSchemas = {
750
790
  artifact: artifactRefSchema,
751
791
  session: z.string().min(1),
752
792
  }),
753
- 'spec.revised': z.strictObject({
754
- artifact: artifactRefSchema,
755
- /** seq of the `escalation.raised` event that forced the revision. */
756
- escalation: z.number().int().positive(),
757
- /** Present (possibly empty) when the revision re-pins the build to the
758
- * ticket's then-current assets; absent leaves the pinned set unchanged. */
759
- assets: z.array(pinnedAssetSchema).optional(),
760
- }),
793
+ 'spec.revised': z.union([
794
+ z.strictObject({
795
+ artifact: artifactRefSchema,
796
+ escalation: z.number().int().positive(),
797
+ assets: z.array(pinnedAssetSchema).optional(),
798
+ }),
799
+ z.strictObject({
800
+ artifact: artifactRefSchema,
801
+ operator: z.strictObject({ user: z.string().min(1), via: viaSchema.optional() }),
802
+ assets: z.array(pinnedAssetSchema).optional(),
803
+ }),
804
+ ]),
761
805
 
762
806
  // ── Sessions (every agent run is bracketed by these) ──────────────────────
763
807
  'session.started': z.strictObject({
@@ -34,9 +34,11 @@ export const buildEventPolicy = {
34
34
  'integration.prepared': 'decisive',
35
35
  'integration.landing-intended': 'decisive',
36
36
  'integration.landed': 'decisive',
37
+ 'integration.verification-failed': 'decisive',
37
38
  'integration.audited': 'decisive',
38
39
  'node.restack-requested': 'decisive',
39
40
  'node.restack-satisfied': 'decisive',
41
+ 'node.poll-checked': 'advisory',
40
42
  'node.parent-distance': 'advisory',
41
43
  'node.parent-requested': 'decisive',
42
44
  'node.parent-accepted': 'decisive',
@@ -60,11 +62,15 @@ export const buildEventPolicy = {
60
62
  'pr.opened': 'decisive',
61
63
  'build.created': 'decisive',
62
64
  'build.completed': 'decisive',
65
+ 'runner.runtime-recorded': 'advisory',
63
66
  'runner.attached': 'decisive',
64
67
  'runner.setup-failed': 'decisive',
65
68
  'workspace.provisioned': 'decisive',
66
69
  'workspace.provision-started': 'decisive',
67
70
  'workspace.released': 'decisive',
71
+ 'execution.relaunch-requested': 'decisive',
72
+ 'execution.drain-authorized': 'decisive',
73
+ 'execution.drain-settled': 'decisive',
68
74
  'execution.started': 'decisive',
69
75
  'execution.ended': 'decisive',
70
76
  'infrastructure.failed': 'decisive',
@@ -157,6 +163,11 @@ export const repositoryEventPolicy = {
157
163
  'harvest.step.completed': 'decisive',
158
164
  'harvest.session.started': 'decisive',
159
165
  'harvest.session.ended': 'decisive',
166
+ 'harvest.session.native-handle-recorded': 'decisive',
167
+ 'harvest.session.suspended': 'decisive',
168
+ 'harvest.session.resumed': 'decisive',
169
+ 'harvest.session.resume-fallback': 'decisive',
170
+
160
171
  'harvest.proposals.submitted': 'decisive',
161
172
  'harvest.review.verdict': 'decisive',
162
173
  'harvest.proposal.id-reserved': 'decisive',
@@ -172,6 +183,20 @@ export const repositoryEventPolicy = {
172
183
  'orchestrator.sandbox.reset': 'decisive',
173
184
  'orchestrator.sandbox.published': 'decisive',
174
185
  'orchestrator.sandbox.publish-failed': 'decisive',
186
+ 'dispatcher.upgrade-target-resolved': 'advisory',
187
+ 'dispatcher.target-prepared': 'decisive',
188
+ 'dispatcher.yield-requested': 'decisive',
189
+ 'dispatcher.terminal-released': 'decisive',
190
+ 'dispatcher.takeover': 'decisive',
191
+ 'dispatcher.drain-settled': 'decisive',
192
+ 'dispatcher.drain-deadline': 'decisive',
193
+ 'dispatcher.upgrade-detected': 'advisory',
194
+ 'dispatcher.upgrade-failed': 'decisive',
195
+ 'dispatcher.runtime-rolled-back': 'decisive',
196
+ 'dispatcher.rollback-hold-cleared': 'decisive',
197
+ 'dispatcher.handoff-started': 'decisive',
198
+ 'dispatcher.handoff-completed': 'decisive',
199
+ 'dispatcher.runtime-recorded': 'advisory',
175
200
  'dispatcher.run-started': 'decisive',
176
201
  'dispatcher.stop-requested': 'decisive',
177
202
  'dispatcher.run-stopped': 'decisive',