@defrex/autobuild 1.3.0 → 1.4.1

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 (144) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +307 -27
  3. package/docs/accounts.md +38 -0
  4. package/docs/architecture.md +198 -25
  5. package/docs/build-store.md +18 -0
  6. package/docs/builds.md +5 -1
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +38 -19
  9. package/docs/dispatcher-hosting.md +42 -0
  10. package/docs/dispatcher.md +41 -0
  11. package/docs/forges.md +5 -0
  12. package/docs/integration-tree.md +8 -0
  13. package/docs/operating.md +11 -3
  14. package/docs/operator-api.md +37 -4
  15. package/docs/plugin-authoring.md +45 -1
  16. package/docs/remote-store-protocol.md +262 -42
  17. package/docs/remote-ticket-protocol.md +12 -10
  18. package/docs/restacking.md +60 -3
  19. package/docs/setup.md +37 -8
  20. package/docs/skills.md +1 -1
  21. package/docs/spec-standard.md +37 -3
  22. package/docs/troubleshooting.md +9 -0
  23. package/docs/workspaces.md +1 -1
  24. package/package.json +4 -3
  25. package/packages/core/src/accounts/availability.ts +96 -0
  26. package/packages/core/src/accounts/local-owner.ts +49 -2
  27. package/packages/core/src/cli/attention.ts +2 -0
  28. package/packages/core/src/cli/binary.ts +17 -1
  29. package/packages/core/src/cli/context.ts +62 -0
  30. package/packages/core/src/cli/dashboard/model.ts +12 -3
  31. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  32. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  33. package/packages/core/src/cli/dashboard/render.ts +46 -5
  34. package/packages/core/src/cli/dispatch-args.ts +27 -3
  35. package/packages/core/src/cli/dispatch-frontend.ts +187 -53
  36. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  38. package/packages/core/src/cli/dispatch-repository-feed.ts +45 -9
  39. package/packages/core/src/cli/dispatch.ts +145 -11
  40. package/packages/core/src/cli/harvest.ts +2 -1
  41. package/packages/core/src/cli/help.ts +16 -3
  42. package/packages/core/src/cli/historical-build-state.ts +6 -0
  43. package/packages/core/src/cli/main.ts +15 -2
  44. package/packages/core/src/cli/publication-settlement.ts +17 -0
  45. package/packages/core/src/cli/remote-poll.ts +11 -1
  46. package/packages/core/src/cli/repository-status.ts +11 -0
  47. package/packages/core/src/cli/status.ts +7 -1
  48. package/packages/core/src/cli/wait.ts +9 -2
  49. package/packages/core/src/cli/watch.ts +38 -3
  50. package/packages/core/src/config/roles.ts +16 -1
  51. package/packages/core/src/events/catalog.ts +7 -0
  52. package/packages/core/src/events/payloads.ts +85 -2
  53. package/packages/core/src/events/policy.ts +10 -0
  54. package/packages/core/src/events/repository.ts +35 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +189 -0
  56. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  57. package/packages/core/src/kernel/engine.ts +19 -12
  58. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  59. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  60. package/packages/core/src/kernel/log-index.ts +1 -1
  61. package/packages/core/src/kernel/node-landing.ts +27 -10
  62. package/packages/core/src/kernel/node-restack-demand.ts +1 -0
  63. package/packages/core/src/kernel/node-restack-state.ts +16 -1
  64. package/packages/core/src/kernel/node-restack-transaction.ts +14 -0
  65. package/packages/core/src/kernel/read-facts.ts +114 -9
  66. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  67. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  68. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  69. package/packages/core/src/kernel/reducer.ts +20 -2
  70. package/packages/core/src/kernel/replay-retention.ts +176 -0
  71. package/packages/core/src/kernel/target-lineage.ts +65 -0
  72. package/packages/core/src/kernel/target-observation.ts +117 -0
  73. package/packages/core/src/operator/registry.ts +5 -13
  74. package/packages/core/src/operator/tickets.ts +8 -2
  75. package/packages/core/src/plugin-sdk/index.ts +1 -0
  76. package/packages/core/src/ports/forge/fake.ts +22 -0
  77. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  78. package/packages/core/src/ports/forge/github.ts +42 -10
  79. package/packages/core/src/ports/forge/local-git.ts +16 -1
  80. package/packages/core/src/ports/types.ts +58 -4
  81. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  82. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  83. package/packages/core/src/ports/workspace/create.ts +2 -0
  84. package/packages/core/src/ports/workspace/distribution-archive.ts +14 -4
  85. package/packages/core/src/ports/workspace/fake.ts +4 -0
  86. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  87. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  88. package/packages/core/src/processes/build-runner.ts +240 -111
  89. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  90. package/packages/core/src/processes/dispatcher.ts +262 -80
  91. package/packages/core/src/processes/execution-no-progress.ts +7 -0
  92. package/packages/core/src/processes/harvest-runner.ts +6 -7
  93. package/packages/core/src/processes/publication-state.ts +2 -1
  94. package/packages/core/src/processes/repo-view.ts +22 -0
  95. package/packages/core/src/processes/tick-publication.ts +35 -47
  96. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  97. package/packages/core/src/scenarios/harness.ts +7 -0
  98. package/packages/core/src/store/adapter.ts +9 -0
  99. package/packages/core/src/store/build-scope.ts +28 -0
  100. package/packages/core/src/store/contract.ts +125 -0
  101. package/packages/core/src/store/event-reads.ts +156 -0
  102. package/packages/core/src/store/local/schema.ts +11 -0
  103. package/packages/core/src/store/local/store.ts +117 -2
  104. package/packages/core/src/store/memory.ts +237 -0
  105. package/packages/core/src/store/phase-session.ts +47 -0
  106. package/packages/core/src/store/reduced-reads.ts +8 -0
  107. package/packages/core/src/store/reducer-value-shapes.json +6262 -5227
  108. package/packages/core/src/store/reducer-value-validation.ts +3 -0
  109. package/packages/core/src/store/reducer-values.ts +62 -2
  110. package/packages/core/src/store/remote/client.ts +161 -16
  111. package/packages/core/src/store/remote/compatibility.ts +177 -46
  112. package/packages/core/src/store/remote/errors.ts +16 -0
  113. package/packages/core/src/store/remote/index.ts +11 -0
  114. package/packages/core/src/store/remote/protocol.ts +22 -0
  115. package/packages/core/src/store/remote/released-clients.json +48 -0
  116. package/packages/core/src/store/remote/released-clients.ts +88 -0
  117. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  118. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  119. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  120. package/packages/core/src/store/remote/version.ts +5 -2
  121. package/packages/core/src/store/repo-state-events.ts +4 -3
  122. package/packages/core/src/store/scan-cadence.ts +15 -0
  123. package/packages/core/src/store/session-handle.ts +18 -0
  124. package/packages/core/src/store/types.ts +27 -6
  125. package/packages/core/src/testing/dispatch-read-budget.ts +313 -2
  126. package/packages/core/src/testing/index.ts +5 -0
  127. package/packages/core/src/testing/reduced-read-budget.ts +728 -5
  128. package/skills/guide/SKILL.md +201 -18
  129. package/skills/guide/references/accounts.md +38 -0
  130. package/skills/guide/references/integration-tree.md +8 -0
  131. package/skills/guide/references/operator-api.md +37 -4
  132. package/skills/guide/references/plugin-authoring.md +45 -1
  133. package/skills/guide/references/remote-store-protocol.md +262 -42
  134. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  135. package/skills/guide/references/restacking.md +60 -3
  136. package/skills/guide/references/setup.md +37 -8
  137. package/skills/guide/references/spec-standard.md +37 -3
  138. package/skills/implement/SKILL.md +12 -3
  139. package/skills/operate/SKILL.md +87 -15
  140. package/skills/plan/SKILL.md +27 -4
  141. package/skills/plan-review/SKILL.md +22 -2
  142. package/skills/reconcile/SKILL.md +10 -1
  143. package/skills/spec/SKILL.md +7 -4
  144. package/templates/hosted-service/package.json +2 -2
@@ -0,0 +1,94 @@
1
+ import type { Exec } from '../ports/workspace/git-worktree'
2
+ import type { DispatchPlacement } from '../kernel/dispatch-placement'
3
+ import { RemoteBuildStore } from '../store/remote/client'
4
+ import { resolveRepoState, isRemoteStoreRef } from './repo-state'
5
+ import { projectToken } from './project-credentials'
6
+
7
+ export const TAKEOVER_WARNING =
8
+ 'Warning: --takeover dispatches locally and can displace the hosted dispatcher.'
9
+
10
+ export class DispatchPlacementStartupError extends Error {
11
+ readonly code = 'DISPATCH_PLACEMENT_UNREADABLE'
12
+ constructor(cause: unknown, secrets: string[] = []) {
13
+ let detail = cause instanceof Error ? cause.message : String(cause)
14
+ for (const secret of secrets) if (secret) detail = detail.split(secret).join('[redacted]')
15
+ detail = detail.replace(/https?:\/\/[^\s]+/g, (url) => {
16
+ try {
17
+ const parsed = new URL(url)
18
+ return `${parsed.origin}${parsed.pathname}`
19
+ } catch {
20
+ return '[redacted URL]'
21
+ }
22
+ })
23
+ super(
24
+ `Cannot read dispatch placement: ${detail}. Use --viewer to watch, or --takeover to dispatch locally and potentially displace hosted dispatch.`,
25
+ { cause },
26
+ )
27
+ this.name = 'DispatchPlacementStartupError'
28
+ }
29
+ }
30
+
31
+ export interface DispatchModeOptions {
32
+ viewer?: boolean
33
+ takeover?: boolean
34
+ dispatchedBy?: string
35
+ repository?: string
36
+ intake?: boolean
37
+ targetRepo: string
38
+ repo?: string
39
+ storeRef?: string
40
+ env: Record<string, string | undefined>
41
+ exec: Exec
42
+ stderr: (message: string) => void
43
+ }
44
+ export interface PlacementReader {
45
+ getDispatchPlacement(repo: string): Promise<DispatchPlacement>
46
+ close(): Promise<void>
47
+ }
48
+ export async function selectDispatchMode(
49
+ opts: DispatchModeOptions,
50
+ deps: {
51
+ resolve?: typeof resolveRepoState
52
+ open?: (url: string, token: string | undefined) => PlacementReader
53
+ } = {},
54
+ ): Promise<{ viewer: boolean; dispatchedBy?: string }> {
55
+ if (opts.viewer && opts.takeover) throw new Error('--viewer and --takeover cannot be combined')
56
+ if (opts.viewer)
57
+ return {
58
+ viewer: true,
59
+ ...(opts.dispatchedBy !== undefined ? { dispatchedBy: opts.dispatchedBy } : {}),
60
+ }
61
+ if (opts.repository || opts.env.AB_REPOSITORY?.trim()) return { viewer: false }
62
+ if (opts.takeover) {
63
+ opts.stderr(TAKEOVER_WARNING)
64
+ return { viewer: false }
65
+ }
66
+ let token: string | undefined
67
+ let placement: DispatchPlacement
68
+ try {
69
+ const state = await (deps.resolve ?? resolveRepoState)({
70
+ targetRepo: opts.targetRepo,
71
+ exec: opts.exec,
72
+ ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
73
+ ...(opts.env.AB_STORE !== undefined ? { envStore: opts.env.AB_STORE } : {}),
74
+ })
75
+ if (!isRemoteStoreRef(state.storeRef)) return { viewer: false }
76
+ const repo = opts.repo ?? state.repo
77
+ token = projectToken(state.storeRef, repo, opts.env)
78
+ const reader = (deps.open ?? ((url, token) => new RemoteBuildStore({ url, token })))(
79
+ state.storeRef,
80
+ token,
81
+ )
82
+ try {
83
+ placement = await reader.getDispatchPlacement(repo)
84
+ } finally {
85
+ await reader.close()
86
+ }
87
+ } catch (cause) {
88
+ throw new DispatchPlacementStartupError(cause, [token ?? '', opts.env.AB_TOKEN ?? ''])
89
+ }
90
+ if (placement.status !== 'known' || !placement.placement.hosted) return { viewer: false }
91
+ if (opts.intake !== undefined)
92
+ throw new Error('--viewer cannot set startup intake; use --takeover to dispatch locally')
93
+ return { viewer: true, dispatchedBy: new URL(placement.placement.origin).host }
94
+ }
@@ -1,3 +1,8 @@
1
+ import { hostname } from 'node:os'
2
+ import { selectedExecutionAccounts } from '../config/roles'
3
+ import { LocalCredentials } from '../accounts/local-credentials'
4
+ import { inspectLocalAccountEnvironment } from '../accounts/local-owner'
5
+ import { missingAccountCredentials, MissingAccountCredentialsError } from '../accounts/availability'
1
6
  import type { BuildStore } from '../store/types'
2
7
  import { DISPATCHER } from '../events/envelope'
3
8
  import type { Handoff } from '../kernel/dispatch-upgrade'
@@ -176,6 +181,25 @@ async function runGenerationPreflight(
176
181
  config.accounts,
177
182
  )
178
183
  const facts = (await readDispatcherRunFacts(opened.store, opened.repo, handoff.run)).value
184
+ const start = facts.start
185
+ const predecessorPid =
186
+ start?.type === 'dispatcher.run-started' && start.payload.host === hostname()
187
+ ? start.payload.pid
188
+ : undefined
189
+ const accounts = selectedExecutionAccounts(config)
190
+ const available = inspectLocalAccountEnvironment(
191
+ new LocalCredentials(join(launch.checkout, '.autobuild')),
192
+ accounts,
193
+ env,
194
+ predecessorPid,
195
+ )
196
+ const missing = missingAccountCredentials(
197
+ accounts,
198
+ available,
199
+ 'environment',
200
+ config.workspace.provider,
201
+ )
202
+ if (missing.length) throw new MissingAccountCredentialsError(missing)
179
203
  if (facts.stopRequest || facts.stop)
180
204
  throw new Error('predecessor stopped during preflight')
181
205
  },
@@ -202,6 +226,25 @@ async function runGenerationPreflight(
202
226
  (current.completed &&
203
227
  facts.stop?.type === 'dispatcher.run-stopped' &&
204
228
  facts.stop.payload.outcome === 'normal'))
229
+ if (ready) {
230
+ const config = await loadConfig(join(launch.checkout, 'autobuild.toml'))
231
+ const accounts = selectedExecutionAccounts(config)
232
+ const available = inspectLocalAccountEnvironment(
233
+ new LocalCredentials(join(launch.checkout, '.autobuild')),
234
+ accounts,
235
+ env,
236
+ )
237
+ const missing = missingAccountCredentials(
238
+ accounts,
239
+ available,
240
+ 'environment',
241
+ config.workspace.provider,
242
+ )
243
+ if (missing.length) {
244
+ await failure(new MissingAccountCredentialsError(missing).message)
245
+ return false
246
+ }
247
+ }
205
248
  if (ready && (await opened.store.claimRepoLease(opened.repo, launch.run, 60_000))) {
206
249
  await opened.store.appendRepo(opened.repo, {
207
250
  actor: DISPATCHER,
@@ -1,3 +1,4 @@
1
+ import { CursorTooOldError, REPOSITORY_TAIL_WINDOW } from '../store/event-reads'
1
2
  import { DISPATCH_HANDOFF_EVENT_TYPES } from '../store/repo-state-events'
2
3
  import { type RepositoryEvent, validateRepositoryEventWrite } from '../events/repository'
3
4
  import { defineReducer } from '../kernel/incremental'
@@ -105,6 +106,7 @@ export class DispatchRepositoryFeed {
105
106
  refresh(persist = true): Promise<RepositoryEvent[]> {
106
107
  let result: RepositoryEvent[] = []
107
108
  const next = this.tail.then(async () => {
109
+ let holder = this.holder
108
110
  let cursor = this.cursor
109
111
  let retained = this.retained
110
112
  let incompleteIdentities = this.incompleteIdentities
@@ -125,7 +127,11 @@ export class DispatchRepositoryFeed {
125
127
  dispatchFrontendReducer,
126
128
  )
127
129
  let restored = false
128
- if (snapshot && snapshot.cursor <= high) {
130
+ if (
131
+ snapshot &&
132
+ snapshot.cursor <= high &&
133
+ high - snapshot.cursor <= REPOSITORY_TAIL_WINDOW
134
+ ) {
129
135
  try {
130
136
  const state = snapshot.state as {
131
137
  retained: RepositoryEvent[]
@@ -145,7 +151,7 @@ export class DispatchRepositoryFeed {
145
151
  throw new Error('invalid retained fact')
146
152
  if (state.holder !== undefined && typeof state.holder !== 'string')
147
153
  throw new Error('invalid holder')
148
- this.holder = state.holder
154
+ holder = state.holder
149
155
  retained = dispatchFrontendReducer.advance({ ...state }, []).retained
150
156
  incompleteIdentities = true
151
157
  if (state.incompleteIdentities && retained.length === state.retained.length) {
@@ -165,13 +171,13 @@ export class DispatchRepositoryFeed {
165
171
  retained = dispatchFrontendReducer.reduce(seed)
166
172
  cursor = Math.max(high, seed.at(-1)?.seq ?? 0)
167
173
  }
168
- delta = await this.store.getRepoEvents(this.repo, cursor)
174
+ delta = await this.readStartupTail(cursor)
169
175
  this.validate(delta, cursor, true)
170
176
  // A failed prelaunch seed must not skip this invocation's config/start
171
177
  // even if a competing run advanced the bounded seed's anchor.
172
- if (this.recovery) {
173
- const recovery = await this.store.getRepoEvents(this.repo, this.boundary ?? 0)
174
- this.validate(recovery, this.boundary ?? 0, true)
178
+ if (this.recovery && this.boundary !== undefined) {
179
+ const recovery = await this.readStartupTail(this.boundary)
180
+ this.validate(recovery, this.boundary, true)
175
181
  delta = [...new Map([...delta, ...recovery].map((e) => [e.seq, e])).values()].sort(
176
182
  (a, b) => a.seq - b.seq,
177
183
  )
@@ -181,14 +187,16 @@ export class DispatchRepositoryFeed {
181
187
  this.validate(delta, cursor, true)
182
188
  // A standby correlation may have supplied an older identity while the
183
189
  // delta read was pending. Keep those memoized facts in this commit.
190
+ holder = this.holder
184
191
  retained = this.retained
185
192
  incompleteIdentities = this.incompleteIdentities
186
193
  }
187
194
  if (delta.length > 0)
188
195
  retained = dispatchFrontendReducer.advance(
189
- { retained, incompleteIdentities, holder: this.holder },
196
+ { retained, incompleteIdentities, holder },
190
197
  delta,
191
198
  ).retained
199
+ this.holder = holder
192
200
  this.cursor = Math.max(cursor, delta.at(-1)?.seq ?? 0)
193
201
  this.incompleteIdentities = true
194
202
  if (restoredKey !== undefined) {
@@ -202,8 +210,36 @@ export class DispatchRepositoryFeed {
202
210
  result = delta
203
211
  if (persist) await this.save()
204
212
  })
205
- this.tail = next.catch(() => {})
206
- return next.then(() => result)
213
+ const recovered = next.catch(async (error) => {
214
+ if (!(error instanceof CursorTooOldError)) throw error
215
+ const high = await this.store.getRepoHighWater(this.repo)
216
+ const seed = await this.store.getRepoStateEvents(this.repo)
217
+ this.validate(seed, 0, false)
218
+ const cursor = Math.max(high, seed.at(-1)?.seq ?? 0)
219
+ const delta = await this.readStartupTail(cursor)
220
+ this.validate(delta, cursor, true)
221
+ this.replaceRetained(
222
+ dispatchFrontendReducer.advance(
223
+ { retained: dispatchFrontendReducer.reduce(seed), incompleteIdentities: true },
224
+ delta,
225
+ ).retained,
226
+ )
227
+ this.cursor = Math.max(cursor, delta.at(-1)?.seq ?? 0)
228
+ this.incompleteIdentities = true
229
+ this.ready = true
230
+ this.recovery = false
231
+ this.boundary = undefined
232
+ result = delta
233
+ if (persist) await this.save()
234
+ })
235
+ this.tail = recovered.catch(() => {})
236
+ return recovered.then(() => result)
237
+ }
238
+
239
+ private readStartupTail(cursor: number): Promise<RepositoryEvent[]> {
240
+ if (!this.store.getRepositoryTail)
241
+ throw new Error('dashboard restoration requires getRepositoryTail')
242
+ return this.store.getRepositoryTail(this.repo, cursor)
207
243
  }
208
244
 
209
245
  private replaceRetained(events: RepositoryEvent[]): void {
@@ -1,3 +1,11 @@
1
+ import { selectDispatchMode } from './dispatch-mode'
2
+ import { createTerminalModeController } from './terminal-restore'
3
+ import { inspectLocalAccountEnvironment } from '../accounts/local-owner'
4
+ import {
5
+ applyProjectAccountSnapshot,
6
+ missingAccountCredentials,
7
+ MissingAccountCredentialsError,
8
+ } from '../accounts/availability'
1
9
  import { LocalCredentials } from '../accounts/local-credentials'
2
10
  import { LocalAccountOwner, renewLocalAccounts } from '../accounts/local-owner'
3
11
  import { accountRedactor, redactAccountStore } from '../store/account-redaction'
@@ -92,7 +100,12 @@ import {
92
100
  type PipelineSourceFailure,
93
101
  type PipelineSourceMeta,
94
102
  } from '../config/pipeline-source'
95
- import { effectiveRuntimeReferences, roleKeyWarnings, SLUG_ROLE } from '../config/roles'
103
+ import {
104
+ effectiveRuntimeReferences,
105
+ selectedExecutionAccounts,
106
+ roleKeyWarnings,
107
+ SLUG_ROLE,
108
+ } from '../config/roles'
96
109
  import type { Config } from '../config/schema'
97
110
  import { loadPlugins, pluginResolutionKind } from '../plugins/load'
98
111
  import type { PluginRegistry } from '../plugins/registry'
@@ -300,7 +313,8 @@ interface ResumePrompt {
300
313
  /** The real adapters the loop drives — resolved by `wire` (default: the
301
314
  * production ports; tests inject fakes). */
302
315
  export interface DispatchWiring {
303
- renewAccounts?: (authority: { repo: string; run: string }) => Promise<void>
316
+ inspectAccounts?: () => Record<string, string | undefined>
317
+ renewAccounts?: (authority?: { repo: string; run: string }) => Promise<void>
304
318
  releaseAccounts?: () => Promise<void>
305
319
 
306
320
  credentialIssuer?: typeof delegateCredential
@@ -360,6 +374,9 @@ const DEFAULT_TIMERS: TimerScheduler = {
360
374
  }
361
375
 
362
376
  export interface DispatchOpts {
377
+ takeover?: boolean
378
+ viewer?: boolean
379
+ dispatchedBy?: string
363
380
  /** Repo the dispatcher serves (§12: one dispatcher per repo) — the cwd, or
364
381
  * in origin mode a private scratch root. Filesystem consumers only.
365
382
  * Callers without a checkout may pass a non-filesystem identity token
@@ -552,16 +569,22 @@ async function defaultWire(
552
569
  if (opts.env.AB_PROJECT_SECRETS_FAILED === '1')
553
570
  for (const name of JSON.parse(opts.env.AB_PROJECT_SECRETS_UNAVAILABLE ?? '[]') as string[])
554
571
  delete opts.env[name]
555
- let accounts = config.accounts
572
+ let allAccounts = config.accounts
573
+ let accounts = selectedExecutionAccounts(config)
574
+ // Origin execution accepts only the project snapshot, including an empty one.
575
+ if (originMode) {
576
+ const snapshot = JSON.parse(opts.env.AB_PROJECT_ACCOUNT_ENV ?? '{}') as Record<string, string>
577
+ applyProjectAccountSnapshot(allAccounts, opts.env, snapshot)
578
+ }
556
579
  const credentials = new LocalCredentials(join(state.checkout, '.autobuild'))
557
580
  const owner = new LocalAccountOwner(credentials)
558
581
  const claimed = new Set<string>()
559
582
  let renewal: Promise<void> | undefined
560
583
  let accountTimer: ReturnType<typeof setInterval> | undefined
561
- const renewAccounts = async (authority: { repo: string; run: string }) => {
584
+ const renewAccounts = async (authority?: { repo: string; run: string }) => {
562
585
  if (opts.repository || !Object.values(accounts).some((a) => a.kind === 'chatgpt-subscription'))
563
586
  return
564
- if (!accountTimer) {
587
+ if (authority && !accountTimer) {
565
588
  accountTimer = setInterval(() => {
566
589
  void (async () => {
567
590
  const held = await opened.store.getRepo(authority.repo)
@@ -592,9 +615,9 @@ async function defaultWire(
592
615
  }
593
616
  opened.store = redactAccountStore(
594
617
  opened.store,
595
- accountRedactor(() => accounts, opts.env),
618
+ accountRedactor(() => allAccounts, opts.env),
596
619
  )
597
- let runtimeReferences = effectiveRuntimeReferences(config)
620
+ let runtimeReferences = effectiveRuntimeReferences(config, { includeUnusedAccounts: false })
598
621
  // A local override relocates the whole tree. Remote stores still need local
599
622
  // scratch beneath the repository default. Plugin factories receive only
600
623
  // their explicit config plus repository/environment context.
@@ -607,7 +630,8 @@ async function defaultWire(
607
630
  env: opts.env,
608
631
  storeRef: opened.storeRef,
609
632
  runtimeReferences: () => runtimeReferences,
610
- accounts: () => accounts,
633
+ accounts: () => allAccounts,
634
+ executionAccounts: () => accounts,
611
635
  sandboxSetupCommand: config.commands.setup,
612
636
  sandboxRoot: resolve(join(opened.localStateRoot, 'orchestrator-sandboxes')),
613
637
  sandboxEnvironmentVariables: config.orchestrator.sandbox.environmentVariables,
@@ -631,6 +655,8 @@ async function defaultWire(
631
655
  return {
632
656
  store: opened.store,
633
657
  renewAccounts,
658
+ inspectAccounts: () =>
659
+ inspectLocalAccountEnvironment(credentials, accounts, opts.env, undefined, true),
634
660
  releaseAccounts,
635
661
  tickets,
636
662
  forge,
@@ -647,8 +673,18 @@ async function defaultWire(
647
673
  clock: systemClock,
648
674
  plugins,
649
675
  updateRuntimeReferences: (effectiveConfig) => {
650
- accounts = effectiveConfig.accounts
651
- runtimeReferences = effectiveRuntimeReferences(effectiveConfig)
676
+ allAccounts = effectiveConfig.accounts
677
+ accounts = selectedExecutionAccounts(effectiveConfig)
678
+ if (originMode) {
679
+ const snapshot = JSON.parse(opts.env.AB_PROJECT_ACCOUNT_ENV ?? '{}') as Record<
680
+ string,
681
+ string
682
+ >
683
+ applyProjectAccountSnapshot(allAccounts, opts.env, snapshot)
684
+ }
685
+ runtimeReferences = effectiveRuntimeReferences(effectiveConfig, {
686
+ includeUnusedAccounts: false,
687
+ })
652
688
  },
653
689
  }
654
690
  }
@@ -901,6 +937,8 @@ class DispatchLoop {
901
937
  forge: wiring.forge,
902
938
  config,
903
939
  getConfig: () => this.liveConfig.current().config,
940
+ missingAccounts: () => this.missingAccounts(),
941
+ accountCredentialSource: opts.repository ? 'project-secrets' : 'environment',
904
942
  repairBuildConfig: (slug) => this.publishBuildConfig(slug),
905
943
  repo: this.repoIdentity,
906
944
  // Origin mode: the forge answers remote base-branch questions; no
@@ -926,6 +964,15 @@ class DispatchLoop {
926
964
  })
927
965
  }
928
966
 
967
+ private missingAccounts(env = this.opts.env) {
968
+ return missingAccountCredentials(
969
+ selectedExecutionAccounts(this.currentConfig().config),
970
+ env,
971
+ this.opts.repository ? 'project-secrets' : 'environment',
972
+ this.currentConfig().config.workspace.provider,
973
+ )
974
+ }
975
+
929
976
  private currentConfig(): ConfigSnapshot {
930
977
  return this.liveConfig.current()
931
978
  }
@@ -2329,7 +2376,7 @@ class DispatchLoop {
2329
2376
  private launchHarvest(): void {
2330
2377
  // Do not even start a second local contender while one is active. A second
2331
2378
  // dispatch process is independently excluded by the repository lease.
2332
- if (this.stopped || this.harvestInFlight !== undefined) return
2379
+ if (this.stopped || this.harvestInFlight !== undefined || this.missingAccounts().length) return
2333
2380
 
2334
2381
  let tracked: Promise<void>
2335
2382
  tracked = this.launchHarvestIfNeeded()
@@ -2809,6 +2856,10 @@ class DispatchLoop {
2809
2856
  // Left open: durable settlement re-proves and reaps it later.
2810
2857
  }
2811
2858
  }
2859
+ if (error instanceof MissingAccountCredentialsError) {
2860
+ await this.dispatcher.holdForMissingAccounts(error)
2861
+ return
2862
+ }
2812
2863
  this.pendingHarvest.harvestFailed += 1
2813
2864
  await this.appendStatus({
2814
2865
  actor: DISPATCHER,
@@ -3222,6 +3273,7 @@ class DispatchLoop {
3222
3273
  cleanupPending: boolean
3223
3274
  identity?: BuildExecutionHandle['identity']
3224
3275
  }): Promise<void> {
3276
+ if (await this.dispatcher.holdForMissingAccounts(input.error)) return
3225
3277
  // The failed executor may have appended through its own handle.
3226
3278
  await this.repoView.refreshBuild(input.slug)
3227
3279
  await appendInfrastructureFailure(
@@ -3249,6 +3301,7 @@ class DispatchLoop {
3249
3301
  * kernel decisions; the kernel reserves the durable execution lease before
3250
3302
  * launch and retains it until the executor has reaped its complete tree. */
3251
3303
  private async launchRunner(slug: string): Promise<LaunchRunnerResult> {
3304
+ if (this.missingAccounts().length) return 'already-active'
3252
3305
  if (!this.acceptingBuildLaunches || this.activeBuildRuns.has(slug)) return 'already-active'
3253
3306
 
3254
3307
  const reservation = Symbol(slug)
@@ -3423,6 +3476,12 @@ class DispatchLoop {
3423
3476
  this.inFlightKinds.set(tracked, handle.supervision)
3424
3477
  return 'scheduled'
3425
3478
  } catch (error) {
3479
+ if (error instanceof MissingAccountCredentialsError) {
3480
+ await this.dispatcher.holdForMissingAccounts(error)
3481
+ if (leaseClaimed) await this.repoView.releaseLease(slug, instance)
3482
+ this.activeBuildRuns.delete(slug)
3483
+ return 'already-active'
3484
+ }
3426
3485
  if (this.activeBuildRuns.get(slug)?.reservation === reservation) {
3427
3486
  this.activeBuildRuns.delete(slug)
3428
3487
  }
@@ -4645,6 +4704,10 @@ class DispatchLoop {
4645
4704
  async run(): Promise<void> {
4646
4705
  // Before the `--once` branch, so both modes report it exactly once.
4647
4706
  this.reportRoleDiagnostics()
4707
+ if (!this.opts.repository) {
4708
+ const missing = this.missingAccounts(this.wiring.inspectAccounts?.() ?? this.opts.env)
4709
+ if (missing.length) throw new MissingAccountCredentialsError(missing)
4710
+ }
4648
4711
  // Repository supervisor lease (§12): two invocations for one repository
4649
4712
  // never both act. A losing invocation records the yield and performs no
4650
4713
  // claims, launches, or publications. The holder is the invocation's
@@ -4895,6 +4958,77 @@ async function resolveOriginModeState(
4895
4958
  * path — is the served repository.
4896
4959
  */
4897
4960
  export async function abDispatch(opts: DispatchOpts): Promise<void> {
4961
+ if (opts.kernelRunId === undefined && !launchContext(opts.env)) {
4962
+ opts = { ...opts, ...(await selectDispatchMode(opts)) }
4963
+ }
4964
+ if (opts.viewer) {
4965
+ if (opts.repository !== undefined)
4966
+ throw new Error('--viewer requires a local checkout; omit --repository')
4967
+ if (opts.intake !== undefined) throw new Error('--viewer cannot set startup intake')
4968
+ if (opts.dispatchedBy !== undefined && !opts.dispatchedBy.trim())
4969
+ throw new Error('--dispatched-by requires a nonblank label')
4970
+ const state = await resolveRepoState({
4971
+ targetRepo: opts.targetRepo,
4972
+ exec: opts.exec,
4973
+ ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
4974
+ ...(opts.env.AB_STORE !== undefined ? { envStore: opts.env.AB_STORE } : {}),
4975
+ })
4976
+ const env = {
4977
+ ...opts.env,
4978
+ AB_STORE: state.storeRef,
4979
+ ...(isRemoteStoreRef(state.storeRef)
4980
+ ? { AB_TOKEN: projectToken(state.storeRef, state.repo, opts.env) }
4981
+ : {}),
4982
+ }
4983
+ const opened = openStoreForRepoState(state, { env })
4984
+ try {
4985
+ const interactive =
4986
+ opts.plain !== true && opts.terminal?.interactive === true && opts.input !== undefined
4987
+ await new DispatchFrontend({
4988
+ viewer: { ...(opts.dispatchedBy !== undefined ? { dispatchedBy: opts.dispatchedBy } : {}) },
4989
+ repo: opts.repo ?? state.repo,
4990
+ checkout: state.checkout,
4991
+ store: opened.store,
4992
+ storeRef: opened.storeRef,
4993
+ env,
4994
+ terminal: opts.terminal ?? {
4995
+ columns: 100,
4996
+ rows: 24,
4997
+ interactive: false,
4998
+ write: () => {},
4999
+ modes: createTerminalModeController(
5000
+ () => {},
5001
+ () => {},
5002
+ ),
5003
+ },
5004
+ input: opts.input ?? { start: () => () => {} },
5005
+ ...(!interactive ? { plainOutput: opts.stdout } : {}),
5006
+ ticketSource: async () =>
5007
+ (
5008
+ await openTicketSource(
5009
+ {
5010
+ targetRepo: state.checkout,
5011
+ exec: opts.exec,
5012
+ env,
5013
+ storeRef: opened.storeRef,
5014
+ stdout: opts.stdout,
5015
+ },
5016
+ 'ab merge',
5017
+ )
5018
+ ).source,
5019
+ once: opts.once === true,
5020
+ ...(opts.intervalMs !== undefined ? { intervalMs: opts.intervalMs } : {}),
5021
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
5022
+ ...(opts.resolveDashboardRenderer !== undefined
5023
+ ? { resolveDashboardRenderer: opts.resolveDashboardRenderer }
5024
+ : {}),
5025
+ }).run()
5026
+ } finally {
5027
+ await opened.store.close()
5028
+ }
5029
+ return
5030
+ }
5031
+ if (opts.dispatchedBy !== undefined) throw new Error('--dispatched-by requires --viewer')
4898
5032
  if (opts.wire !== undefined && opts.nonStoreWire !== undefined) {
4899
5033
  throw new Error('dispatch wire and nonStoreWire are mutually exclusive')
4900
5034
  }
@@ -1,3 +1,4 @@
1
+ import { readHarvestTail } from '../store/event-reads'
1
2
  import { readRepositoryFacts, type RepositoryReadFacts } from '../store/reduced-reads'
2
3
  /** Typed agent/operator surface for repository-scoped harvest workflows. Agent
3
4
  * stdout is never interpreted: proposal sets and review verdicts land through
@@ -863,7 +864,7 @@ export async function abHarvestStatus(opts: HarvestStatusOpts): Promise<void> {
863
864
  view.events =
864
865
  record === null
865
866
  ? []
866
- : (await store.getRepoEvents(repo)).filter(isHarvestEvent).slice(-opts.events)
867
+ : (await readHarvestTail(store, repo, opts.events)).filter(isHarvestEvent)
867
868
  if (opts.json === true) opts.stdout(JSON.stringify(view, null, 2))
868
869
  else for (const line of renderHarvestStatus(view)) opts.stdout(line)
869
870
  },
@@ -144,19 +144,32 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
144
144
  detail: page([
145
145
  'Usage:',
146
146
  ' ab dispatch [--once] [--interval <s>] [--store <ref>] [--plain] [--intake | --no-intake]',
147
+ ' ab dispatch --viewer [--dispatched-by <label>] [--once] [--interval <s>] [--store <ref>] [--plain]',
147
148
  '',
148
149
  'Run the outer loop for this repository: resume current builds, run the',
149
150
  'janitor and lease sweep, and dispatch ready work (§3.3, §12). This command',
150
151
  'runs outside sessions.',
151
152
  '',
152
153
  'Options:',
153
- ' --once Run one pass instead of watching continuously.',
154
+ ' Hosted placement defaults to viewer before any local dispatcher starts.',
155
+ ' --takeover Dispatch locally; warns it can displace hosted dispatch.',
156
+ ' --viewer Watch shared state without dispatching or taking a lease.',
157
+ ' Unreadable placement fails closed: use --viewer or --takeover explicitly.',
158
+ ' Unknown capability/local placement preserves local dispatch; origin/cron bypass.',
159
+ ' --viewer and --takeover cannot be combined.',
160
+ ' --dispatched-by <label> Describe where dispatching runs (requires --viewer).',
161
+ ' --once Run one pass, or read one viewer snapshot, then exit.',
154
162
  ' --interval <s> Set the positive polling interval in seconds.',
155
163
  ' --store <ref> Override the BuildStore path or URL.',
156
164
  ' --plain Force line-oriented output.',
157
165
  ' --intake Durably turn new ticket intake on.',
158
166
  ' --no-intake Durably turn new ticket intake off.',
159
167
  'With omission, intake reuses stored state (fresh repository: on).',
168
+ 'Viewer requires a local checkout; --repository and startup intake flags',
169
+ 'cannot be combined with --viewer. --interval sets its polling cadence.',
170
+ 'Every viewer frame says viewer, optionally viewer · dispatched by <label>.',
171
+ 'Plain/non-TTY output states the same at startup and prints state changes.',
172
+ 'Viewer keeps the shared-store controls below; Ctrl-C never stops dispatch elsewhere.',
160
173
  '',
161
174
  '',
162
175
  'An interactive terminal gets a fixed global/harvest/build dashboard.',
@@ -171,7 +184,7 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
171
184
  ' resume or acknowledge the run.',
172
185
  ' r On the global row, resume every paused build and turn intake',
173
186
  ' back on. On a build, resume a paused or blocked build.',
174
- ' Ctrl-C Stop dispatch.',
187
+ ' Ctrl-C Stop dispatch, or close only the viewer in --viewer mode.',
175
188
  '',
176
189
  'ab pause --all and ab resume --all are the sessionless equivalents of the',
177
190
  'global row’s p and r; they need no dispatcher and no terminal.',
@@ -368,7 +381,7 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
368
381
  '',
369
382
  'Default filter — actionable attention only. Builds: escalation.raised, phase.deferral-escalated, integration.landed,',
370
383
  'integration.verification-failed (failed node verification), build.janitor-failing, build.compatibility-deferred,',
371
- 'node.item-conflicted, conflicted restack.replayed, derived build.consent-ready and',
384
+ 'node.item-conflicted, target.rewritten, conflicted restack.replayed, derived build.consent-ready and',
372
385
  'build.merge-decision (a current actionable merge-gate deferral or unsafe forge outcome).',
373
386
  'Consent and held ready merges use only build.consent-ready, once per readiness episode.',
374
387
  'Unready or stale consent candidates stay silent; one merge gate decision per build/PR.',
@@ -10,6 +10,9 @@ export async function historicalBuildState(
10
10
  current: { cursor: number; value: BuildStreamSeed },
11
11
  ) {
12
12
  if (requested >= current.cursor) return current.value
13
+ if (store.getStreamSeed)
14
+ return (await store.getStreamSeed({ kind: 'build', slug }, requested))
15
+ .value as unknown as BuildStreamSeed
13
16
  const events = await store.getEvents(slug)
14
17
  return buildStreamSeedReducer.reduce(events.filter((event) => event.seq <= requested))
15
18
  }
@@ -22,6 +25,9 @@ export async function historicalRepositoryAttention(
22
25
  current: { cursor: number; value: ReturnType<typeof repositoryAttentionReducer.finish> },
23
26
  ) {
24
27
  if (requested >= current.cursor) return current.value
28
+ if (store.getStreamSeed)
29
+ return (await store.getStreamSeed({ kind: 'repo', repo }, requested))
30
+ .value as unknown as ReturnType<typeof repositoryAttentionReducer.finish>
25
31
  const events = await store.getRepoEvents(repo)
26
32
  return repositoryAttentionReducer.reduce(events.filter((event) => event.seq <= requested))
27
33
  }
@@ -752,8 +752,18 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
752
752
  // a build, so it routes before any store/env requirement and does its own
753
753
  // heavy wiring (like ticket create). One dispatcher per repo (§12).
754
754
  case 'dispatch': {
755
- const { once, plain, intake, defaultAutoMerge, intervalMs, storeRef, repository } =
756
- parseDispatchArgs(rest, deps.processEnv ?? {})
755
+ const {
756
+ viewer,
757
+ takeover,
758
+ dispatchedBy,
759
+ once,
760
+ plain,
761
+ intake,
762
+ defaultAutoMerge,
763
+ intervalMs,
764
+ storeRef,
765
+ repository,
766
+ } = parseDispatchArgs(rest, deps.processEnv ?? {})
757
767
  if (deps.exec === undefined) {
758
768
  throw new Error("'ab dispatch' needs an exec seam — this is a wiring bug in the ab binary")
759
769
  }
@@ -763,6 +773,9 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
763
773
  exec: deps.exec,
764
774
  stdout,
765
775
  stderr,
776
+ viewer,
777
+ takeover,
778
+ ...(dispatchedBy !== undefined ? { dispatchedBy } : {}),
766
779
  once,
767
780
  plain,
768
781
  ...(intake !== undefined ? { intake } : {}),