@defrex/autobuild 1.2.0 → 1.4.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 (164) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +416 -36
  3. package/docs/accounts.md +50 -1
  4. package/docs/answering-blocked-builds.md +4 -1
  5. package/docs/architecture.md +298 -17
  6. package/docs/build-store.md +18 -0
  7. package/docs/builds.md +7 -1
  8. package/docs/cli.md +1 -1
  9. package/docs/configuration-overview.md +6 -0
  10. package/docs/configuration.md +44 -19
  11. package/docs/dispatcher-hosting.md +42 -0
  12. package/docs/dispatcher.md +41 -0
  13. package/docs/forges.md +5 -0
  14. package/docs/integration-tree.md +24 -5
  15. package/docs/operating.md +11 -3
  16. package/docs/operator-api.md +81 -10
  17. package/docs/operator-surfaces.md +29 -0
  18. package/docs/plugin-authoring.md +51 -2
  19. package/docs/remote-store-protocol.md +321 -46
  20. package/docs/remote-ticket-protocol.md +12 -10
  21. package/docs/restacking.md +105 -3
  22. package/docs/setup.md +37 -8
  23. package/docs/skills.md +1 -1
  24. package/docs/spec-standard.md +41 -5
  25. package/docs/ticket-dependencies.md +8 -0
  26. package/docs/troubleshooting.md +9 -0
  27. package/docs/workspaces.md +1 -1
  28. package/package.json +4 -3
  29. package/packages/core/src/accounts/availability.ts +96 -0
  30. package/packages/core/src/accounts/local-owner.ts +49 -2
  31. package/packages/core/src/cli/attention.ts +2 -0
  32. package/packages/core/src/cli/binary.ts +17 -1
  33. package/packages/core/src/cli/context.ts +62 -0
  34. package/packages/core/src/cli/dashboard/model.ts +12 -3
  35. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  36. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  37. package/packages/core/src/cli/dashboard/render.ts +46 -5
  38. package/packages/core/src/cli/dispatch-args.ts +27 -3
  39. package/packages/core/src/cli/dispatch-frontend.ts +179 -52
  40. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  41. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +150 -33
  43. package/packages/core/src/cli/dispatch.ts +209 -36
  44. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  45. package/packages/core/src/cli/forge-clear.ts +30 -0
  46. package/packages/core/src/cli/harvest.ts +2 -1
  47. package/packages/core/src/cli/help.ts +17 -3
  48. package/packages/core/src/cli/historical-build-state.ts +6 -0
  49. package/packages/core/src/cli/main.ts +43 -2
  50. package/packages/core/src/cli/publication-settlement.ts +17 -0
  51. package/packages/core/src/cli/remote-poll.ts +11 -1
  52. package/packages/core/src/cli/repository-status.ts +11 -0
  53. package/packages/core/src/cli/status.ts +7 -1
  54. package/packages/core/src/cli/wait.ts +9 -2
  55. package/packages/core/src/cli/watch.ts +47 -16
  56. package/packages/core/src/config/roles.ts +16 -1
  57. package/packages/core/src/events/catalog.ts +8 -0
  58. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  59. package/packages/core/src/events/payloads.ts +95 -2
  60. package/packages/core/src/events/policy.ts +19 -0
  61. package/packages/core/src/events/repository.ts +108 -2
  62. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +464 -0
  63. package/packages/core/src/kernel/change-presence.ts +74 -8
  64. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  65. package/packages/core/src/kernel/engine.ts +27 -12
  66. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  67. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  68. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  69. package/packages/core/src/kernel/log-index.ts +1 -1
  70. package/packages/core/src/kernel/node-landing.ts +27 -10
  71. package/packages/core/src/kernel/node-polling.ts +40 -7
  72. package/packages/core/src/kernel/node-restack-demand.ts +75 -0
  73. package/packages/core/src/kernel/node-restack-state.ts +20 -1
  74. package/packages/core/src/kernel/node-restack-transaction.ts +47 -1
  75. package/packages/core/src/kernel/read-facts.ts +120 -9
  76. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  77. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  78. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  79. package/packages/core/src/kernel/reducer.ts +20 -2
  80. package/packages/core/src/kernel/replay-retention.ts +176 -0
  81. package/packages/core/src/kernel/target-lineage.ts +65 -0
  82. package/packages/core/src/kernel/target-observation.ts +117 -0
  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 +2 -0
  87. package/packages/core/src/operator/registry.ts +25 -13
  88. package/packages/core/src/operator/tickets.ts +8 -2
  89. package/packages/core/src/plugin-sdk/index.ts +1 -0
  90. package/packages/core/src/ports/forge/fake.ts +22 -0
  91. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  92. package/packages/core/src/ports/forge/github.ts +42 -10
  93. package/packages/core/src/ports/forge/local-git.ts +16 -1
  94. package/packages/core/src/ports/runner/account-env.ts +60 -9
  95. package/packages/core/src/ports/runner/claude.ts +49 -45
  96. package/packages/core/src/ports/types.ts +58 -4
  97. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  98. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  99. package/packages/core/src/ports/workspace/create.ts +2 -0
  100. package/packages/core/src/ports/workspace/fake.ts +4 -0
  101. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  102. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  103. package/packages/core/src/processes/build-runner.ts +240 -111
  104. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  105. package/packages/core/src/processes/dispatcher.ts +732 -201
  106. package/packages/core/src/processes/execution-no-progress.ts +8 -0
  107. package/packages/core/src/processes/harvest-runner.ts +6 -7
  108. package/packages/core/src/processes/harvest.ts +11 -16
  109. package/packages/core/src/processes/publication-state.ts +2 -1
  110. package/packages/core/src/processes/repo-view.ts +25 -0
  111. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  112. package/packages/core/src/scenarios/harness.ts +7 -0
  113. package/packages/core/src/store/adapter.ts +9 -0
  114. package/packages/core/src/store/artifact-meta.ts +7 -0
  115. package/packages/core/src/store/build-scope.ts +28 -0
  116. package/packages/core/src/store/contract.ts +182 -0
  117. package/packages/core/src/store/event-reads.ts +156 -0
  118. package/packages/core/src/store/local/schema.ts +11 -0
  119. package/packages/core/src/store/local/store.ts +117 -2
  120. package/packages/core/src/store/memory.ts +241 -0
  121. package/packages/core/src/store/phase-session.ts +47 -0
  122. package/packages/core/src/store/reduced-reads.ts +8 -0
  123. package/packages/core/src/store/reducer-value-shapes.json +10546 -8877
  124. package/packages/core/src/store/reducer-value-validation.ts +109 -6
  125. package/packages/core/src/store/reducer-values.ts +62 -2
  126. package/packages/core/src/store/remote/client.ts +208 -23
  127. package/packages/core/src/store/remote/compatibility.ts +195 -25
  128. package/packages/core/src/store/remote/errors.ts +16 -0
  129. package/packages/core/src/store/remote/index.ts +17 -0
  130. package/packages/core/src/store/remote/protocol.ts +30 -1
  131. package/packages/core/src/store/remote/released-clients.json +37 -0
  132. package/packages/core/src/store/remote/released-clients.ts +88 -0
  133. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  135. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  136. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  137. package/packages/core/src/store/remote/version.ts +8 -1
  138. package/packages/core/src/store/repo-state-events.ts +6 -3
  139. package/packages/core/src/store/scan-cadence.ts +15 -0
  140. package/packages/core/src/store/session-handle.ts +18 -0
  141. package/packages/core/src/store/snapshots.ts +16 -3
  142. package/packages/core/src/store/types.ts +29 -6
  143. package/packages/core/src/testing/dispatch-read-budget.ts +457 -7
  144. package/packages/core/src/testing/index.ts +6 -1
  145. package/packages/core/src/testing/reduced-read-budget.ts +1240 -9
  146. package/skills/guide/SKILL.md +220 -22
  147. package/skills/guide/references/accounts.md +50 -1
  148. package/skills/guide/references/integration-tree.md +24 -5
  149. package/skills/guide/references/operator-api.md +81 -10
  150. package/skills/guide/references/plugin-authoring.md +51 -2
  151. package/skills/guide/references/remote-store-protocol.md +321 -46
  152. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  153. package/skills/guide/references/restacking.md +105 -3
  154. package/skills/guide/references/setup.md +37 -8
  155. package/skills/guide/references/spec-standard.md +41 -5
  156. package/skills/guide/references/ticket-dependencies.md +8 -0
  157. package/skills/implement/SKILL.md +12 -3
  158. package/skills/operate/SKILL.md +85 -12
  159. package/skills/plan/SKILL.md +27 -4
  160. package/skills/plan-review/SKILL.md +22 -2
  161. package/skills/reconcile/SKILL.md +16 -1
  162. package/skills/spec/SKILL.md +7 -4
  163. package/skills/tickets/SKILL.md +7 -3
  164. package/templates/hosted-service/package.json +2 -2
@@ -2,7 +2,11 @@ import { normalizeEffectiveConfigArtifact } from '../config/effective-artifact'
2
2
  import { migrationIdentity, ticketMigrationsReducer } from '../kernel/ticket-migrations'
3
3
  import type { DispatchUpgradeState } from '../kernel/dispatch-upgrade'
4
4
  import { releaseDispatchPresentation } from './dispatch-presentation-ownership'
5
- import { readDispatchUpgrade } from '../store/reduced-reads'
5
+ import {
6
+ readDispatchUpgrade,
7
+ readRepositoryFacts,
8
+ type RepositoryReadFacts,
9
+ } from '../store/reduced-reads'
6
10
  import { DISPATCHER } from '../events/envelope'
7
11
  import { launchContext } from './dispatch-launch-contract'
8
12
  import { dispatchCapacity } from '../kernel/dispatch-capacity'
@@ -49,6 +53,8 @@ import {
49
53
  moveDetailScroll,
50
54
  moveTranscriptScroll,
51
55
  renderDashboard,
56
+ viewerIndicator,
57
+ renderViewerNotice,
52
58
  revealDetailFocus,
53
59
  type DashboardRendererResolver,
54
60
  } from './dashboard/render'
@@ -95,6 +101,8 @@ interface ResumePrompt {
95
101
  }
96
102
 
97
103
  export interface DispatchFrontendOptions {
104
+ viewer?: { dispatchedBy?: string }
105
+ plainOutput?: (line: string) => void
98
106
  /** Repository identity (§12): the normalized origin, or the checkout path
99
107
  * when there is no origin. Every Store key uses this. */
100
108
  repo: string
@@ -161,14 +169,23 @@ export class DispatchFrontend {
161
169
  private actionTail: Promise<void> = Promise.resolve()
162
170
  private presentationRestored = false
163
171
  private operatorStopRequested = false
172
+ private viewerStopped: (() => void) | undefined
173
+ private viewerFacts: RepositoryReadFacts | undefined
174
+ private viewerPosition: string | undefined
175
+ private viewerReadAt = -Infinity
176
+ private lastPlainFrame: string | undefined
164
177
 
165
178
  constructor(private readonly opts: DispatchFrontendOptions) {
166
179
  this.runId = launchContext(opts.env)?.run ?? crypto.randomUUID()
167
180
  this.dispatchStatus = reduceDispatchStatus([], this.runId)
168
- this.reader = presentationReader(opts.store, () => this.refresh?.admitted ?? true)
181
+ this.reader = presentationReader(
182
+ opts.store,
183
+ () => !this.presentationRestored && (this.refresh?.admitted ?? true),
184
+ )
169
185
  this.clock = opts.clock ?? systemClock
170
186
  this.repositoryFeed = new DispatchRepositoryFeed(this.reader, opts.repo, this.clock)
171
187
  this.standbyResolver = new StandbyIdentityResolver(this.reader, opts.repo, {
188
+ selectHolder: (holder) => this.repositoryFeed.selectHolder(holder),
172
189
  allowLookup: () => this.repositoryFeed.incompleteIdentities,
173
190
  remember: (events, complete) => this.repositoryFeed.remember(events, complete),
174
191
  })
@@ -183,7 +200,20 @@ export class DispatchFrontend {
183
200
  * operator action. High-frequency dispatcher status is folded from deltas;
184
201
  * only the low-volume settings/Harvest facts needed by the dashboard model
185
202
  * are retained for their existing replay reducers. */
186
- private async events(): Promise<RepositoryEvent[]> {
203
+ private async events(sampledPosition?: string): Promise<RepositoryEvent[]> {
204
+ if (this.opts.viewer) {
205
+ const position = sampledPosition ?? (await this.reader.getRepoChangePosition(this.opts.repo))
206
+ if (
207
+ position !== this.viewerPosition ||
208
+ this.clock().getTime() - this.viewerReadAt >= 10_000
209
+ ) {
210
+ this.viewerFacts = (await readRepositoryFacts(this.reader, this.opts.repo)).value
211
+ this.viewerPosition = position
212
+ this.viewerReadAt = this.clock().getTime()
213
+ }
214
+ this.dispatchStatus = this.viewerFacts!.status ?? reduceDispatchStatus([], this.runId)
215
+ return []
216
+ }
187
217
  const refresh = this.eventRefreshTail.then(async () => {
188
218
  const delta = await this.repositoryFeed.refresh(false)
189
219
  this.standbyResolver.ingest(this.repositoryFeed.identities)
@@ -268,7 +298,7 @@ export class DispatchFrontend {
268
298
  detailScrollLimit(
269
299
  next,
270
300
  dashboardContentWidth(this.opts.terminal.columns),
271
- paintableRows(this.opts.terminal.rows),
301
+ this.contentHeight(),
272
302
  ),
273
303
  ),
274
304
  ),
@@ -283,14 +313,26 @@ export class DispatchFrontend {
283
313
  if (this.refresh !== undefined && !this.refresh.painting) return
284
314
  if (this.model === undefined) return
285
315
  const renderer = this.opts.resolveDashboardRenderer?.() ?? renderDashboard
286
- this.region.update(
287
- renderer(this.model, {
288
- color: true,
289
- width: this.opts.terminal.columns,
290
- height: paintableRows(this.opts.terminal.rows),
291
- now: this.clock().getTime(),
292
- }),
293
- )
316
+ const lines = renderer(this.model, {
317
+ color: this.opts.plainOutput === undefined,
318
+ width: this.opts.terminal.columns,
319
+ height: paintableRows(this.opts.terminal.rows),
320
+ now: this.clock().getTime(),
321
+ })
322
+ this.outputFrame(lines)
323
+ }
324
+
325
+ private outputFrame(lines: string[]): void {
326
+ if (this.presentationRestored) return
327
+ if (this.opts.plainOutput) {
328
+ const frame = lines.join('\n')
329
+ if (frame !== this.lastPlainFrame) this.opts.plainOutput(frame)
330
+ this.lastPlainFrame = frame
331
+ } else this.region.update(lines)
332
+ }
333
+
334
+ private contentHeight(): number {
335
+ return Math.max(0, paintableRows(this.opts.terminal.rows) - (this.opts.viewer ? 1 : 0))
294
336
  }
295
337
 
296
338
  private async loadConfig(kind: string, rev: number): Promise<Config> {
@@ -315,6 +357,7 @@ export class DispatchFrontend {
315
357
  private readonly repositoryPoll = new RepositoryPollCache<{
316
358
  repositoryEvents: RepositoryEvent[]
317
359
  upgrades: DispatchUpgradeState
360
+ repositoryFacts: RepositoryReadFacts
318
361
  status: DispatchStatus
319
362
  config: Config
320
363
  observationCount: number
@@ -323,8 +366,12 @@ export class DispatchFrontend {
323
366
 
324
367
  private async readFrame(): Promise<void> {
325
368
  if (this.refresh !== undefined && !this.refresh.admitted) return
369
+ let sampledPosition: string | undefined
326
370
  const frame = await this.repositoryPoll.refresh({
327
- position: () => this.reader.getRepoChangePosition(this.opts.repo),
371
+ position: async () => {
372
+ sampledPosition = await this.reader.getRepoChangePosition(this.opts.repo)
373
+ return sampledPosition
374
+ },
328
375
  now: () => this.clock().getTime(),
329
376
  revision: 0,
330
377
  enabled: !this.opts.once,
@@ -332,14 +379,33 @@ export class DispatchFrontend {
332
379
  admitted: () => this.refresh === undefined || this.refresh.admitted,
333
380
  nextPollMs: this.refresh?.intervalMs ?? 0,
334
381
  read: async ({ fullEnrichment }) => {
335
- const repositoryEvents = await this.events()
382
+ const repositoryEvents = await this.events(sampledPosition)
336
383
  // Authority and rollback holds need the full durable reduction, not the
337
384
  // low-volume replay feed (which deliberately discards per-tick facts).
338
- const upgrades = (await readDispatchUpgrade(this.reader, this.opts.repo)).value
385
+ const repositoryFacts =
386
+ this.viewerFacts ??
387
+ (
388
+ await readRepositoryFacts(
389
+ this.reader,
390
+ this.opts.repo,
391
+ repositoryEvents.length || this.repositoryFeed.identities.length ? true : undefined,
392
+ )
393
+ ).value
394
+ const upgrades = repositoryFacts.upgrades
339
395
  const status = this.dispatchStatus
340
396
  const ref = status.effectiveConfig
341
397
  if (ref === undefined) {
342
- if (status.health === 'failed' && status.warningNotice !== undefined)
398
+ if (this.opts.viewer) {
399
+ this.model = undefined
400
+ this.outputFrame(
401
+ renderViewerNotice(
402
+ this.opts.viewer,
403
+ status.warningNotice ?? 'Waiting for dispatcher configuration',
404
+ this.opts.terminal.columns,
405
+ paintableRows(this.opts.terminal.rows),
406
+ ),
407
+ )
408
+ } else if (status.health === 'failed' && status.warningNotice !== undefined)
343
409
  this.region.update([status.warningNotice])
344
410
  // Startup is incomplete: retry at the same position.
345
411
  return undefined
@@ -349,7 +415,7 @@ export class DispatchFrontend {
349
415
  try {
350
416
  observationCount = unclaimedObservationCount({
351
417
  digests: await this.reader.getRepoBuildDigests(this.opts.repo),
352
- harvestEvents: repositoryEvents,
418
+ harvestEvents: this.opts.viewer ? repositoryFacts.harvest : repositoryEvents,
353
419
  })
354
420
  } catch {
355
421
  // Incomplete snapshots never acknowledge the sampled position.
@@ -359,19 +425,28 @@ export class DispatchFrontend {
359
425
  }
360
426
  this.cache ??= new DashboardBuildPollCache(this.reader, this.opts.repo, config)
361
427
  const snapshot = await this.cache.refresh(config, this.configRevision, fullEnrichment)
362
- if (!this.opts.once)
428
+ if (!this.opts.once && !this.opts.viewer)
363
429
  await this.standbyResolver.refresh(this.runId, status.yieldedHolder, this.clock())
364
- await this.repositoryFeed.save()
430
+ if (!this.opts.viewer) await this.repositoryFeed.save()
365
431
  if (!this.cache.isCurrent(snapshot)) return undefined
366
- return { repositoryEvents, upgrades, status, config, observationCount, snapshot }
432
+ return {
433
+ repositoryEvents,
434
+ repositoryFacts,
435
+ upgrades,
436
+ status,
437
+ config,
438
+ observationCount,
439
+ snapshot,
440
+ }
367
441
  },
368
442
  })
369
443
  if (frame === undefined) return
370
- let { repositoryEvents, upgrades, status } = frame
444
+ let { repositoryEvents, repositoryFacts, upgrades, status } = frame
371
445
  const { config, snapshot } = frame
372
- const standby = this.opts.once
373
- ? undefined
374
- : this.standbyResolver.current(this.runId, status.yieldedHolder, this.clock())
446
+ const standby =
447
+ this.opts.once || this.opts.viewer
448
+ ? undefined
449
+ : this.standbyResolver.current(this.runId, status.yieldedHolder, this.clock())
375
450
  this.observationCount = frame.observationCount
376
451
  this.refresh?.activity(snapshot.states.size > 0)
377
452
 
@@ -387,7 +462,14 @@ export class DispatchFrontend {
387
462
  if (!validAbortConfirmation(snapshot.states.get(slug))) {
388
463
  await this.dismissStaleAbortConfirmation(slug)
389
464
  repositoryEvents = await this.events()
390
- upgrades = (await readDispatchUpgrade(this.reader, this.opts.repo)).value
465
+ repositoryFacts = (
466
+ await readRepositoryFacts(
467
+ this.reader,
468
+ this.opts.repo,
469
+ repositoryEvents.length || this.repositoryFeed.identities.length ? true : undefined,
470
+ )
471
+ ).value
472
+ upgrades = repositoryFacts.upgrades
391
473
  status = this.dispatchStatus
392
474
  }
393
475
  }
@@ -413,7 +495,9 @@ export class DispatchFrontend {
413
495
  config.capacity,
414
496
  this.clock(),
415
497
  migrationIdentity(
416
- ticketMigrationsReducer.reduce(repositoryEvents),
498
+ this.opts.viewer
499
+ ? repositoryFacts.ticketMigrations
500
+ : ticketMigrationsReducer.reduce(repositoryEvents),
417
501
  config.tickets.source,
418
502
  ),
419
503
  ),
@@ -424,7 +508,7 @@ export class DispatchFrontend {
424
508
  : {}),
425
509
  ...(warningLines.length > 0 ? { warningLines } : {}),
426
510
  },
427
- repositoryEvents,
511
+ repositoryFacts,
428
512
  upgrades,
429
513
  )
430
514
  this.selection = reconcileSelection(previous, dashboardSelections(projected), this.selection)
@@ -434,7 +518,7 @@ export class DispatchFrontend {
434
518
  ) {
435
519
  this.view = undefined
436
520
  }
437
- this.model = projected
521
+ this.model = { ...projected, ...(this.opts.viewer ? { viewer: this.opts.viewer } : {}) }
438
522
  this.syncControls()
439
523
  this.paint()
440
524
  // The session view's live-read cycle rides the poll tick: one immediate
@@ -449,7 +533,7 @@ export class DispatchFrontend {
449
533
  const limit = sessionScrollLimit(
450
534
  view,
451
535
  this.opts.terminal.columns,
452
- paintableRows(this.opts.terminal.rows),
536
+ this.contentHeight(),
453
537
  upgrade,
454
538
  this.model?.standby !== undefined,
455
539
  )
@@ -457,7 +541,7 @@ export class DispatchFrontend {
457
541
  const scroll = moveSessionScroll(
458
542
  view,
459
543
  this.opts.terminal.columns,
460
- paintableRows(this.opts.terminal.rows),
544
+ this.contentHeight(),
461
545
  current,
462
546
  delta,
463
547
  upgrade,
@@ -477,7 +561,7 @@ export class DispatchFrontend {
477
561
  scroll: moveTranscriptScroll(
478
562
  this.view.transcript,
479
563
  this.opts.terminal.columns,
480
- paintableRows(this.opts.terminal.rows),
564
+ this.contentHeight(),
481
565
  this.view.scroll,
482
566
  delta,
483
567
  this.model?.availableUpgrade !== undefined,
@@ -490,7 +574,7 @@ export class DispatchFrontend {
490
574
  scroll: moveDetailScroll(
491
575
  this.model,
492
576
  dashboardContentWidth(this.opts.terminal.columns),
493
- paintableRows(this.opts.terminal.rows),
577
+ this.contentHeight(),
494
578
  this.view.scroll,
495
579
  delta,
496
580
  ),
@@ -518,7 +602,7 @@ export class DispatchFrontend {
518
602
  scroll: revealDetailFocus(
519
603
  { ...this.model!, view: candidate },
520
604
  dashboardContentWidth(this.opts.terminal.columns),
521
- paintableRows(this.opts.terminal.rows),
605
+ this.contentHeight(),
522
606
  'session',
523
607
  candidate.scroll,
524
608
  ),
@@ -578,7 +662,7 @@ export class DispatchFrontend {
578
662
  scroll: revealDetailFocus(
579
663
  { ...this.model!, view: candidate },
580
664
  dashboardContentWidth(this.opts.terminal.columns),
581
- paintableRows(this.opts.terminal.rows),
665
+ this.contentHeight(),
582
666
  'message',
583
667
  candidate.scroll,
584
668
  ),
@@ -642,7 +726,7 @@ export class DispatchFrontend {
642
726
  const limit = sessionScrollLimit(
643
727
  next,
644
728
  terminal.columns,
645
- paintableRows(terminal.rows),
729
+ this.contentHeight(),
646
730
  this.model?.availableUpgrade !== undefined,
647
731
  this.model?.standby !== undefined,
648
732
  )
@@ -1005,29 +1089,32 @@ export class DispatchFrontend {
1005
1089
  },
1006
1090
  this.opts.refreshScheduler,
1007
1091
  this.opts.store.networkReads,
1092
+ this.opts.viewer ? this.opts.intervalMs : undefined,
1008
1093
  )
1009
- this.listen()
1010
- this.opts.terminal.modes.enter(FOCUS_REPORTING_MODE)
1011
- this.suspension = installPresentationSuspension(
1012
- this.opts.terminal.modes,
1013
- () => {
1014
- this.refresh?.suspend()
1015
- this.cleanupInput?.()
1016
- this.cleanupInput = undefined
1017
- },
1018
- () => {
1019
- this.listen()
1020
- this.region.invalidate()
1021
- this.refresh?.resume()
1022
- },
1023
- )
1024
- this.paintTimer = setInterval(() => this.paint(), PAINT_MS)
1025
- this.paintTimer.unref?.()
1094
+ if (!this.opts.plainOutput) this.listen()
1095
+ if (!this.opts.plainOutput) this.opts.terminal.modes.enter(FOCUS_REPORTING_MODE)
1096
+ if (!this.opts.plainOutput)
1097
+ this.suspension = installPresentationSuspension(
1098
+ this.opts.terminal.modes,
1099
+ () => {
1100
+ this.refresh?.suspend()
1101
+ this.cleanupInput?.()
1102
+ this.cleanupInput = undefined
1103
+ },
1104
+ () => {
1105
+ this.listen()
1106
+ this.region.invalidate()
1107
+ this.refresh?.resume()
1108
+ },
1109
+ )
1110
+ if (!this.opts.plainOutput) this.paintTimer = setInterval(() => this.paint(), PAINT_MS)
1111
+ this.paintTimer?.unref?.()
1026
1112
  void this.refresh.request()
1027
1113
  }
1028
1114
 
1029
1115
  private requestOperatorStop(): void {
1030
1116
  this.operatorStopRequested = true
1117
+ this.viewerStopped?.()
1031
1118
  this.restorePresentationForStop()
1032
1119
  void this.child?.stop(
1033
1120
  typeof this.opts.signal?.reason === 'string' ? this.opts.signal.reason : undefined,
@@ -1081,7 +1168,47 @@ export class DispatchFrontend {
1081
1168
  }
1082
1169
  }
1083
1170
 
1171
+ private async runViewer(): Promise<void> {
1172
+ // Viewing has no repository creation, lease, child, or dispatcher lifecycle writes.
1173
+ if (this.opts.plainOutput) this.opts.plainOutput(viewerIndicator(this.opts.viewer!, 1000))
1174
+ if (this.opts.signal?.aborted) return
1175
+ const stopped = new Promise<void>((resolve) => {
1176
+ this.viewerStopped = resolve
1177
+ })
1178
+ const stop = () => this.requestOperatorStop()
1179
+ // A pending Promise and the adaptive scheduler's unref timers do not keep
1180
+ // a plain viewer alive. This timer owns only the presentation lifetime.
1181
+ const lifetime = setInterval(() => {}, 60_000)
1182
+ this.opts.signal?.addEventListener('abort', stop, { once: true })
1183
+ try {
1184
+ await this.readFrame()
1185
+ if (!this.opts.once && !this.operatorStopRequested) {
1186
+ this.startPresentation()
1187
+ await stopped
1188
+ }
1189
+ } catch (error) {
1190
+ if (this.operatorStopRequested) return
1191
+ this.outputFrame(
1192
+ renderViewerNotice(
1193
+ this.opts.viewer!,
1194
+ `Viewer unavailable: ${error instanceof Error ? error.message : String(error)}`,
1195
+ this.opts.terminal.columns,
1196
+ paintableRows(this.opts.terminal.rows),
1197
+ ),
1198
+ )
1199
+ throw error
1200
+ } finally {
1201
+ clearInterval(lifetime)
1202
+ this.opts.signal?.removeEventListener('abort', stop)
1203
+ this.restorePresentationForStop()
1204
+ await this.refresh?.join()
1205
+ await this.actionTail
1206
+ this.viewerStopped = undefined
1207
+ }
1208
+ }
1209
+
1084
1210
  async run(): Promise<void> {
1211
+ if (this.opts.viewer) return this.runViewer()
1085
1212
  await this.opts.store.ensureRepo(this.opts.repo)
1086
1213
  const actor = humanActor(buildControlUser(this.opts.env))
1087
1214
  if (this.opts.intake !== undefined) {
@@ -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,