@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
@@ -0,0 +1,190 @@
1
+ import { ownsDispatchPresentation } from './dispatch-presentation-ownership'
2
+ import { guardForge } from '../kernel/guarded-forge'
3
+ import { scopeLocalStoreToPhaseSession } from '../store/phase-session'
4
+ import { openProductionStore } from './store-opening'
5
+ /**
6
+ * Shared wiring for the `ab` process entry points. Production calls this with
7
+ * argv only; the repo-local hot entry may additionally supply a per-paint
8
+ * dashboard renderer resolver. All command routing and resource cleanup stay
9
+ * identical between the two entries.
10
+ */
11
+ import { join } from 'node:path'
12
+ import { isSessionlessInvocation, runCli } from './main'
13
+ import { createUpgradeAgentResolver } from './upgrade-agent'
14
+ import { loadDotEnv } from './dotenv'
15
+ import { MissingAmbientContextError, resolveCliEnv, resolveHarvestCliEnv } from './env'
16
+ import { openProductionSessionStore } from './store-opening'
17
+ import { processTerminal, processTerminalInput } from './terminal'
18
+ import type { TerminalRestoreProcess } from './terminal-restore'
19
+ import type { DashboardRendererResolver } from './dashboard/render'
20
+ import { loadConfig } from '../config/load'
21
+ import { loadPlugins } from '../plugins/load'
22
+ import { createForge } from '../ports/forge/create'
23
+ import { spawnExec } from '../ports/workspace/git-worktree'
24
+ import { randomIds } from '../ids'
25
+ import { systemClock } from '../store/types'
26
+ import { resolveMainRepo } from './repo-state'
27
+
28
+ import {
29
+ usesGenericSessionlessSigintHandler,
30
+ installSessionlessSigintHandler,
31
+ withDispatchTerminalRestore,
32
+ } from './binary-lifecycle'
33
+
34
+ export async function runDirectBinary(
35
+ argv: string[],
36
+ resolveDashboardRenderer?: DashboardRendererResolver,
37
+ ): Promise<number> {
38
+ const command = argv[0]
39
+ // Version identity is installation-local and offline; do not inspect even a
40
+ // repository-local .env before routing it.
41
+ if (command !== '--version') {
42
+ // Local .env supplies developer-set secrets (e.g. LINEAR_API_KEY); real
43
+ // environment variables always win over .env values.
44
+ loadDotEnv(join(process.cwd(), '.env'), process.env)
45
+ }
46
+
47
+ delete process.env.AB_DISPATCH_GENERATION
48
+
49
+ const unscopedDeps = {
50
+ workspacePath: process.cwd(),
51
+ processEnv: process.env,
52
+ exec: spawnExec,
53
+ stdout: (line: string) => {
54
+ if (command !== 'dispatch' || ownsDispatchPresentation()) console.log(line)
55
+ },
56
+ stderr: (line: string) => {
57
+ if (command !== 'dispatch' || ownsDispatchPresentation()) console.error(line)
58
+ },
59
+ }
60
+
61
+ // Sessionless commands resolve their own repository/store and do not require
62
+ // a phase tuple; durable controls also take a target slug and inspect raw
63
+ // AB_SESSION/AB_BUILD only to reject self-control. The flat-name set and
64
+ // mixed nested-command classifier live beside the switch in main.ts.
65
+ if (isSessionlessInvocation(argv)) {
66
+ // The dispatch watch loop runs until SIGINT; abort the signal so it exits
67
+ // cleanly at the next tick boundary (§15.6-C: in-flight leases expire and
68
+ // a future dispatch re-attaches).
69
+ const controller = new AbortController()
70
+ const onSigint = (): void => controller.abort('SIGINT')
71
+ const ownsSigint = usesGenericSessionlessSigintHandler(command)
72
+ const terminal = processTerminal(process.stdout)
73
+ const removeSigint = installSessionlessSigintHandler(command, onSigint)
74
+ try {
75
+ return await withDispatchTerminalRestore(
76
+ command,
77
+ terminal,
78
+ () =>
79
+ runCli(argv, {
80
+ ...unscopedDeps,
81
+ ...(ownsSigint ? { signal: controller.signal } : {}),
82
+ // `ab dispatch`'s dashboard seam: interactive iff stdout is a real
83
+ // TTY, so a pipe or redirect silently gets plain output.
84
+ terminal,
85
+ input: processTerminalInput(process.stdin),
86
+ ...(command === 'init'
87
+ ? { initInteractive: process.stdin.isTTY === true && process.stdout.isTTY === true }
88
+ : {}),
89
+ upgradeResolverFactory: createUpgradeAgentResolver,
90
+ ...(resolveDashboardRenderer !== undefined ? { resolveDashboardRenderer } : {}),
91
+ }),
92
+ process as unknown as TerminalRestoreProcess,
93
+ (signal) => controller.abort(signal),
94
+ )
95
+ } finally {
96
+ removeSigint()
97
+ }
98
+ }
99
+
100
+ if (command === 'harvest') {
101
+ let harvestEnv: ReturnType<typeof resolveHarvestCliEnv>
102
+ try {
103
+ harvestEnv = resolveHarvestCliEnv(process.env)
104
+ } catch (error) {
105
+ if (error instanceof MissingAmbientContextError) {
106
+ return runCli(argv, unscopedDeps)
107
+ }
108
+ console.error(error instanceof Error ? error.message : String(error))
109
+ return 1
110
+ }
111
+ const store = openProductionSessionStore(harvestEnv)
112
+ try {
113
+ return await runCli(argv, {
114
+ ...unscopedDeps,
115
+ store,
116
+ harvestEnv,
117
+ ids: randomIds(),
118
+ clock: systemClock,
119
+ })
120
+ } finally {
121
+ await store.close()
122
+ }
123
+ }
124
+
125
+ let cliEnv: ReturnType<typeof resolveCliEnv>
126
+ try {
127
+ cliEnv = resolveCliEnv(process.env)
128
+ } catch (error) {
129
+ if (error instanceof MissingAmbientContextError) {
130
+ return runCli(argv, unscopedDeps)
131
+ }
132
+ console.error(error instanceof Error ? error.message : String(error))
133
+ return 1
134
+ }
135
+
136
+ // A scoped phase process is composed from the build worktree's immutable
137
+ // configuration just like dispatch. Load and select the forge before opening
138
+ // the store so plugin failures cannot partially execute terminal plumbing.
139
+ // Guest tolerance (AUT-517), always on here: in checkout mode `ab dispatch`
140
+ // already failed startup if a configured plugin did not resolve, and
141
+ // origin-mode phase processes only run inside guests — so an unresolvable
142
+ // bare specifier here can only be the provider-plugin case, which a phase
143
+ // process (never constructing workspace providers) may skip.
144
+ let forge: Awaited<ReturnType<typeof createForge>>
145
+ try {
146
+ const repoRoot = process.cwd()
147
+ const packageRoot = await resolveMainRepo(repoRoot, spawnExec)
148
+ const config = await loadConfig(join(repoRoot, 'autobuild.toml'))
149
+ const plugins = await loadPlugins(config.plugins, repoRoot, {
150
+ packageRoot,
151
+ guest: true,
152
+ })
153
+ forge = await createForge({
154
+ name: config.forge,
155
+ registry: plugins,
156
+ env: process.env,
157
+ repoRoot,
158
+ })
159
+ } catch (error) {
160
+ console.error(error instanceof Error ? error.message : String(error))
161
+ return 1
162
+ }
163
+
164
+ const kernelStore = openProductionStore(cliEnv.store, cliEnv.token)
165
+ const store = scopeLocalStoreToPhaseSession(kernelStore, {
166
+ kind: 'build',
167
+ id: cliEnv.build,
168
+ session: cliEnv.session,
169
+ })
170
+ try {
171
+ const record = await store.getBuild(cliEnv.build)
172
+ if (record)
173
+ forge = guardForge(forge, {
174
+ store: kernelStore,
175
+ repo: record.repo,
176
+ name: forge.name,
177
+ wait: true,
178
+ })
179
+ return await runCli(argv, {
180
+ ...unscopedDeps,
181
+ store,
182
+ env: cliEnv,
183
+ forge,
184
+ ids: randomIds(),
185
+ clock: systemClock,
186
+ })
187
+ } finally {
188
+ await store.close()
189
+ }
190
+ }
@@ -0,0 +1,46 @@
1
+ import type { TerminalOut } from './terminal'
2
+ import { installTerminalRestoreHook, type TerminalRestoreProcess } from './terminal-restore'
3
+ /** Upgrade (including its `update` alias) owns Ctrl-C only while raw per-file
4
+ * progress is active. Everywhere else its process must retain Node's ordinary
5
+ * immediate SIGINT termination. */
6
+ export function usesGenericSessionlessSigintHandler(command: string | undefined): boolean {
7
+ return command !== 'upgrade' && command !== 'update'
8
+ }
9
+
10
+ export interface SessionlessSigintBoundary {
11
+ on(event: 'SIGINT', listener: () => void): unknown
12
+ once(event: 'SIGINT', listener: () => void): unknown
13
+ removeListener(event: 'SIGINT', listener: () => void): unknown
14
+ }
15
+
16
+ /** Dispatch keeps its listener through the complete child drain; ordinary
17
+ * sessionless commands preserve the historical one-shot cancellation. */
18
+ export function installSessionlessSigintHandler(
19
+ command: string | undefined,
20
+ onSigint: () => void,
21
+ boundary: SessionlessSigintBoundary = process,
22
+ ): () => void {
23
+ if (!usesGenericSessionlessSigintHandler(command)) return () => {}
24
+ if (command === 'dispatch') boundary.on('SIGINT', onSigint)
25
+ else boundary.once('SIGINT', onSigint)
26
+ return () => boundary.removeListener('SIGINT', onSigint)
27
+ }
28
+
29
+ /** Install the dispatch-only process fallback around the exact CLI lifetime. */
30
+ export async function withDispatchTerminalRestore<T>(
31
+ command: string | undefined,
32
+ terminal: TerminalOut,
33
+ run: () => Promise<T>,
34
+ boundary: TerminalRestoreProcess = process as unknown as TerminalRestoreProcess,
35
+ requestStop: (signal: NodeJS.Signals) => void = () => {},
36
+ ): Promise<T> {
37
+ const hook =
38
+ command === 'dispatch'
39
+ ? installTerminalRestoreHook(terminal.modes, boundary, requestStop)
40
+ : undefined
41
+ try {
42
+ return await run()
43
+ } finally {
44
+ hook?.close()
45
+ }
46
+ }
@@ -1,222 +1,36 @@
1
- import { guardForge } from '../kernel/guarded-forge'
2
- import { scopeLocalStoreToPhaseSession } from '../store/phase-session'
3
- import { openProductionStore } from './store-opening'
4
- /**
5
- * Shared wiring for the `ab` process entry points. Production calls this with
6
- * argv only; the repo-local hot entry may additionally supply a per-paint
7
- * dashboard renderer resolver. All command routing and resource cleanup stay
8
- * identical between the two entries.
9
- */
10
1
  import { join } from 'node:path'
11
- import { isSessionlessInvocation, runCli } from './main'
12
- import { createUpgradeAgentResolver } from './upgrade-agent'
13
- import { loadDotEnv } from './dotenv'
14
- import { MissingAmbientContextError, resolveCliEnv, resolveHarvestCliEnv } from './env'
15
- import { openProductionSessionStore } from './store-opening'
16
- import { processTerminal, processTerminalInput, type TerminalOut } from './terminal'
17
- import { installTerminalRestoreHook, type TerminalRestoreProcess } from './terminal-restore'
18
2
  import type { DashboardRendererResolver } from './dashboard/render'
19
- import { loadConfig } from '../config/load'
20
- import { loadPlugins } from '../plugins/load'
21
- import { createForge } from '../ports/forge/create'
22
- import { spawnExec } from '../ports/workspace/git-worktree'
23
- import { randomIds } from '../ids'
24
- import { systemClock } from '../store/types'
25
- import { resolveMainRepo } from './repo-state'
26
-
27
- /** Upgrade (including its `update` alias) owns Ctrl-C only while raw per-file
28
- * progress is active. Everywhere else its process must retain Node's ordinary
29
- * immediate SIGINT termination. */
30
- export function usesGenericSessionlessSigintHandler(command: string | undefined): boolean {
31
- return command !== 'upgrade' && command !== 'update'
32
- }
33
-
34
- export interface SessionlessSigintBoundary {
35
- on(event: 'SIGINT', listener: () => void): unknown
36
- once(event: 'SIGINT', listener: () => void): unknown
37
- removeListener(event: 'SIGINT', listener: () => void): unknown
38
- }
39
-
40
- /** Dispatch keeps its listener through the complete child drain; ordinary
41
- * sessionless commands preserve the historical one-shot cancellation. */
42
- export function installSessionlessSigintHandler(
43
- command: string | undefined,
44
- onSigint: () => void,
45
- boundary: SessionlessSigintBoundary = process,
46
- ): () => void {
47
- if (!usesGenericSessionlessSigintHandler(command)) return () => {}
48
- if (command === 'dispatch') boundary.on('SIGINT', onSigint)
49
- else boundary.once('SIGINT', onSigint)
50
- return () => boundary.removeListener('SIGINT', onSigint)
51
- }
52
-
53
- /** Install the dispatch-only process fallback around the exact CLI lifetime. */
54
- export async function withDispatchTerminalRestore<T>(
55
- command: string | undefined,
56
- terminal: TerminalOut,
57
- run: () => Promise<T>,
58
- boundary: TerminalRestoreProcess = process as unknown as TerminalRestoreProcess,
59
- requestStop: (signal: NodeJS.Signals) => void = () => {},
60
- ): Promise<T> {
61
- const hook =
62
- command === 'dispatch'
63
- ? installTerminalRestoreHook(terminal.modes, boundary, requestStop)
64
- : undefined
65
- try {
66
- return await run()
67
- } finally {
68
- hook?.close()
69
- }
70
- }
71
-
3
+ import { loadDotEnv } from './dotenv'
4
+ import { parseDispatchArgs } from './dispatch-args'
5
+ import { launchDispatcher } from './dispatch-launcher'
6
+ import { DISPATCH_GENERATION_ENV } from './dispatch-launch-contract'
7
+ export {
8
+ usesGenericSessionlessSigintHandler,
9
+ installSessionlessSigintHandler,
10
+ withDispatchTerminalRestore,
11
+ } from './binary-lifecycle'
72
12
  export async function runBinary(
73
13
  argv: string[],
74
- resolveDashboardRenderer?: DashboardRendererResolver,
14
+ resolver?: DashboardRendererResolver,
75
15
  ): Promise<number> {
76
- const command = argv[0]
77
- // Version identity is installation-local and offline; do not inspect even a
78
- // repository-local .env before routing it.
79
- if (command !== '--version') {
80
- // Local .env supplies developer-set secrets (e.g. LINEAR_API_KEY); real
81
- // environment variables always win over .env values.
82
- loadDotEnv(join(process.cwd(), '.env'), process.env)
83
- }
84
-
85
- const unscopedDeps = {
86
- workspacePath: process.cwd(),
87
- processEnv: process.env,
88
- exec: spawnExec,
89
- stdout: (line: string) => console.log(line),
90
- stderr: (line: string) => console.error(line),
91
- }
92
-
93
- // Sessionless commands resolve their own repository/store and do not require
94
- // a phase tuple; durable controls also take a target slug and inspect raw
95
- // AB_SESSION/AB_BUILD only to reject self-control. The flat-name set and
96
- // mixed nested-command classifier live beside the switch in main.ts.
97
- if (isSessionlessInvocation(argv)) {
98
- // The dispatch watch loop runs until SIGINT; abort the signal so it exits
99
- // cleanly at the next tick boundary (§15.6-C: in-flight leases expire and
100
- // a future dispatch re-attaches).
101
- const controller = new AbortController()
102
- const onSigint = (): void => controller.abort('SIGINT')
103
- const ownsSigint = usesGenericSessionlessSigintHandler(command)
104
- const terminal = processTerminal(process.stdout)
105
- const removeSigint = installSessionlessSigintHandler(command, onSigint)
16
+ delete process.env.AB_DISPATCH_LAUNCH_CONTEXT
17
+ delete process.env[DISPATCH_GENERATION_ENV]
18
+ if (argv[0] !== '--version') loadDotEnv(join(process.cwd(), '.env'), process.env)
19
+ delete process.env.AB_DISPATCH_LAUNCH_CONTEXT
20
+ delete process.env[DISPATCH_GENERATION_ENV]
21
+ if (
22
+ argv[0] === 'dispatch' &&
23
+ !(argv.length === 2 && argv[1] === '--help') &&
24
+ resolver === undefined
25
+ ) {
106
26
  try {
107
- return await withDispatchTerminalRestore(
108
- command,
109
- terminal,
110
- () =>
111
- runCli(argv, {
112
- ...unscopedDeps,
113
- ...(ownsSigint ? { signal: controller.signal } : {}),
114
- // `ab dispatch`'s dashboard seam: interactive iff stdout is a real
115
- // TTY, so a pipe or redirect silently gets plain output.
116
- terminal,
117
- input: processTerminalInput(process.stdin),
118
- ...(command === 'init'
119
- ? { initInteractive: process.stdin.isTTY === true && process.stdout.isTTY === true }
120
- : {}),
121
- upgradeResolverFactory: createUpgradeAgentResolver,
122
- ...(resolveDashboardRenderer !== undefined ? { resolveDashboardRenderer } : {}),
123
- }),
124
- process as unknown as TerminalRestoreProcess,
125
- (signal) => controller.abort(signal),
126
- )
127
- } finally {
128
- removeSigint()
129
- }
130
- }
131
-
132
- if (command === 'harvest') {
133
- let harvestEnv: ReturnType<typeof resolveHarvestCliEnv>
134
- try {
135
- harvestEnv = resolveHarvestCliEnv(process.env)
27
+ const args = parseDispatchArgs(argv.slice(1), process.env)
28
+ if (!args.once && !args.repository) return await launchDispatcher(argv)
136
29
  } catch (error) {
137
- if (error instanceof MissingAmbientContextError) {
138
- return runCli(argv, unscopedDeps)
139
- }
140
30
  console.error(error instanceof Error ? error.message : String(error))
141
31
  return 1
142
32
  }
143
- const store = openProductionSessionStore(harvestEnv)
144
- try {
145
- return await runCli(argv, {
146
- ...unscopedDeps,
147
- store,
148
- harvestEnv,
149
- ids: randomIds(),
150
- clock: systemClock,
151
- })
152
- } finally {
153
- await store.close()
154
- }
155
- }
156
-
157
- let cliEnv: ReturnType<typeof resolveCliEnv>
158
- try {
159
- cliEnv = resolveCliEnv(process.env)
160
- } catch (error) {
161
- if (error instanceof MissingAmbientContextError) {
162
- return runCli(argv, unscopedDeps)
163
- }
164
- console.error(error instanceof Error ? error.message : String(error))
165
- return 1
166
- }
167
-
168
- // A scoped phase process is composed from the build worktree's immutable
169
- // configuration just like dispatch. Load and select the forge before opening
170
- // the store so plugin failures cannot partially execute terminal plumbing.
171
- // Guest tolerance (AUT-517), always on here: in checkout mode `ab dispatch`
172
- // already failed startup if a configured plugin did not resolve, and
173
- // origin-mode phase processes only run inside guests — so an unresolvable
174
- // bare specifier here can only be the provider-plugin case, which a phase
175
- // process (never constructing workspace providers) may skip.
176
- let forge: Awaited<ReturnType<typeof createForge>>
177
- try {
178
- const repoRoot = process.cwd()
179
- const packageRoot = await resolveMainRepo(repoRoot, spawnExec)
180
- const config = await loadConfig(join(repoRoot, 'autobuild.toml'))
181
- const plugins = await loadPlugins(config.plugins, repoRoot, {
182
- packageRoot,
183
- guest: true,
184
- })
185
- forge = await createForge({
186
- name: config.forge,
187
- registry: plugins,
188
- env: process.env,
189
- repoRoot,
190
- })
191
- } catch (error) {
192
- console.error(error instanceof Error ? error.message : String(error))
193
- return 1
194
- }
195
-
196
- const kernelStore = openProductionStore(cliEnv.store, cliEnv.token)
197
- const store = scopeLocalStoreToPhaseSession(kernelStore, {
198
- kind: 'build',
199
- id: cliEnv.build,
200
- session: cliEnv.session,
201
- })
202
- try {
203
- const record = await store.getBuild(cliEnv.build)
204
- if (record)
205
- forge = guardForge(forge, {
206
- store: kernelStore,
207
- repo: record.repo,
208
- name: forge.name,
209
- wait: true,
210
- })
211
- return await runCli(argv, {
212
- ...unscopedDeps,
213
- store,
214
- env: cliEnv,
215
- forge,
216
- ids: randomIds(),
217
- clock: systemClock,
218
- })
219
- } finally {
220
- await store.close()
221
33
  }
34
+ const { runDirectBinary } = await import('./binary-direct')
35
+ return runDirectBinary(argv, resolver)
222
36
  }
@@ -1,3 +1,4 @@
1
+ import { integrationFailed } from '../kernel/integration-state'
1
2
  import { landPreconditions } from '../kernel/landing-readiness'
2
3
  import { observeIntegration } from '../kernel/integration-completeness'
3
4
  import type { TicketSource } from '../ports/types'
@@ -92,6 +93,7 @@ export type BuildControlResult =
92
93
  count: number
93
94
  resolution: 'guidance' | 'retry' | 'dismiss-finding' | 'revise-spec'
94
95
  resumed: boolean
96
+ nodeRevision?: boolean
95
97
  specRev?: number
96
98
  authorizedEarlier?: boolean
97
99
  remainingOpen?: number
@@ -370,6 +372,35 @@ export function decideRevise(
370
372
  }
371
373
  }
372
374
 
375
+ function assertNodeRevisionEligible(slug: string, state: BuildState): void {
376
+ const restack = state.nodeRestack
377
+ if (
378
+ state.kind !== 'node' ||
379
+ !state.nodeOpened ||
380
+ (state.status !== 'collecting' && !(state.status === 'blocked' && integrationFailed(state))) ||
381
+ terminalSignal(state) ||
382
+ state.pendingCommands.length ||
383
+ state.openEscalations.length ||
384
+ state.currentPhase ||
385
+ state.sessions.open.length ||
386
+ state.sessions.suspended.length ||
387
+ restack?.active ||
388
+ restack?.parentRequest ||
389
+ restack?.parentChange ||
390
+ Object.keys(restack?.requests ?? {}).length ||
391
+ state.integration?.intent ||
392
+ state.landing?.nativeEnablePending ||
393
+ state.landing?.native?.enabled ||
394
+ state.landing?.forgeMerge ||
395
+ state.landing?.command?.kind === 'land'
396
+ ) {
397
+ throw new BuildControlError(
398
+ 'inactive',
399
+ `build "${slug}" cannot revise its node spec while work or controls are active; wait for idle collection or failed verification and retry`,
400
+ )
401
+ }
402
+ }
403
+
373
404
  function throwRefusal(decision: Extract<ReviseDecision, { kind: 'refuse' }>): never {
374
405
  throw new BuildControlError(decision.code, decision.message)
375
406
  }
@@ -435,7 +466,7 @@ export interface ControlBuildOpts {
435
466
  ticketSource?: () => Promise<TicketSource>
436
467
  /** Injected only for --revise-spec-from-ticket. */
437
468
  prepareTicketAssets?: (ref: TicketRef, store: BuildStore, repo: string) => Promise<PinnedAsset[]>
438
- readTicketBody?: (ref: TicketRef) => Promise<string>
469
+ readTicketBody?: (ref: TicketRef, store: BuildStore, repo: string) => Promise<string>
439
470
  }
440
471
 
441
472
  /** Apply one control against a freshly reduced build log. */
@@ -610,7 +641,17 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
610
641
  : reviewRoundLimitEscalation(opts.slug, selectedOpen(state, captured))
611
642
 
612
643
  if (opts.action.resolve?.kind === 'revise-spec') {
613
- const initial = decideRevise(opts.slug, state, captured)
644
+ const nodeRevision =
645
+ state.kind === 'node' &&
646
+ captured === undefined &&
647
+ state.openEscalations.length === 0 &&
648
+ !state.answeredEscalations.some(
649
+ (item) => item.resolution === 'revise-spec' && item.answeredSeq > state.restartSince,
650
+ )
651
+ if (nodeRevision) assertNodeRevisionEligible(opts.slug, state)
652
+ const initial = nodeRevision
653
+ ? { kind: 'node' as const }
654
+ : decideRevise(opts.slug, state, captured)
614
655
  if (initial.kind === 'refuse') throwRefusal(initial)
615
656
 
616
657
  let artifact: ArtifactRef
@@ -642,7 +683,7 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
642
683
  'ticket body reader is unavailable for --revise-spec-from-ticket',
643
684
  )
644
685
  }
645
- body = await opts.readTicketBody(record.ticket)
686
+ body = await opts.readTicketBody(record.ticket, opts.store, record.repo)
646
687
  if (record.ticket.source === 'hosted' && !opts.prepareTicketAssets) {
647
688
  throw new BuildControlError(
648
689
  'ticket-unavailable',
@@ -674,6 +715,62 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
674
715
  artifact = { kind: 'spec', rev: deposited.revision }
675
716
  }
676
717
 
718
+ if (nodeRevision) {
719
+ const holder = `spec-revision-${crypto.randomUUID()}`
720
+ if (!(await opts.store.claimNodeWriter(opts.slug, holder, 60_000))) {
721
+ throw new BuildControlError('inactive', 'Node writer is busy; retry the spec revision')
722
+ }
723
+ let runnerLease = false
724
+ try {
725
+ // Fence attachment as well as branch writers while publishing.
726
+ // Lease expiry is evaluated by the store's clock, never client time.
727
+ runnerLease = await opts.store.claimLease(opts.slug, holder, 60_000)
728
+ if (!runnerLease)
729
+ throw new BuildControlError(
730
+ 'inactive',
731
+ 'Node runner is busy; retry the spec revision',
732
+ )
733
+ const fresh = (await readBuildFacts(opts.store, opts.slug)).value.state
734
+ assertNodeRevisionEligible(opts.slug, fresh)
735
+ // Do not adopt intervening work or an unrelated escalation as authority.
736
+ if (fresh.lastSeq !== state.lastSeq) {
737
+ throw new BuildControlError(
738
+ 'inactive',
739
+ 'Build changed while preparing the spec; retry. Deposited artifacts remain inert.',
740
+ )
741
+ }
742
+ const published = await opts.store.appendIfCurrent(opts.slug, fresh.lastSeq, {
743
+ actor: KERNEL,
744
+ type: 'spec.revised',
745
+ payload: {
746
+ artifact,
747
+ operator: { user, ...(opts.via ? { via: opts.via } : {}) },
748
+ ...(assets !== undefined ? { assets } : {}),
749
+ },
750
+ })
751
+ if (!published)
752
+ throw new BuildControlError(
753
+ 'inactive',
754
+ 'Build changed while publishing the spec; retry. Deposited artifacts remain inert.',
755
+ )
756
+ return {
757
+ kind: 'answered',
758
+ slug: opts.slug,
759
+ count: 0,
760
+ resolution: 'revise-spec',
761
+ resumed: false,
762
+ nodeRevision: true,
763
+ specRev: artifact.rev,
764
+ }
765
+ } finally {
766
+ try {
767
+ if (runnerLease) await opts.store.releaseLease(opts.slug, holder)
768
+ } finally {
769
+ await opts.store.releaseNodeWriter(opts.slug, holder)
770
+ }
771
+ }
772
+ }
773
+
677
774
  // Re-read at the last durable moment. The PR janitor and abort
678
775
  // acknowledgement may still write while a blocked build is parked.
679
776
  const freshState = (await readBuildFacts(opts.store, opts.slug)).value.state
@@ -685,7 +782,12 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
685
782
  assets = decision.assets
686
783
  authorizedEarlier = true
687
784
  }
688
- const answer = guidance === '' ? SPEC_REVISION_ANSWER : guidance
785
+ const answer =
786
+ guidance === ''
787
+ ? state.kind === 'node'
788
+ ? 'Operator replaced the node spec; recollect and verify'
789
+ : SPEC_REVISION_ANSWER
790
+ : guidance
689
791
  const alsoPaused = freshState.status === 'paused'
690
792
 
691
793
  // Answers must precede spec.revised: the engine parks an answered
@@ -727,6 +829,7 @@ export async function controlBuild(opts: ControlBuildOpts): Promise<BuildControl
727
829
  count: decision.open.length,
728
830
  resolution: 'revise-spec',
729
831
  resumed: alsoPaused,
832
+ ...(state.kind === 'node' ? { nodeRevision: true } : {}),
730
833
  ...(after.specRev !== undefined ? { specRev: after.specRev } : {}),
731
834
  ...(authorizedEarlier ? { authorizedEarlier: true } : {}),
732
835
  ...(signal !== undefined ? { terminalSignal: signal } : {}),
@@ -891,7 +994,7 @@ export interface AbBuildControlOpts {
891
994
  storeRef?: string
892
995
  /** Injected only for --revise-spec-from-ticket. */
893
996
  prepareTicketAssets?: (ref: TicketRef, store: BuildStore, repo: string) => Promise<PinnedAsset[]>
894
- readTicketBody?: (ref: TicketRef) => Promise<string>
997
+ readTicketBody?: (ref: TicketRef, store: BuildStore, repo: string) => Promise<string>
895
998
  /** Injectable adapter seam for unit tests. */
896
999
  openStore?: StoreOpener
897
1000
  }