@defrex/autobuild 0.10.1 → 0.11.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 (45) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +15 -1
  3. package/bin/ab-dispatch-kernel.ts +1 -1
  4. package/docs/configuration.md +32 -3
  5. package/docs/operator-api.md +17 -0
  6. package/docs/remote-ticket-protocol.md +5 -0
  7. package/package.json +3 -3
  8. package/packages/core/src/cli/binary.ts +3 -3
  9. package/packages/core/src/cli/dashboard/model.ts +4 -0
  10. package/packages/core/src/cli/dashboard/render.ts +37 -7
  11. package/packages/core/src/cli/dispatch-frontend.ts +16 -1
  12. package/packages/core/src/cli/dispatch-process.ts +25 -7
  13. package/packages/core/src/cli/dispatch.ts +64 -6
  14. package/packages/core/src/cli/dispatcher-liveness.ts +91 -0
  15. package/packages/core/src/cli/help.ts +8 -5
  16. package/packages/core/src/cli/repository-status.ts +45 -5
  17. package/packages/core/src/cli/watch.ts +159 -14
  18. package/packages/core/src/config/live.ts +1 -0
  19. package/packages/core/src/config/schema.ts +9 -2
  20. package/packages/core/src/events/globs.ts +8 -3
  21. package/packages/core/src/events/repository.ts +51 -2
  22. package/packages/core/src/integration/harness.ts +2 -1
  23. package/packages/core/src/kernel/__snapshots__/reducer-registry.test.ts.snap +18 -0
  24. package/packages/core/src/kernel/dispatch-status.ts +9 -1
  25. package/packages/core/src/kernel/dispatcher-liveness.ts +70 -0
  26. package/packages/core/src/kernel/reducer-registry.ts +4 -0
  27. package/packages/core/src/kernel/ticket-source-health.ts +30 -0
  28. package/packages/core/src/operator/query.ts +6 -3
  29. package/packages/core/src/ports/tickets/contract.ts +25 -0
  30. package/packages/core/src/ports/tickets/fake.ts +10 -8
  31. package/packages/core/src/ports/tickets/file.ts +1 -0
  32. package/packages/core/src/ports/tickets/linear.ts +241 -49
  33. package/packages/core/src/ports/tickets/remote-protocol.ts +2 -0
  34. package/packages/core/src/ports/types.ts +17 -0
  35. package/packages/core/src/processes/dispatcher.ts +277 -73
  36. package/packages/core/src/processes/repo-view.ts +2 -1
  37. package/packages/core/src/store/adapter.ts +1 -0
  38. package/packages/core/src/store/contract.ts +109 -0
  39. package/packages/core/src/store/digest.ts +14 -2
  40. package/packages/core/src/store/local/store.ts +18 -5
  41. package/packages/core/src/store/remote/protocol.ts +1 -0
  42. package/packages/core/src/store/repo-state-events.ts +49 -59
  43. package/packages/core/src/store/types.ts +5 -1
  44. package/skills/guide/SKILL.md +31 -0
  45. package/skills/operate/SKILL.md +39 -4
@@ -1,3 +1,5 @@
1
+ import { readDispatcherLiveness, StandbyIdentityResolver } from './dispatcher-liveness'
2
+ import { formatDispatcherIdentity } from '../kernel/dispatcher-liveness'
1
3
  /**
2
4
  * `ab dispatch` — the operator's entry into the outer loop (SPEC §3.3, §12).
3
5
  * Runs OUTSIDE build sessions like init/upgrade/ticket (§16.3): it takes a
@@ -691,6 +693,9 @@ class DispatchLoop {
691
693
  * discarded on Escape. All read semantics live in the shared feed module. */
692
694
  private sessionFeed: SessionStreamFeed | undefined
693
695
  private warningLine: string | undefined
696
+ /** Invocation-local ownership; independent of every notice slot. */
697
+ private standby: string | undefined
698
+ private standbyResolver: StandbyIdentityResolver | undefined
694
699
  /** Process-local, persistent release notice. It never shares the replaceable
695
700
  * warning slot and is re-applied to every store projection. */
696
701
  private availableUpgrade: string | undefined
@@ -1190,6 +1195,7 @@ class DispatchLoop {
1190
1195
  selection: _oldSelection,
1191
1196
  warningLines: _oldWarningLines,
1192
1197
  availableUpgrade: _oldAvailableUpgrade,
1198
+ standby: _oldStandby,
1193
1199
  resumeInput: _oldResumeInput,
1194
1200
  abortConfirmation: _oldAbortConfirmation,
1195
1201
  view: _oldView,
@@ -1204,6 +1210,7 @@ class DispatchLoop {
1204
1210
  ]
1205
1211
  let effective: DashboardModel = {
1206
1212
  ...base,
1213
+ ...(this.standby !== undefined ? { standby: this.standby } : {}),
1207
1214
  ...(this.availableUpgrade !== undefined ? { availableUpgrade: this.availableUpgrade } : {}),
1208
1215
  ...(warningLines.length > 0 ? { warningLines } : {}),
1209
1216
  ...(this.selection !== undefined ? { selection: this.selection } : {}),
@@ -1258,7 +1265,13 @@ class DispatchLoop {
1258
1265
  const limit =
1259
1266
  terminal === undefined
1260
1267
  ? 0
1261
- : sessionScrollLimit(view, terminal.columns, paintableRows(terminal.rows), upgrade)
1268
+ : sessionScrollLimit(
1269
+ view,
1270
+ terminal.columns,
1271
+ paintableRows(terminal.rows),
1272
+ upgrade,
1273
+ this.standby !== undefined,
1274
+ )
1262
1275
  const current = view.follow ? limit : view.scroll
1263
1276
  const scroll =
1264
1277
  terminal === undefined
@@ -1270,6 +1283,7 @@ class DispatchLoop {
1270
1283
  current,
1271
1284
  delta,
1272
1285
  upgrade,
1286
+ this.standby !== undefined,
1273
1287
  )
1274
1288
  let follow = view.follow
1275
1289
  if (delta < 0 && follow && scroll < limit) follow = false
@@ -1291,6 +1305,7 @@ class DispatchLoop {
1291
1305
  terminal.columns,
1292
1306
  paintableRows(terminal.rows),
1293
1307
  this.availableUpgrade !== undefined,
1308
+ this.standby !== undefined,
1294
1309
  )
1295
1310
  return { ...view, scroll: view.follow ? limit : Math.min(view.scroll, limit) }
1296
1311
  }
@@ -1350,6 +1365,7 @@ class DispatchLoop {
1350
1365
  this.view.scroll,
1351
1366
  delta,
1352
1367
  this.availableUpgrade !== undefined,
1368
+ this.standby !== undefined,
1353
1369
  ),
1354
1370
  }
1355
1371
  this.syncModelControls()
@@ -3389,6 +3405,18 @@ class DispatchLoop {
3389
3405
  const claimed = await this.wiring.store
3390
3406
  .claimRepoLease(this.repoIdentity, holder, REPO_LEASE_TTL_MS)
3391
3407
  .catch(() => false)
3408
+ if (this.dashboard && !this.opts.once) {
3409
+ this.standbyResolver ??= new StandbyIdentityResolver(this.wiring.store, this.repoIdentity)
3410
+ this.standby = claimed
3411
+ ? undefined
3412
+ : await this.standbyResolver.refresh(
3413
+ this.runId,
3414
+ this.yieldedTo ?? 'another invocation',
3415
+ this.wiring.clock(),
3416
+ )
3417
+ this.syncModelControls()
3418
+ this.paint()
3419
+ }
3392
3420
  if (!claimed) {
3393
3421
  if (this.repoLeaseHolder !== undefined) {
3394
3422
  // We held the lease and the store says it is gone: a peer took over.
@@ -3474,10 +3502,17 @@ class DispatchLoop {
3474
3502
  const holder = this.runId
3475
3503
  if (!(await this.ensureRepoLease(holder))) {
3476
3504
  await this.recordTickYielded()
3477
- const peer = (await this.wiring.store.getRepo(this.repoIdentity).catch(() => null))?.lease
3478
- ?.holder
3479
- const message = `tick yielded: repository held by ${peer ?? 'another invocation'}`
3480
- this.warn(message)
3505
+ if ((!this.dashboard && this.opts.kernelRunId === undefined) || this.opts.once) {
3506
+ const peer = (await this.wiring.store.getRepo(this.repoIdentity).catch(() => null))?.lease
3507
+ ?.holder
3508
+ const liveness = await readDispatcherLiveness(
3509
+ this.wiring.store,
3510
+ this.repoIdentity,
3511
+ this.wiring.clock(),
3512
+ ).catch(() => null)
3513
+ const message = `tick yielded: repository held by ${liveness?.dispatcher.holder ? formatDispatcherIdentity(liveness.dispatcher.holder) : (peer ?? 'another invocation')}`
3514
+ this.warn(message)
3515
+ }
3481
3516
  if (this.opts.once === true) return
3482
3517
  // Watch mode stays alive and retries the claim at every tick.
3483
3518
  }
@@ -3498,7 +3533,17 @@ class DispatchLoop {
3498
3533
  // lease and any provisioning state are released for the next
3499
3534
  // invocation.
3500
3535
  if (this.pastDeadline()) return
3501
- const initial = await this.dispatcherTick(true)
3536
+ const initial = await this.dispatcherTick(true).catch(async (error: unknown) => {
3537
+ await this.appendStatus({
3538
+ actor: DISPATCHER,
3539
+ type: 'dispatcher.tick-failed',
3540
+ payload: {
3541
+ run: this.runId,
3542
+ error: error instanceof Error ? error.message : String(error),
3543
+ },
3544
+ })
3545
+ throw error
3546
+ })
3502
3547
  const initialPrinted = this.printReport(initial, false)
3503
3548
  await this.drainInFlight()
3504
3549
  const settledReports = await this.publishSettlementReports()
@@ -3963,6 +4008,7 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
3963
4008
  payload: {
3964
4009
  run: runId,
3965
4010
  pid: process.pid,
4011
+ host: hostname(),
3966
4012
  effectiveConfig: { kind: artifact.kind, rev: artifact.revision },
3967
4013
  roleWarnings: roleKeyWarnings(config),
3968
4014
  },
@@ -3973,6 +4019,17 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
3973
4019
  const loop = new DispatchLoop(liveConfig, wiring, resolvedOpts, view)
3974
4020
  try {
3975
4021
  await loop.run()
4022
+ const stopRequest = (
4023
+ resolvedOpts.kernelRunId && resolvedOpts.signal?.aborted
4024
+ ? await wiring.store.getRepoEvents(state.repo)
4025
+ : []
4026
+ ).find((event) => event.type === 'dispatcher.stop-requested' && event.payload.run === runId)
4027
+ const stoppedSignal =
4028
+ stopRequest?.type === 'dispatcher.stop-requested'
4029
+ ? stopRequest.payload.signal
4030
+ : typeof resolvedOpts.signal?.reason === 'string'
4031
+ ? resolvedOpts.signal.reason
4032
+ : undefined
3976
4033
  await view.appendRepo(state.repo, {
3977
4034
  actor: DISPATCHER,
3978
4035
  type: 'dispatcher.run-stopped',
@@ -3980,6 +4037,7 @@ export async function abDispatch(opts: DispatchOpts): Promise<void> {
3980
4037
  run: runId,
3981
4038
  outcome: 'normal',
3982
4039
  exitCode: 0,
4040
+ ...(stoppedSignal === undefined ? {} : { signal: stoppedSignal }),
3983
4041
  ...(loop.supersededByPeer ? { reason: 'superseded' as const } : {}),
3984
4042
  },
3985
4043
  })
@@ -0,0 +1,91 @@
1
+ import type { RepositoryEvent } from '../events/repository'
2
+ import type { BuildStore, RepositoryRecord } from '../store/types'
3
+ import { formatDispatcherIdentity, projectDispatcherLiveness } from '../kernel/dispatcher-liveness'
4
+
5
+ /** Bounded first; a later yielding invocation can hide the owner's identity or
6
+ * an earlier stop. Only this correlation query falls back to full history. */
7
+ export async function readDispatcherLiveness(
8
+ store: BuildStore,
9
+ repo: string,
10
+ now = new Date(),
11
+ subset?: RepositoryEvent[],
12
+ ) {
13
+ const record = await store.getRepo(repo)
14
+ let events = record === null ? [] : (subset ?? (await store.getRepoStateEvents(repo)))
15
+ const bounded = projectDispatcherLiveness(record, events, now)
16
+ if (
17
+ record &&
18
+ ((record.lease &&
19
+ !events.some(
20
+ (e) => e.type === 'dispatcher.run-started' && e.payload.run === record.lease!.holder,
21
+ )) ||
22
+ (bounded.state !== 'held' &&
23
+ events.some((e) => e.type === 'dispatcher.run-started') &&
24
+ !events.some((e) => e.type === 'dispatcher.run-stopped')))
25
+ ) {
26
+ events = await store.getRepoEvents(repo)
27
+ }
28
+ return { record, events, dispatcher: projectDispatcherLiveness(record, events, now) }
29
+ }
30
+
31
+ /** Invocation-local identity cache. Only start facts survive refreshes; ages
32
+ * always come from the current lease record and clock. Failed correlations are
33
+ * negatively cached so a standby cannot repeatedly replay a large journal. */
34
+ export class StandbyIdentityResolver {
35
+ private readonly starts = new Map<string, RepositoryEvent>()
36
+ private readonly attempted = new Set<string>()
37
+ private readonly pending = new Map<string, Promise<void>>()
38
+
39
+ constructor(
40
+ private readonly store: BuildStore,
41
+ private readonly repo: string,
42
+ ) {}
43
+
44
+ ingest(events: readonly RepositoryEvent[]): void {
45
+ for (const event of events) {
46
+ if (event.type === 'dispatcher.run-started') this.starts.set(event.payload.run, event)
47
+ }
48
+ }
49
+
50
+ private async correlate(holder: string): Promise<void> {
51
+ const pending = this.pending.get(holder)
52
+ if (pending !== undefined) return pending
53
+ if (this.starts.has(holder) || this.attempted.has(holder)) return
54
+ this.attempted.add(holder)
55
+ const lookup = (async () => {
56
+ try {
57
+ this.ingest(await this.store.getRepoStateEvents(this.repo))
58
+ if (!this.starts.has(holder)) this.ingest(await this.store.getRepoEvents(this.repo, 0))
59
+ } catch {
60
+ // Identity is best effort; the sampled holder id remains sufficient.
61
+ }
62
+ })()
63
+ this.pending.set(holder, lookup)
64
+ try {
65
+ await lookup
66
+ } finally {
67
+ this.pending.delete(holder)
68
+ }
69
+ }
70
+
71
+ async refresh(
72
+ run: string,
73
+ yieldedHolder: string | undefined,
74
+ now: Date,
75
+ ): Promise<string | undefined> {
76
+ let record: RepositoryRecord | null
77
+ try {
78
+ record = await this.store.getRepo(this.repo)
79
+ } catch {
80
+ return yieldedHolder
81
+ }
82
+ const holder = record?.lease?.holder
83
+ if (holder === run) return undefined
84
+ if (holder === undefined) return yieldedHolder
85
+ await this.correlate(holder)
86
+ if (!this.starts.has(holder)) return holder
87
+ const projection = projectDispatcherLiveness(record, [...this.starts.values()], now)
88
+ const identity = projection.holder ?? projection.expiredHolder
89
+ return identity?.run === holder ? formatDispatcherIdentity(identity) : holder
90
+ }
91
+ }
@@ -282,7 +282,7 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
282
282
  ' ab watch [<slug>...] [--repository] [--event <glob>]... [--since <cursor>] [--timeout <duration>] [--interval <duration>] [--count <n>] [--json] [--store <ref>]',
283
283
  '',
284
284
  'Follow the event logs of one, several, or all active builds in this repository —',
285
- 'optionally the repository journal — and emit one record per matching event as it',
285
+ 'the repository journal by default with no slugs — and emit one record per matching event as it',
286
286
  'lands. With no slug, every nonterminal build (queued, running, paused, blocked) is',
287
287
  'watched, and a build created while the watch runs joins it without a restart.',
288
288
  'Naming one or more slugs watches exactly those builds; an unknown slug is an error',
@@ -291,16 +291,18 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
291
291
  '',
292
292
  'Options:',
293
293
  ' --repository Also follow the repository journal (dispatcher and harvest',
294
- ' events). Without it, repository events are never emitted.',
294
+ ' events) for named watches. No-slug watches include it by default.',
295
295
  ' --event <glob> Repeatable glob over event type names: * matches any run of',
296
296
  ' characters, ? one character (escalation.*, pr.merged, *). Every',
297
297
  ' glob must match at least one type in the build catalog — or,',
298
- ' with --repository, the repository catalog — or the command fails',
298
+ ' with no slugs or --repository, the repository catalog — or the command fails',
299
299
  ' before any store read. Any --event replaces the default filter.',
300
300
  ' --since <cursor> Resume from a cursor emitted by an earlier record; every matching',
301
301
  ' event after that cursor is delivered exactly once, including',
302
302
  ' events that landed while no watch was running. A cursor from a',
303
- ' different repository or store is rejected.',
303
+ ' different repository or store is rejected. A legacy cursor without',
304
+ ' a repository position baselines that stream now; reconcile earlier',
305
+ ' source conditions with ab repository status.',
304
306
  ' --timeout <dur> End the watch after this duration (30, 45s, 5m, 1h). Default',
305
307
  ' 30 minutes; 0 means unbounded.',
306
308
  ' --interval <dur> Poll cadence. Default: 5s for an http(s) store, 1s for a local store.',
@@ -313,7 +315,8 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
313
315
  'infrastructure.failed, runner.setup-failed, dispatch.failed, publication.lost,',
314
316
  'finalize.completed, pr.conflicted, pr.merged, pr.closed, build.completed,',
315
317
  'build.aborted. For the repository journal: harvest.escalated, harvest.failed,',
316
- 'dispatcher.tick-failed, dispatcher.config-rejected, dispatcher.harvest-runner-failed.',
318
+ 'dispatcher.tick-failed, dispatcher.config-rejected, dispatcher.harvest-runner-failed,',
319
+ 'dispatcher.ticket-source-degraded, dispatcher.ticket-source-recovered.',
317
320
  '',
318
321
  'Record shape (--json): build (slug, or null for a repository event), repo (repository',
319
322
  'id, present only for repository events), event (the complete durable envelope: build,',
@@ -1,3 +1,13 @@
1
+ import {
2
+ formatDispatcherIdentity,
3
+ projectDispatcherLiveness,
4
+ type DispatcherLiveness,
5
+ } from '../kernel/dispatcher-liveness'
6
+ import { readDispatcherLiveness } from './dispatcher-liveness'
7
+ import {
8
+ reduceTicketSourceHealth,
9
+ type TicketSourceDegradation,
10
+ } from '../kernel/ticket-source-health'
1
11
  import type { RepositoryEvent } from '../events/repository'
2
12
  import { reduceDispatchSettings, type DispatchSettings } from '../kernel/dispatch-settings'
3
13
  import { sandboxStates } from '../processes/sandbox-state'
@@ -7,6 +17,8 @@ import { withSessionlessStore, type StoreOpener } from './store-opening'
7
17
  /** Script-facing projection returned by `ab repository status`. */
8
18
  export interface RepositoryStatus extends DispatchSettings {
9
19
  repo: string
20
+ dispatcher: DispatcherLiveness
21
+ ticketSourceDegradation?: TicketSourceDegradation
10
22
  /** Live operator sandboxes (AUT-340); released environments are omitted. */
11
23
  sandboxes: Array<{
12
24
  operator: string
@@ -38,10 +50,15 @@ export interface RepositoryStatusOpts {
38
50
  json?: boolean
39
51
  /** Explicit --store reference; precedence is owned by repo-state.ts. */
40
52
  storeRef?: string
53
+ now?: () => Date
41
54
  openStore?: StoreOpener
42
55
  }
43
56
 
44
- export function projectRepositoryStatus(repo: string, events: RepositoryEvent[]): RepositoryStatus {
57
+ export function projectRepositoryStatus(
58
+ repo: string,
59
+ events: RepositoryEvent[],
60
+ dispatcher = projectDispatcherLiveness(null, [], new Date()),
61
+ ): RepositoryStatus {
45
62
  const publications: RepositoryStatus['publications'] = []
46
63
  for (const event of events) {
47
64
  if (event.type !== 'orchestrator.sandbox.published') continue
@@ -63,8 +80,11 @@ export function projectRepositoryStatus(repo: string, events: RepositoryEvent[])
63
80
  })
64
81
  }
65
82
  publications.reverse()
83
+ const active = reduceTicketSourceHealth(events)
66
84
  return {
85
+ ...(active === undefined ? {} : { ticketSourceDegradation: active }),
67
86
  repo,
87
+ dispatcher,
68
88
  ...reduceDispatchSettings(events),
69
89
  sandboxes: sandboxStates(events)
70
90
  .filter((state) => state.state !== 'released')
@@ -81,8 +101,30 @@ export function projectRepositoryStatus(repo: string, events: RepositoryEvent[])
81
101
 
82
102
  export function renderRepositoryStatus(status: RepositoryStatus): string[] {
83
103
  const setting = (enabled: boolean): string => (enabled ? 'ON' : 'OFF')
104
+ const active = status.ticketSourceDegradation
84
105
  return [
106
+ ...(active === undefined
107
+ ? []
108
+ : [
109
+ `ticket source ${active.source}: ${active.cause} (${active.operation}) — ${active.message}${'resetAt' in active ? `; reset ${active.resetAt}` : ''}`,
110
+ ]),
85
111
  `repository: ${status.repo}`,
112
+ `dispatcher: ${status.dispatcher.state}${status.dispatcher.holder ? ` — ${formatDispatcherIdentity(status.dispatcher.holder)}` : ' — no dispatcher holds the repository'}`,
113
+ ...(status.dispatcher.expiredHolder
114
+ ? [`expired dispatcher: ${formatDispatcherIdentity(status.dispatcher.expiredHolder)}`]
115
+ : []),
116
+ ...[status.dispatcher.holder ?? status.dispatcher.expiredHolder].flatMap((run) =>
117
+ run
118
+ ? [
119
+ `last tick: ${run.lastTickAt ?? 'unknown'} (${run.lastTickAgeMs ?? 'unknown'}ms ago); ${JSON.stringify(run.lastTick)}`,
120
+ ]
121
+ : [],
122
+ ),
123
+ ...(status.dispatcher.latestStoppedRun
124
+ ? [
125
+ `last dispatcher stop: ${status.dispatcher.latestStoppedRun.stoppedAt}; ${status.dispatcher.latestStoppedRun.stop?.outcome}; signal ${status.dispatcher.latestStoppedRun.stop?.signal ?? 'none'}`,
126
+ ]
127
+ : []),
86
128
  `intake: ${setting(status.intake)}`,
87
129
  `repository pause: ${setting(status.paused)}`,
88
130
  `default auto-merge: ${setting(status.defaultAutoMerge)}`,
@@ -105,10 +147,8 @@ export async function abRepositoryStatus(opts: RepositoryStatusOpts): Promise<vo
105
147
  await withSessionlessStore(opts, async ({ store, repo }) => {
106
148
  // A fresh store has no repository row. Do not call ensureRepo: this query's
107
149
  // empty-stream defaults must remain a genuinely read-only operation.
108
- const record = await store.getRepo(repo)
109
- // Bounded read (AUT-489): projectRepositoryStatus reduces durable types only.
110
- const events = record === null ? [] : await store.getRepoStateEvents(repo)
111
- const status = projectRepositoryStatus(repo, events)
150
+ const { events, dispatcher } = await readDispatcherLiveness(store, repo, opts.now?.())
151
+ const status = projectRepositoryStatus(repo, events, dispatcher)
112
152
  if (opts.json === true) {
113
153
  opts.stdout(JSON.stringify(status, null, 2))
114
154
  return