@defrex/autobuild 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/README.md +5 -13
  2. package/SPEC.md +249 -15
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +130 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/answering-blocked-builds.md +4 -1
  7. package/docs/architecture.md +224 -12
  8. package/docs/build-store.md +3 -41
  9. package/docs/builds.md +2 -0
  10. package/docs/cli.md +14 -0
  11. package/docs/configuration-overview.md +117 -0
  12. package/docs/configuration.md +266 -141
  13. package/docs/dispatcher-hosting.md +18 -33
  14. package/docs/intake.md +2 -0
  15. package/docs/integration-tree.md +16 -5
  16. package/docs/merge-policy.md +1 -3
  17. package/docs/operating.md +1 -2
  18. package/docs/operator-api.md +144 -53
  19. package/docs/operator-surfaces.md +32 -20
  20. package/docs/overview.md +1 -1
  21. package/docs/plugin-authoring.md +27 -1
  22. package/docs/remote-store-protocol.md +259 -91
  23. package/docs/remote-ticket-protocol.md +29 -49
  24. package/docs/restacking.md +45 -0
  25. package/docs/seams.md +8 -8
  26. package/docs/setup.md +34 -129
  27. package/docs/spec-standard.md +4 -2
  28. package/docs/ticket-dependencies.md +8 -0
  29. package/docs/ticket-sources.md +18 -0
  30. package/docs/troubleshooting.md +7 -11
  31. package/docs/upgrading.md +1 -1
  32. package/docs/workspaces.md +4 -4
  33. package/package.json +14 -5
  34. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  35. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  36. package/packages/core/src/accounts/local-credentials.ts +194 -0
  37. package/packages/core/src/accounts/local-inference.ts +106 -0
  38. package/packages/core/src/accounts/local-owner.ts +123 -0
  39. package/packages/core/src/accounts/sensitive.ts +2 -0
  40. package/packages/core/src/cli/accounts.ts +147 -0
  41. package/packages/core/src/cli/binary.ts +3 -1
  42. package/packages/core/src/cli/connect.ts +3 -3
  43. package/packages/core/src/cli/dispatch-frontend.ts +1 -0
  44. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  45. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  46. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  47. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  48. package/packages/core/src/cli/dispatch-repository-feed.ts +107 -26
  49. package/packages/core/src/cli/dispatch.ts +135 -27
  50. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  51. package/packages/core/src/cli/forge-clear.ts +30 -0
  52. package/packages/core/src/cli/help.ts +17 -0
  53. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  54. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  55. package/packages/core/src/cli/init-validation.ts +160 -18
  56. package/packages/core/src/cli/main.ts +72 -0
  57. package/packages/core/src/cli/publication-settlement.ts +4 -1
  58. package/packages/core/src/cli/secrets.ts +173 -0
  59. package/packages/core/src/cli/store-opening.ts +11 -1
  60. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  61. package/packages/core/src/cli/watch.ts +12 -14
  62. package/packages/core/src/config/accounts.ts +101 -0
  63. package/packages/core/src/config/live.ts +14 -1
  64. package/packages/core/src/config/roles.ts +54 -3
  65. package/packages/core/src/config/schema.ts +60 -0
  66. package/packages/core/src/events/catalog.ts +1 -0
  67. package/packages/core/src/events/compatibility.ts +2 -1
  68. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  69. package/packages/core/src/events/payloads.ts +13 -0
  70. package/packages/core/src/events/policy.ts +9 -0
  71. package/packages/core/src/events/repository.ts +75 -2
  72. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +278 -0
  73. package/packages/core/src/kernel/change-presence.ts +74 -8
  74. package/packages/core/src/kernel/engine.ts +8 -0
  75. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  76. package/packages/core/src/kernel/node-polling.ts +40 -7
  77. package/packages/core/src/kernel/node-restack-demand.ts +74 -0
  78. package/packages/core/src/kernel/node-restack-state.ts +5 -1
  79. package/packages/core/src/kernel/node-restack-transaction.ts +33 -1
  80. package/packages/core/src/kernel/read-facts.ts +6 -0
  81. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  82. package/packages/core/src/kernel/reducer.ts +4 -1
  83. package/packages/core/src/kernel/ticket-preparation.ts +66 -0
  84. package/packages/core/src/operator/annotations.ts +6 -0
  85. package/packages/core/src/operator/control.ts +20 -0
  86. package/packages/core/src/operator/index.ts +4 -0
  87. package/packages/core/src/operator/protocol.ts +6 -0
  88. package/packages/core/src/operator/registry.ts +42 -1
  89. package/packages/core/src/operator/tickets.ts +25 -4
  90. package/packages/core/src/plugins/manifest.ts +2 -1
  91. package/packages/core/src/ports/runner/account-env.ts +139 -0
  92. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  93. package/packages/core/src/ports/runner/claude.ts +70 -42
  94. package/packages/core/src/ports/runner/codex.ts +63 -31
  95. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  96. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  97. package/packages/core/src/ports/runner/routing.ts +35 -4
  98. package/packages/core/src/ports/tickets/contract.ts +58 -0
  99. package/packages/core/src/ports/tickets/tree.ts +1 -1
  100. package/packages/core/src/ports/types.ts +28 -7
  101. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  102. package/packages/core/src/ports/workspace/build-execution.ts +6 -1
  103. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  104. package/packages/core/src/ports/workspace/create.ts +2 -0
  105. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  106. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  107. package/packages/core/src/ports/workspace/vercel-sandbox.ts +125 -35
  108. package/packages/core/src/processes/build-runner.ts +32 -1
  109. package/packages/core/src/processes/dispatcher.ts +493 -121
  110. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  111. package/packages/core/src/processes/execution-settlement.ts +21 -3
  112. package/packages/core/src/processes/harvest-runner.ts +68 -8
  113. package/packages/core/src/processes/harvest.ts +11 -16
  114. package/packages/core/src/processes/repo-view.ts +3 -0
  115. package/packages/core/src/project-secrets.ts +105 -0
  116. package/packages/core/src/secret-name.ts +41 -0
  117. package/packages/core/src/store/account-redaction.ts +156 -0
  118. package/packages/core/src/store/artifact-meta.ts +7 -0
  119. package/packages/core/src/store/contract.ts +60 -1
  120. package/packages/core/src/store/memory.ts +4 -0
  121. package/packages/core/src/store/reducer-value-shapes.json +7389 -6647
  122. package/packages/core/src/store/reducer-value-validation.ts +106 -6
  123. package/packages/core/src/store/remote/client.ts +85 -50
  124. package/packages/core/src/store/remote/compatibility.ts +57 -0
  125. package/packages/core/src/store/remote/index.ts +6 -0
  126. package/packages/core/src/store/remote/protocol.ts +8 -1
  127. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  128. package/packages/core/src/store/remote/version.ts +4 -0
  129. package/packages/core/src/store/repo-state-events.ts +4 -2
  130. package/packages/core/src/store/snapshots.ts +16 -3
  131. package/packages/core/src/store/types.ts +2 -0
  132. package/packages/core/src/testing/dispatch-read-budget.ts +266 -5
  133. package/packages/core/src/testing/index.ts +2 -1
  134. package/packages/core/src/testing/reduced-read-budget.ts +560 -5
  135. package/skills/guide/SKILL.md +164 -37
  136. package/skills/guide/references/accounts.md +130 -0
  137. package/skills/guide/references/integration-tree.md +16 -5
  138. package/skills/guide/references/merge-policy.md +1 -3
  139. package/skills/guide/references/operator-api.md +144 -53
  140. package/skills/guide/references/plugin-authoring.md +27 -1
  141. package/skills/guide/references/remote-store-protocol.md +259 -91
  142. package/skills/guide/references/remote-ticket-protocol.md +29 -49
  143. package/skills/guide/references/restacking.md +45 -0
  144. package/skills/guide/references/setup.md +34 -129
  145. package/skills/guide/references/spec-standard.md +4 -2
  146. package/skills/guide/references/ticket-dependencies.md +8 -0
  147. package/skills/harvest/SKILL.md +3 -1
  148. package/skills/harvest-review/SKILL.md +3 -1
  149. package/skills/operate/SKILL.md +26 -11
  150. package/skills/reconcile/SKILL.md +6 -0
  151. package/skills/spec/SKILL.md +1 -1
  152. package/skills/tickets/SKILL.md +10 -5
  153. package/templates/hosted-service/package.json +2 -2
  154. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  155. package/docs/hosted-dispatcher.md +0 -278
  156. package/docs/hosted-service.md +0 -304
  157. package/docs/mcp.md +0 -150
@@ -0,0 +1,123 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import type { Accounts } from '../config/accounts'
3
+ import { refreshChatGPT } from './chatgpt-oauth'
4
+ import type { LocalCredentials } from './local-credentials'
5
+ import type { ChatGPTState } from './chatgpt-state'
6
+
7
+ /** One claimed dispatcher/validator owns renewal. Durable refreshing state is
8
+ * written before HTTP, and uncertain completion is terminal for that generation. */
9
+ export class LocalAccountOwner {
10
+ readonly id = randomUUID()
11
+ constructor(
12
+ readonly credentials: LocalCredentials,
13
+ private readonly refresh = refreshChatGPT,
14
+ ) {}
15
+ claim(name: string): void {
16
+ this.credentials.locked(name, () => {
17
+ const r = this.credentials.load(name)
18
+ if (!r || (r.owner && r.owner !== this.id && !ownerProcessEnded(r.ownerPid)))
19
+ throw new Error('ChatGPT account already owned or missing')
20
+ if (r.status === 'refreshing') r.status = 'failed'
21
+ this.credentials.save(name, { ...r, owner: this.id, ownerPid: process.pid })
22
+ })
23
+ }
24
+ release(name: string): void {
25
+ this.credentials.locked(name, () => {
26
+ const r = this.credentials.load(name)
27
+ if (r?.owner === this.id) {
28
+ delete r.owner
29
+ delete r.ownerPid
30
+ this.credentials.save(name, r)
31
+ }
32
+ })
33
+ }
34
+ async tick(accounts: Accounts, now = Date.now()): Promise<Record<string, string>> {
35
+ const env: Record<string, string> = {}
36
+ for (const [name, descriptor] of Object.entries(accounts)) {
37
+ if (descriptor.kind !== 'chatgpt-subscription') continue
38
+ let r = this.credentials.load(name)
39
+ if (!r || r.owner !== this.id || JSON.stringify(r.descriptor) !== JSON.stringify(descriptor))
40
+ throw new Error('ChatGPT account ownership or descriptor changed; sign in again')
41
+ if (r.status !== 'ready') throw new Error('ChatGPT account failed; sign in again')
42
+ if (now >= Math.max(r.state.earliestRefreshAt ?? 0, r.state.expiresAt - 60000)) {
43
+ const claim = this.credentials.locked(name, () => {
44
+ const current = this.credentials.load(name)
45
+ if (
46
+ !current ||
47
+ current.owner !== this.id ||
48
+ current.generation !== r!.generation ||
49
+ current.status !== 'ready'
50
+ )
51
+ throw new Error('ChatGPT account changed')
52
+ this.credentials.save(name, { ...current, status: 'refreshing' })
53
+ return current
54
+ })
55
+ try {
56
+ const state: ChatGPTState = await this.refresh(claim.state, AbortSignal.timeout(15000))
57
+ this.credentials.locked(name, () => {
58
+ const current = this.credentials.load(name)
59
+ if (
60
+ current?.generation === claim.generation &&
61
+ current.owner === this.id &&
62
+ current.status === 'refreshing'
63
+ )
64
+ this.credentials.save(name, { ...current, state, status: 'ready' })
65
+ })
66
+ } catch {
67
+ this.credentials.locked(name, () => {
68
+ const current = this.credentials.load(name)
69
+ if (current?.generation === claim.generation && current.status === 'refreshing')
70
+ this.credentials.save(name, { ...current, status: 'failed' })
71
+ })
72
+ throw new Error('ChatGPT refresh failed; sign in again')
73
+ }
74
+ r = this.credentials.load(name)!
75
+ }
76
+ if (r.status !== 'ready' || r.state.expiresAt <= now)
77
+ throw new Error('ChatGPT account expired; sign in again')
78
+ env[descriptor.credentialEnv] = r.state.accessToken
79
+ }
80
+ return env
81
+ }
82
+ }
83
+
84
+ /** Unknown ownership and permission errors remain live; only OS proof of exit
85
+ * permits reclaiming a record. An abandoned rotating attempt still fails closed. */
86
+ function ownerProcessEnded(pid: number | undefined): boolean {
87
+ if (!Number.isSafeInteger(pid) || pid! <= 0) return false
88
+ try {
89
+ process.kill(pid!, 0)
90
+ return false
91
+ } catch (error) {
92
+ return (error as NodeJS.ErrnoException).code === 'ESRCH'
93
+ }
94
+ }
95
+
96
+ /** Dispatcher renewal also recovers ready credentials after sleep or downtime.
97
+ * Access expiry is not refresh failure; only the owner may consume refresh state. */
98
+ export async function renewLocalAccounts(
99
+ owner: LocalAccountOwner,
100
+ accounts: Accounts,
101
+ env: Record<string, string | undefined>,
102
+ claimed: Set<string>,
103
+ now = Date.now(),
104
+ ): Promise<void> {
105
+ for (const [name, descriptor] of Object.entries(accounts)) {
106
+ if (descriptor.kind !== 'chatgpt-subscription') continue
107
+ try {
108
+ const record = owner.credentials.load(name)
109
+ if (!record || record.status === 'failed') {
110
+ delete env[descriptor.credentialEnv]
111
+ continue
112
+ }
113
+ owner.claim(name)
114
+ claimed.add(name)
115
+ // Only expose a still-valid access value during the rotating HTTP call.
116
+ if (record.state.expiresAt > now) env[descriptor.credentialEnv] = record.state.accessToken
117
+ else delete env[descriptor.credentialEnv]
118
+ Object.assign(env, await owner.tick({ [name]: descriptor }, now))
119
+ } catch {
120
+ delete env[descriptor.credentialEnv]
121
+ }
122
+ }
123
+ }
@@ -0,0 +1,2 @@
1
+ /** Host-only registry: retain previous generations until process exit. */
2
+ export const sensitiveAccountValues = new Set<string>()
@@ -0,0 +1,147 @@
1
+ import { join } from 'node:path'
2
+ import { connectedProject } from './connect'
3
+ import { parseConfig } from '../config/load'
4
+ import { ProjectCredentials } from './project-credentials'
5
+ import { LocalCredentials } from '../accounts/local-credentials'
6
+ import { transaction, authorizationUrl, exchangeCode } from '../accounts/chatgpt-oauth'
7
+ import type { Exec } from '../ports/workspace/git-worktree'
8
+ import {
9
+ AUTOBUILD_VERSION,
10
+ AUTOBUILD_VERSION_HEADER,
11
+ REMOTE_STORE_PROTOCOL_VERSION,
12
+ REMOTE_STORE_PROTOCOL_VERSION_HEADER,
13
+ } from '../store/remote/version'
14
+
15
+ export async function abAccountsLogin(
16
+ name: string,
17
+ opts: {
18
+ cwd: string
19
+ env: Record<string, string | undefined>
20
+ exec: Exec
21
+ print: (s: string) => void
22
+ destination?: 'local' | 'project'
23
+ signal?: AbortSignal
24
+ browser?: (url: string) => Promise<void>
25
+ },
26
+ ): Promise<void> {
27
+ const project = await connectedProject(opts)
28
+ const account = parseConfig(project.text).accounts[name]
29
+ if (account?.kind !== 'chatgpt-subscription')
30
+ throw new Error('Select a declared ChatGPT subscription account')
31
+ const destination = opts.destination ?? (project.service ? 'project' : 'local')
32
+ if (destination === 'project' && !project.service)
33
+ throw new Error('Project login requires ab connect')
34
+ const credential =
35
+ destination === 'project'
36
+ ? new ProjectCredentials(opts.env).load(project.service!, project.repo)
37
+ : undefined
38
+ if (destination === 'project' && !credential)
39
+ throw new Error('Missing project credential; run ab connect')
40
+ const local = new LocalCredentials(join(project.checkout, '.autobuild'))
41
+ // Host identity is nonsecret. Project credentials themselves are never written here.
42
+ let hostId: string
43
+ if (destination === 'project') {
44
+ if (local.load(name))
45
+ throw new Error(
46
+ 'A local credential already owns this account; use a separate account for the project',
47
+ )
48
+ const response = await fetch(
49
+ `${project.service}/secrets/v1/chatgpt-host?repo=${encodeURIComponent(project.repo)}`,
50
+ {
51
+ headers: {
52
+ authorization: `Bearer ${credential!.token}`,
53
+ [AUTOBUILD_VERSION_HEADER]: AUTOBUILD_VERSION,
54
+ [REMOTE_STORE_PROTOCOL_VERSION_HEADER]: REMOTE_STORE_PROTOCOL_VERSION,
55
+ },
56
+ signal: AbortSignal.timeout(15000),
57
+ redirect: 'error',
58
+ },
59
+ )
60
+ if (!response.ok) throw new Error('Project host identity unavailable')
61
+ const result = await response.json()
62
+ if (
63
+ result?.version !== 1 ||
64
+ typeof result.hostId !== 'string' ||
65
+ !/^urn:uuid:[0-9a-f-]{36}$/.test(result.hostId)
66
+ )
67
+ throw new Error('Invalid project host identity')
68
+ hostId = result.hostId
69
+ } else hostId = local.hostId()
70
+ const previous = destination === 'local' ? local.load(name)?.state : undefined
71
+ opts.print(
72
+ `Continue with ChatGPT: account ${JSON.stringify(name)}, destination ${destination === 'local' ? 'local dispatcher' : 'connected project'}.`,
73
+ )
74
+ const signal = AbortSignal.any([
75
+ AbortSignal.timeout(300000),
76
+ ...(opts.signal ? [opts.signal] : []),
77
+ ])
78
+ let resolveCallback!: (url: URL) => void
79
+ let rejectCallback!: (error: Error) => void
80
+ const received = new Promise<URL>((resolve, reject) => {
81
+ resolveCallback = resolve
82
+ rejectCallback = reject
83
+ })
84
+ void received.catch(() => {})
85
+ const server = Bun.serve({
86
+ hostname: '127.0.0.1',
87
+ port: 0,
88
+ fetch(request) {
89
+ const url = new URL(request.url)
90
+ if (url.pathname !== '/auth/callback') return new Response('Not found', { status: 404 })
91
+ resolveCallback(url)
92
+ return new Response('Return to the terminal to complete sign-in.', {
93
+ headers: { 'cache-control': 'no-store' },
94
+ })
95
+ },
96
+ })
97
+ const abort = () => rejectCallback(new Error('ChatGPT sign-in cancelled or timed out'))
98
+ signal.addEventListener('abort', abort, { once: true })
99
+ try {
100
+ if (signal.aborted) throw new Error('Sign-in cancelled')
101
+ const t = transaction(`http://127.0.0.1:${server.port}/auth/callback`, hostId, previous)
102
+ const url = authorizationUrl(t)
103
+ const opening = (async () => {
104
+ if (opts.browser) await opts.browser(url)
105
+ else {
106
+ const command = process.platform === 'darwin' ? 'open' : 'xdg-open'
107
+ const result = await opts.exec([command, url], { cwd: opts.cwd })
108
+ if (result.exitCode !== 0) throw new Error('Unable to open system browser')
109
+ }
110
+ })()
111
+ void opening.catch(() => {})
112
+ await Promise.race([opening, received.then(() => {})])
113
+ const state = await exchangeCode(t, await received, signal)
114
+ if (destination === 'local') local.install(name, account, state)
115
+ else {
116
+ const response = await fetch(`${project.service}/secrets/v1/chatgpt`, {
117
+ method: 'POST',
118
+ redirect: 'error',
119
+ signal,
120
+ headers: {
121
+ 'content-type': 'application/json',
122
+ authorization: `Bearer ${credential!.token}`,
123
+ [AUTOBUILD_VERSION_HEADER]: AUTOBUILD_VERSION,
124
+ [REMOTE_STORE_PROTOCOL_VERSION_HEADER]: REMOTE_STORE_PROTOCOL_VERSION,
125
+ },
126
+ body: JSON.stringify({
127
+ version: 1,
128
+ repo: project.repo,
129
+ name: account.credentialEnv,
130
+ state,
131
+ }),
132
+ })
133
+ if (!response.ok) throw new Error('Project sign-in write failed')
134
+ const result = await response.json()
135
+ if (result?.version !== 1 || result?.ok !== true)
136
+ throw new Error('Project sign-in write not acknowledged')
137
+ }
138
+ opts.print(`ChatGPT account ${JSON.stringify(name)} saved for ${destination}.`)
139
+ } catch {
140
+ throw new Error(
141
+ `ChatGPT sign-in failed for account ${JSON.stringify(name)}; run ab accounts login again`,
142
+ )
143
+ } finally {
144
+ signal.removeEventListener('abort', abort)
145
+ await server.stop(true)
146
+ }
147
+ }
@@ -3,7 +3,7 @@ import type { DashboardRendererResolver } from './dashboard/render'
3
3
  import { loadDotEnv } from './dotenv'
4
4
  import { parseDispatchArgs } from './dispatch-args'
5
5
  import { launchDispatcher } from './dispatch-launcher'
6
- import { DISPATCH_GENERATION_ENV } from './dispatch-launch-contract'
6
+ import { DISPATCH_GENERATION_ENV, DISPATCH_CONDITIONAL_ENV } from './dispatch-launch-contract'
7
7
  export {
8
8
  usesGenericSessionlessSigintHandler,
9
9
  installSessionlessSigintHandler,
@@ -15,9 +15,11 @@ export async function runBinary(
15
15
  ): Promise<number> {
16
16
  delete process.env.AB_DISPATCH_LAUNCH_CONTEXT
17
17
  delete process.env[DISPATCH_GENERATION_ENV]
18
+ delete process.env[DISPATCH_CONDITIONAL_ENV]
18
19
  if (argv[0] !== '--version') loadDotEnv(join(process.cwd(), '.env'), process.env)
19
20
  delete process.env.AB_DISPATCH_LAUNCH_CONTEXT
20
21
  delete process.env[DISPATCH_GENERATION_ENV]
22
+ delete process.env[DISPATCH_CONDITIONAL_ENV]
21
23
  if (
22
24
  argv[0] === 'dispatch' &&
23
25
  !(argv.length === 2 && argv[1] === '--help') &&
@@ -37,7 +37,7 @@ function requireOperator(env: ConnectOptions['env']) {
37
37
  )
38
38
  throw new Error('connect and disconnect are unavailable inside build or harvest sessions')
39
39
  }
40
- async function project(opts: ConnectOptions) {
40
+ export async function connectedProject(opts: ConnectOptions) {
41
41
  requireOperator(opts.env)
42
42
  const checkout = await resolveMainRepo(opts.cwd, opts.exec)
43
43
  const remote = await opts.exec(['git', 'remote', 'get-url', 'origin'], { cwd: checkout })
@@ -97,7 +97,7 @@ async function atomicConfig(path: string, before: string, after: string) {
97
97
  }
98
98
  export async function abConnect(raw: string | undefined, opts: ConnectOptions): Promise<void> {
99
99
  if (opts.tickets && opts.builds) throw new Error('Choose --tickets or --builds')
100
- const p = await project(opts)
100
+ const p = await connectedProject(opts)
101
101
  if (opts.tickets && (p.table.tickets as { source?: string } | undefined)?.source !== 'hosted')
102
102
  throw new Error('ab connect --tickets requires [tickets] source = "hosted"')
103
103
  const credentials = new ProjectCredentials(opts.env)
@@ -309,7 +309,7 @@ export async function abConnect(raw: string | undefined, opts: ConnectOptions):
309
309
  }
310
310
  export async function abDisconnect(opts: ConnectOptions): Promise<void> {
311
311
  if (opts.tickets && opts.builds) throw new Error('Choose --tickets or --builds')
312
- const p = await project(opts)
312
+ const p = await connectedProject(opts)
313
313
  if (
314
314
  !opts.tickets &&
315
315
  !opts.builds &&
@@ -169,6 +169,7 @@ export class DispatchFrontend {
169
169
  this.clock = opts.clock ?? systemClock
170
170
  this.repositoryFeed = new DispatchRepositoryFeed(this.reader, opts.repo, this.clock)
171
171
  this.standbyResolver = new StandbyIdentityResolver(this.reader, opts.repo, {
172
+ selectHolder: (holder) => this.repositoryFeed.selectHolder(holder),
172
173
  allowLookup: () => this.repositoryFeed.incompleteIdentities,
173
174
  remember: (events, complete) => this.repositoryFeed.remember(events, complete),
174
175
  })
@@ -6,7 +6,16 @@ import { spawnExec } from '../ports/workspace/git-worktree'
6
6
  import { parseDispatchArgs } from './dispatch-args'
7
7
  import { readDispatchUpgrade, readDispatcherRunFacts } from '../store/reduced-reads'
8
8
  import { cachedRuntime } from './dispatch-runtime-cache'
9
- import type { GenerationLaunch } from './dispatch-launch-contract'
9
+ import type {
10
+ GenerationLaunch,
11
+ UpgradeCondition,
12
+ UpgradeGuards,
13
+ UpgradeProjection,
14
+ ConditionalUpgradeResult,
15
+ } from './dispatch-launch-contract'
16
+ import { validChangePosition } from './dispatch-launch-contract'
17
+ import type { UpgradeRun } from '../kernel/dispatch-upgrade'
18
+ type DispatcherRunFacts = Awaited<ReturnType<typeof readDispatcherRunFacts>>['value']
10
19
  import type { Handoff } from '../kernel/dispatch-upgrade'
11
20
 
12
21
  /** Once a held run identifies its journal, readers retain that transport
@@ -67,66 +76,138 @@ export async function readHandoff(
67
76
  const selected = live ? state?.prepared : state?.handoff
68
77
  if (!selected || (!live && state?.completed) || state?.failure) return undefined
69
78
  const facts = (await readDispatcherRunFacts(opened.store, opened.repo, launch.run)).value
70
- const handoff = selected.payload
71
- if (
72
- (!live &&
73
- (facts.stop?.type !== 'dispatcher.run-stopped' ||
74
- facts.stop.payload.outcome !== 'normal' ||
75
- facts.stop.payload.signal !== undefined)) ||
76
- facts.stopRequest ||
77
- handoff.lineage !== launch.lineage
78
- )
79
- return undefined
80
- const expected = join(launch.checkout, '.autobuild/runtime', handoff.cacheId, 'distribution')
81
- if (
82
- resolve(handoff.root) !== expected ||
83
- dirname(dirname(handoff.root)) !== join(launch.checkout, '.autobuild/runtime')
84
- )
85
- return undefined
86
- const candidate = await cachedRuntime(handoff.root)
87
- if (candidate?.id !== handoff.cacheId) return undefined
88
- return handoff
79
+ return validateHandoff(launch, selectHandoff(launch, state, facts, live))
89
80
  } finally {
90
81
  await opened.store.close()
91
82
  }
92
83
  }
93
84
 
85
+ /** Durable selection is separate from local cache validation. */
86
+ function selectHandoff(
87
+ launch: GenerationLaunch,
88
+ state: UpgradeRun | undefined,
89
+ facts: DispatcherRunFacts,
90
+ live: boolean,
91
+ ): Handoff | null {
92
+ const selected = live ? state?.prepared : state?.handoff
93
+ if (!selected || (!live && state?.completed) || state?.failure) return null
94
+ const handoff = selected.payload
95
+ if (
96
+ (!live &&
97
+ (facts.stop?.type !== 'dispatcher.run-stopped' ||
98
+ facts.stop.payload.outcome !== 'normal' ||
99
+ facts.stop.payload.signal !== undefined)) ||
100
+ facts.stopRequest ||
101
+ handoff.lineage !== launch.lineage
102
+ )
103
+ return null
104
+ return handoff
105
+ }
106
+ async function validateHandoff(
107
+ launch: GenerationLaunch,
108
+ handoff: Handoff | null,
109
+ ): Promise<Handoff | undefined> {
110
+ if (!handoff || handoff.lineage !== launch.lineage || handoff.run !== launch.run) return undefined
111
+ const expected = join(launch.checkout, '.autobuild/runtime', handoff.cacheId, 'distribution')
112
+ if (
113
+ resolve(handoff.root) !== expected ||
114
+ dirname(dirname(handoff.root)) !== join(launch.checkout, '.autobuild/runtime')
115
+ )
116
+ return undefined
117
+ return (await cachedRuntime(handoff.root))?.id === handoff.cacheId ? handoff : undefined
118
+ }
119
+ async function localGuards(launch: GenerationLaunch, guards: UpgradeGuards) {
120
+ return {
121
+ handoff: (await validateHandoff(launch, guards.handoff)) ?? null,
122
+ rollbackRetained:
123
+ guards.rollbackRecorded &&
124
+ (!guards.failedRoot || rollbackRuntimeRetained(guards.failedRoot, launch.lineage!)),
125
+ }
126
+ }
127
+ export function readUpgradeProjection(
128
+ launch: GenerationLaunch,
129
+ argv: string[],
130
+ env: Record<string, string | undefined>,
131
+ ): Promise<UpgradeProjection>
132
+ export function readUpgradeProjection(
133
+ launch: GenerationLaunch,
134
+ argv: string[],
135
+ env: Record<string, string | undefined>,
136
+ options: { openStore?: StoreOpener; condition?: UpgradeCondition },
137
+ ): Promise<UpgradeProjection | ConditionalUpgradeResult>
94
138
  export async function readUpgradeProjection(
95
139
  launch: GenerationLaunch,
96
140
  argv: string[],
97
141
  env: Record<string, string | undefined>,
98
- ) {
99
- const opened = await openGenerationStore(launch, argv, env)
142
+ options: { openStore?: StoreOpener; condition?: UpgradeCondition } = {},
143
+ ): Promise<UpgradeProjection | ConditionalUpgradeResult> {
144
+ const opened = await openGenerationStore(launch, argv, env, options.openStore)
100
145
  try {
146
+ const condition = options.condition
147
+ // Sample before projection reads: concurrent appends invalidate the next poll.
148
+ const position =
149
+ condition && launch.journal
150
+ ? await opened.store.getRepoChangePosition(opened.repo)
151
+ : undefined
152
+ if (position !== undefined && !validChangePosition(position))
153
+ throw new Error('invalid upgrade change position')
154
+ if (position !== undefined && condition?.position === position && condition.guards) {
155
+ return {
156
+ conditionalVersion: 1,
157
+ kind: 'unchanged',
158
+ identity: condition.identity,
159
+ position,
160
+ ...(await localGuards(launch, condition.guards)),
161
+ }
162
+ }
101
163
  const record = await opened.store.getRepo(opened.repo)
102
164
  const journal =
103
165
  launch.journal ??
104
166
  (record?.lease?.holder === launch.run
105
167
  ? { storeRef: opened.storeRef, repo: opened.repo }
106
168
  : undefined)
107
- if (!journal) return { version: 1, handoff: null, takeover: false }
108
- const handoff = await readHandoff({ ...launch, journal }, argv, env, true)
109
- const upgrades = (await readDispatchUpgrade(opened.store, opened.repo)).value
110
- const state = upgrades.runs[launch.run!]
111
- const rollbackRecorded =
112
- !!launch.rollback && upgrades.rollbackIds.includes(launch.rollback.correlation)
113
- const hold = launch.lineage ? upgrades.holds[launch.lineage] : undefined
114
- return {
115
- version: 1,
116
- journal,
117
- handoff: handoff ?? null,
118
- rollbackVersion: 1,
119
- rollbackRetained:
120
- rollbackRecorded &&
121
- (!hold || rollbackRuntimeRetained(hold.payload.failedRoot, launch.lineage!)),
122
- takeover: !!state?.takeover,
123
- takeoverAt: state?.takeover?.ts,
124
- takeoverPayload: state?.takeover?.payload,
125
- completed: !!state?.completed,
126
- accepted: !!state?.handoff,
127
- successor: state?.request?.payload.successor,
128
- released: !!state?.released,
169
+ let projection: UpgradeProjection = { version: 1, handoff: null, takeover: false }
170
+ let guards: UpgradeGuards | undefined
171
+ if (journal) {
172
+ const upgrades = (await readDispatchUpgrade(opened.store, opened.repo)).value
173
+ const state = upgrades.runs[launch.run!]
174
+ const facts =
175
+ launch.run && launch.lineage && record && state?.prepared && !state.failure
176
+ ? (await readDispatcherRunFacts(opened.store, opened.repo, launch.run)).value
177
+ : undefined
178
+ const rollbackRecorded =
179
+ !!launch.rollback && upgrades.rollbackIds.includes(launch.rollback.correlation)
180
+ guards = {
181
+ handoff: facts ? selectHandoff(launch, state, facts, true) : null,
182
+ rollbackRecorded,
183
+ failedRoot:
184
+ rollbackRecorded && launch.lineage
185
+ ? (upgrades.holds[launch.lineage]?.payload.failedRoot ?? null)
186
+ : null,
187
+ }
188
+ projection = {
189
+ version: 1,
190
+ journal,
191
+ rollbackVersion: 1,
192
+ ...(await localGuards(launch, guards)),
193
+ takeover: !!state?.takeover,
194
+ takeoverAt: state?.takeover?.ts,
195
+ takeoverPayload: state?.takeover?.payload,
196
+ completed: !!state?.completed,
197
+ accepted: !!state?.handoff,
198
+ successor: state?.request?.payload.successor,
199
+ released: !!state?.released,
200
+ }
129
201
  }
202
+ return condition
203
+ ? {
204
+ conditionalVersion: 1,
205
+ kind: 'full',
206
+ identity: condition.identity,
207
+ projection,
208
+ ...(position !== undefined && guards ? { position, guards } : {}),
209
+ }
210
+ : projection
130
211
  } finally {
131
212
  await opened.store.close()
132
213
  }