@defrex/autobuild 1.5.0 → 1.6.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 (74) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +85 -14
  3. package/docs/answering-blocked-builds.md +7 -4
  4. package/docs/architecture.md +38 -10
  5. package/docs/configuration.md +55 -5
  6. package/docs/dispatcher.md +2 -2
  7. package/docs/glossary.md +1 -1
  8. package/docs/operating.md +1 -1
  9. package/docs/operator-api.md +14 -2
  10. package/docs/plugin-authoring.md +4 -0
  11. package/docs/remote-store-protocol.md +14 -4
  12. package/docs/restacking.md +4 -0
  13. package/docs/tickets.md +1 -1
  14. package/docs/troubleshooting.md +1 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/attention.ts +2 -0
  17. package/packages/core/src/cli/dashboard/model.ts +14 -4
  18. package/packages/core/src/cli/dashboard/poll.ts +14 -0
  19. package/packages/core/src/cli/dashboard/render.ts +3 -0
  20. package/packages/core/src/cli/dispatch-preflight.ts +4 -1
  21. package/packages/core/src/cli/dispatch-tickets.ts +47 -0
  22. package/packages/core/src/cli/dispatch-upgrade-controller.ts +3 -0
  23. package/packages/core/src/cli/dispatch.ts +368 -98
  24. package/packages/core/src/cli/help.ts +4 -2
  25. package/packages/core/src/cli/repo-lease.ts +225 -0
  26. package/packages/core/src/cli/repository-status.ts +3 -1
  27. package/packages/core/src/cli/status.ts +13 -13
  28. package/packages/core/src/cli/wait.ts +4 -1
  29. package/packages/core/src/cli/watch.ts +15 -4
  30. package/packages/core/src/config/schema.ts +38 -2
  31. package/packages/core/src/events/catalog.ts +2 -0
  32. package/packages/core/src/events/payloads.ts +15 -0
  33. package/packages/core/src/events/policy.ts +2 -0
  34. package/packages/core/src/events/repository.ts +2 -0
  35. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +196 -230
  36. package/packages/core/src/kernel/dispatch-capacity.ts +134 -30
  37. package/packages/core/src/kernel/engine.ts +13 -6
  38. package/packages/core/src/kernel/generators/build-log.ts +9 -0
  39. package/packages/core/src/kernel/incremental-fixtures.ts +1 -0
  40. package/packages/core/src/kernel/janitor-failure.ts +85 -5
  41. package/packages/core/src/kernel/leaf-restack-state.ts +4 -2
  42. package/packages/core/src/kernel/log-index.ts +1 -1
  43. package/packages/core/src/kernel/node-landing.ts +2 -1
  44. package/packages/core/src/kernel/reducer-registry.ts +6 -1
  45. package/packages/core/src/kernel/reducer.ts +58 -4
  46. package/packages/core/src/kernel/ticket-preparation.ts +11 -7
  47. package/packages/core/src/operator/query.ts +15 -12
  48. package/packages/core/src/ports/tickets/create.ts +19 -5
  49. package/packages/core/src/ports/types.ts +4 -0
  50. package/packages/core/src/ports/workspace/commit-preservation.ts +28 -12
  51. package/packages/core/src/ports/workspace/git-worktree.ts +3 -1
  52. package/packages/core/src/ports/workspace/harvest-execution.ts +4 -2
  53. package/packages/core/src/ports/workspace/vercel-sandbox.ts +3 -0
  54. package/packages/core/src/processes/build-runner.ts +2 -1
  55. package/packages/core/src/processes/dispatcher.ts +231 -41
  56. package/packages/core/src/processes/execution-no-progress.ts +2 -0
  57. package/packages/core/src/processes/harvest-child.ts +4 -2
  58. package/packages/core/src/processes/harvest-execution-state.ts +104 -0
  59. package/packages/core/src/processes/harvest-runner.ts +246 -17
  60. package/packages/core/src/scenarios/harness.ts +145 -35
  61. package/packages/core/src/store/reduced-reads.ts +10 -0
  62. package/packages/core/src/store/reducer-value-shapes.json +1463 -1215
  63. package/packages/core/src/store/remote/released-clients.json +11 -0
  64. package/packages/core/src/store/remote/released-reducer-values/1.6.0.json +27173 -0
  65. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  66. package/packages/core/src/testing/reduced-read-budget.ts +339 -2
  67. package/skills/guide/SKILL.md +53 -17
  68. package/skills/guide/references/operator-api.md +14 -2
  69. package/skills/guide/references/plugin-authoring.md +4 -0
  70. package/skills/guide/references/remote-store-protocol.md +14 -4
  71. package/skills/guide/references/restacking.md +4 -0
  72. package/skills/operate/SKILL.md +50 -11
  73. package/skills/tickets/SKILL.md +4 -2
  74. package/templates/hosted-service/package.json +2 -2
@@ -400,13 +400,15 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
400
400
  ' --store <ref> Override the BuildStore path or URL.',
401
401
  '',
402
402
  'Default filter — actionable attention only. Builds: escalation.raised, phase.deferral-escalated, integration.landed,',
403
- 'integration.verification-failed (failed node verification), build.janitor-failing, build.compatibility-deferred,',
404
- 'node.item-conflicted, target.rewritten, conflicted restack.replayed, derived build.consent-ready and',
403
+ 'integration.verification-failed (failed node verification), build.janitor-failing, build.janitor-escalated,',
404
+ 'build.compatibility-deferred, node.item-conflicted, target.rewritten, conflicted restack.replayed,',
405
+ 'derived build.consent-ready and',
405
406
  'build.merge-decision (a current actionable merge-gate deferral or unsafe forge outcome).',
406
407
  'Consent and held ready merges use only build.consent-ready, once per readiness episode.',
407
408
  'Unready or stale consent candidates stay silent; one merge gate decision per build/PR.',
408
409
  'Repository: harvest.escalated, harvest.recovery-exhausted, dispatcher.config-rejected, dispatcher.forge-readiness-failed,',
409
410
  'dispatcher.kernel-git-unavailable, dispatcher.config-reloaded with restartRequired, abnormal dispatcher.run-stopped,',
411
+ 'abandoned ticket-preparation.resolved (claim confirmed or unconfirmed; ticket unchanged),',
410
412
  'and dispatcher.lost. dispatcher.ticket-source-persistent reports degradation past',
411
413
  'resetAt after a tick started at or after reset completes or fails while still degraded,',
412
414
  'or 15 minutes without a reset; dispatcher.tick-failure-persistent reports',
@@ -0,0 +1,225 @@
1
+ import type { Forge } from '../ports/types'
2
+ import type { Exec } from '../ports/workspace/git-worktree'
3
+
4
+ /** Thrown in place of an effect that a dispatcher attempted without current
5
+ * repository authority: its repository lease lapsed and has not been
6
+ * reclaimed, or a peer replaced it. The effect was never started. Catch sites
7
+ * treat it as "stop this unit quietly", never as a recorded failure. */
8
+ export class RepositoryAuthorityLapsed extends Error {
9
+ constructor(message = 'repository dispatch lease lapsed; effect not started') {
10
+ super(message)
11
+ this.name = 'RepositoryAuthorityLapsed'
12
+ }
13
+ }
14
+
15
+ export function isRepositoryAuthorityLapse(error: unknown): error is RepositoryAuthorityLapsed {
16
+ return error instanceof RepositoryAuthorityLapsed
17
+ }
18
+
19
+ /** First statement of a catch that would otherwise record a failure fact: a
20
+ * lapse is not a failure of the unit, so it escapes unrecorded. */
21
+ export function rethrowAuthorityLapse(error: unknown): void {
22
+ if (isRepositoryAuthorityLapse(error)) throw error
23
+ }
24
+
25
+ /** The repository-lease subset of the BuildStore the resolver needs. */
26
+ export interface RepoLeaseStore {
27
+ getRepo(repo: string): Promise<{ lease?: { holder: string } | null } | null>
28
+ claimRepoLease(repo: string, holder: string, ttlMs: number): Promise<boolean>
29
+ }
30
+
31
+ /** `held`: the lease names this run again with a fresh expiry. `superseded`:
32
+ * another run holds or held it since. `unknown`: the store could not answer;
33
+ * do no work and ask again later. */
34
+ export type LapsedLeaseResolution = 'held' | 'superseded' | 'unknown'
35
+
36
+ /** Decide whether a holder whose own lease looks lapsed was replaced, and
37
+ * reclaim it when it was not. "My lease expired" alone never means "a peer
38
+ * replaced me": expiry leaves the record naming the old holder in every
39
+ * adapter, and only the holder's own release clears it. So:
40
+ *
41
+ * - a record naming this holder, expired or not, is claimed again. The claim
42
+ * is atomic in every adapter, so of two runs racing after expiry exactly one
43
+ * wins; a refused claim means the other one did.
44
+ * - a record naming another holder, expired or not, means a peer took over.
45
+ * - no record means a peer claimed and then released it (run ids are unique).
46
+ *
47
+ * A peer could claim and release between the read and the claim. That window
48
+ * is milliseconds wide and is accepted: the claim would then succeed against
49
+ * an absent record, which is the same outcome as a standby takeover. */
50
+ export async function resolveLapsedRepoLease(
51
+ store: RepoLeaseStore,
52
+ repo: string,
53
+ holder: string,
54
+ ttlMs: number,
55
+ ): Promise<LapsedLeaseResolution> {
56
+ try {
57
+ const record = await store.getRepo(repo)
58
+ if (record?.lease?.holder !== holder) return 'superseded'
59
+ return (await store.claimRepoLease(repo, holder, ttlMs)) ? 'held' : 'superseded'
60
+ } catch {
61
+ return 'unknown'
62
+ }
63
+ }
64
+
65
+ type Guard = () => void
66
+
67
+ /** Shallow method fences: each listed member is guarded when it is called,
68
+ * after every `await` that preceded the call. Nested objects are fenced by
69
+ * their own method lists. */
70
+ export interface EffectFence {
71
+ readonly methods: readonly string[]
72
+ readonly nested?: Readonly<Record<string, EffectFence>>
73
+ }
74
+
75
+ /** A view of `port` whose listed methods call `guard()` before delegating.
76
+ * The guard throws to refuse; a refused call returns a rejected promise and
77
+ * never reaches the port. Unlisted members, reads, and data properties pass
78
+ * through. Methods are applied to the real target, so class `this` and
79
+ * private fields keep working, and the view reports the target's prototype.
80
+ *
81
+ * The proxy wraps an empty facade rather than the port itself. A proxy over
82
+ * the port would have to return a frozen (non-configurable, non-writable)
83
+ * member unchanged, so `Object.freeze` on a plugin would let its effects and
84
+ * nested capabilities escape the fence. The facade has no such invariant.
85
+ *
86
+ * An effect that had already been called before a stall still completes:
87
+ * cancelling it could tear external state. Only effects called afterwards
88
+ * are fenced. */
89
+ export function fenceEffects<T extends object>(port: T, fence: EffectFence, guard: Guard): T {
90
+ const methods = new Set(fence.methods)
91
+ const nested = new Map<PropertyKey, { raw: object; wrapped: object }>()
92
+ const bound = new WeakMap<object, unknown>()
93
+ return new Proxy(Object.create(null) as T, {
94
+ getPrototypeOf: () => Reflect.getPrototypeOf(port),
95
+ has: (_facade, key) => Reflect.has(port, key),
96
+ ownKeys: () => Reflect.ownKeys(port),
97
+ getOwnPropertyDescriptor: (_facade, key) => {
98
+ const descriptor = Reflect.getOwnPropertyDescriptor(port, key)
99
+ return descriptor ? { ...descriptor, configurable: true } : undefined
100
+ },
101
+ set: (_facade, key, value) => Reflect.set(port, key, value, port),
102
+ defineProperty: (_facade, key, descriptor) => Reflect.defineProperty(port, key, descriptor),
103
+ deleteProperty: (_facade, key) => Reflect.deleteProperty(port, key),
104
+ get(_facade, key) {
105
+ const value: unknown = Reflect.get(port, key, port)
106
+ const inner = typeof key === 'string' ? fence.nested?.[key] : undefined
107
+ if (inner && value && typeof value === 'object') {
108
+ const cached = nested.get(key)
109
+ if (cached?.raw === value) return cached.wrapped
110
+ const wrapped = fenceEffects(value, inner, guard)
111
+ nested.set(key, { raw: value, wrapped })
112
+ return wrapped
113
+ }
114
+ if (typeof value !== 'function') return value
115
+ const fn = value as (...args: unknown[]) => unknown
116
+ if (typeof key === 'string' && methods.has(key))
117
+ return (...args: unknown[]) => {
118
+ try {
119
+ guard()
120
+ } catch (error) {
121
+ return Promise.reject(error)
122
+ }
123
+ return fn.apply(port, args)
124
+ }
125
+ let cached = bound.get(fn)
126
+ if (!cached) {
127
+ cached = fn.bind(port)
128
+ bound.set(fn, cached)
129
+ }
130
+ return cached
131
+ },
132
+ })
133
+ }
134
+
135
+ /** Forge members that only observe. Every other function member of a fenced
136
+ * forge, at any depth, is an effect and is refused without authority. Each
137
+ * entry is a read per its contract in `ports/types.ts`. */
138
+ export const FORGE_READ_ALLOWLIST: readonly string[] = [
139
+ 'withReadScope',
140
+ 'primeNodeReads',
141
+ 'observeRequests',
142
+ 'inspectReadiness',
143
+ 'inspectMergeFreshness',
144
+ 'inspectLandingGate',
145
+ 'inspectLandingPr',
146
+ 'compareBranches',
147
+ 'confirmPublication',
148
+ 'snapshotBase',
149
+ 'getPrState',
150
+ 'readCommitMessage',
151
+ 'containsBuild',
152
+ 'remoteBranchSha',
153
+ 'remoteBranchExists',
154
+ 'isCommitAncestor',
155
+ 'readFile',
156
+ ]
157
+
158
+ const FORGE_CAPABILITIES = ['rewrite', 'kernelRewrite', 'prAttachments']
159
+
160
+ /** A `git push` anywhere in a command line is a publication. */
161
+ function isGitPush(cmd: readonly string[]): boolean {
162
+ return cmd[0] === 'git' && cmd.includes('push')
163
+ }
164
+
165
+ /** Exec that refuses `git push` without authority; every other command runs. */
166
+ export function fenceExec(exec: Exec, guard: Guard): Exec {
167
+ return (cmd, opts) => {
168
+ if (isGitPush(cmd)) {
169
+ try {
170
+ guard()
171
+ } catch (error) {
172
+ return Promise.reject(error)
173
+ }
174
+ }
175
+ return exec(cmd, opts)
176
+ }
177
+ }
178
+
179
+ /** Deny-by-default forge fence. Every function member, including every method
180
+ * of the nested `rewrite`, `kernelRewrite` and `prAttachments` capabilities and
181
+ * any plugin-added method, is an effect unless it is on the read allowlist.
182
+ * `kernelExec` is fenced for `git push` only. Non-function properties pass
183
+ * through. Compose it underneath `guardForge`, so the guard's identity memo
184
+ * still recognises the outer object. */
185
+ export function fenceForge(forge: Forge, guard: Guard): Forge {
186
+ return fenceForgeObject(forge, guard, new Set(FORGE_READ_ALLOWLIST)) as Forge
187
+ }
188
+
189
+ function fenceForgeObject(target: object, guard: Guard, reads: ReadonlySet<string>): object {
190
+ const nested = new Map<PropertyKey, { raw: object; wrapped: object }>()
191
+ return new Proxy(
192
+ {},
193
+ {
194
+ has: (_facade, key) => key in target,
195
+ ownKeys: () => Reflect.ownKeys(target),
196
+ getOwnPropertyDescriptor: (_facade, key) => {
197
+ const descriptor = Reflect.getOwnPropertyDescriptor(target, key)
198
+ return descriptor ? { ...descriptor, configurable: true } : undefined
199
+ },
200
+ get(_facade, key) {
201
+ const value: unknown = Reflect.get(target, key, target)
202
+ const name = String(key)
203
+ if (value && typeof value === 'object' && FORGE_CAPABILITIES.includes(name)) {
204
+ const cached = nested.get(key)
205
+ if (cached?.raw === value) return cached.wrapped
206
+ const wrapped = fenceForgeObject(value, guard, new Set())
207
+ nested.set(key, { raw: value, wrapped })
208
+ return wrapped
209
+ }
210
+ if (typeof value !== 'function') return value
211
+ const fn = value as (...args: unknown[]) => unknown
212
+ if (name === 'kernelExec') return fenceExec(fn.bind(target) as Exec, guard)
213
+ if (reads.has(name)) return fn.bind(target)
214
+ return (...args: unknown[]) => {
215
+ try {
216
+ guard()
217
+ } catch (error) {
218
+ return Promise.reject(error)
219
+ }
220
+ return fn.apply(target, args)
221
+ }
222
+ },
223
+ },
224
+ )
225
+ }
@@ -9,6 +9,7 @@ import {
9
9
  type UpgradeRun,
10
10
  } from '../kernel/dispatch-upgrade'
11
11
  import { formatRuntimeIdentity } from '../events/runtime'
12
+ import { landingRestackDue } from '../kernel/engine'
12
13
  import {
13
14
  dispatchCapacity,
14
15
  waitingExplanation,
@@ -432,7 +433,7 @@ export function renderRepositoryStatus(status: RepositoryStatus): string[] {
432
433
  `repository: ${status.repo}`,
433
434
  ...(status.capacity
434
435
  ? [
435
- `capacity: ${status.capacity.occupied}/${status.capacity.effective} effective; ${status.capacity.configured} configured; ${status.capacity.borrowingNodes.length} node${status.capacity.borrowingNodes.length === 1 ? '' : 's'} using descendant-held slots${status.capacity.borrowingNodes.length ? `: ${status.capacity.borrowingNodes.join(', ')}` : ''}${status.capacity.waitingNodes?.length ? `; ${waitingExplanation(status.capacity, { requests: true })}` : ''}`,
436
+ `capacity: ${status.capacity.occupied}/${status.capacity.effective} effective; ${status.capacity.configured} configured; ${status.capacity.borrowingNodes.length} node${status.capacity.borrowingNodes.length === 1 ? '' : 's'} using descendant-held slots${status.capacity.borrowingNodes.length ? `: ${status.capacity.borrowingNodes.join(', ')}` : ''}${status.capacity.waitingNodes?.length || status.capacity.waitingBuilds?.length ? `; ${waitingExplanation(status.capacity, { requests: true })}` : ''}`,
436
437
  ]
437
438
  : []),
438
439
  ...(status.warningLines ?? []),
@@ -499,6 +500,7 @@ export async function readRepositoryCapacity(
499
500
  state: build.state,
500
501
  workspace: build.workspace !== null,
501
502
  provisioning: build.provisionMarker !== undefined,
503
+ restackDue: landingRestackDue(build.state, build.log),
502
504
  })
503
505
  }
504
506
  return dispatchCapacity(
@@ -10,6 +10,7 @@ import { buildVocabulary } from './dashboard/model'
10
10
  import { readBuildDigests } from '../store/reduced-reads'
11
11
  import { readBuildFacts } from '../store/reduced-reads'
12
12
  import { slotRequest, slotWaitText, type SlotRequest } from '../kernel/dispatch-capacity'
13
+ import { landingRestackDue } from '../kernel/engine'
13
14
  import type { BuildFacts } from '../processes/repo-view'
14
15
  /**
15
16
  * `ab builds` and `ab build status <slug>` — the read-only query surface on
@@ -127,7 +128,7 @@ export interface BuildSummary {
127
128
  lease: LeaseInfo
128
129
  /** Durable-event progress, separate from mutable lease renewal. */
129
130
  progress: BuildProgress
130
- /** A node's runner request, admitted ahead of new ticket claims. */
131
+ /** A node's or parked build's runner request, admitted ahead of new ticket claims. */
131
132
  slotWait?: SlotRequest
132
133
  }
133
134
 
@@ -598,7 +599,7 @@ export function renderSummaries(summaries: BuildSummary[], now: Date, emptyNote:
598
599
  summary.status,
599
600
  summary.kind === 'integration'
600
601
  ? `integration ${summary.integration ?? ''}${summary.slotWait ? `, ${slotWaitText(summary.slotWait)}` : ''}`
601
- : phaseCell(summary),
602
+ : `${phaseCell(summary)}${summary.slotWait ? `, ${slotWaitText(summary.slotWait)}` : ''}`,
602
603
  healthWord(summary.lease.health),
603
604
  summary.progress.heartbeatAt === undefined
604
605
  ? '—'
@@ -967,17 +968,16 @@ export async function abBuilds(opts: AbBuildsOpts): Promise<void> {
967
968
  record,
968
969
  facts.state,
969
970
  now,
970
- facts.state.kind === 'node'
971
- ? slotRequest(
972
- {
973
- record,
974
- state: facts.state,
975
- workspace: facts.workspace !== null,
976
- provisioning: facts.provisionMarker !== undefined,
977
- },
978
- now,
979
- )
980
- : undefined,
971
+ slotRequest(
972
+ {
973
+ record,
974
+ state: facts.state,
975
+ workspace: facts.workspace !== null,
976
+ provisioning: facts.provisionMarker !== undefined,
977
+ restackDue: landingRestackDue(facts.state, facts.log),
978
+ },
979
+ now,
980
+ ),
981
981
  )
982
982
  if (wanted.has(summary.status)) summaries.push(summary)
983
983
  }
@@ -465,6 +465,7 @@ export async function abWait(opts: AbWaitOpts): Promise<number> {
465
465
  condition === 'consent' ||
466
466
  (condition === 'attention' &&
467
467
  event.type !== 'phase.deferral-escalated' &&
468
+ event.type !== 'build.janitor-escalated' &&
468
469
  event.type !== 'escalation.raised')
469
470
  ? consentReady(seed, now())
470
471
  : null
@@ -472,7 +473,8 @@ export async function abWait(opts: AbWaitOpts): Promise<number> {
472
473
  consent ??
473
474
  (condition === 'attention' &&
474
475
  event.type !== 'escalation.raised' &&
475
- event.type !== 'phase.deferral-escalated'
476
+ event.type !== 'phase.deferral-escalated' &&
477
+ event.type !== 'build.janitor-escalated'
476
478
  ? mergeDecisionFromFacts(state, seed.deferral, now())
477
479
  : null)
478
480
  if (consent) deliveredAttention.add(consentIdentity(event.build, consent.position))
@@ -512,6 +514,7 @@ export async function abWait(opts: AbWaitOpts): Promise<number> {
512
514
  if (
513
515
  event.type === 'escalation.raised' ||
514
516
  event.type === 'phase.deferral-escalated' ||
517
+ event.type === 'build.janitor-escalated' ||
515
518
  event.type === 'integration.landed' ||
516
519
  event.type === 'integration.verification-failed' ||
517
520
  event.type === 'node.item-conflicted' ||
@@ -6,6 +6,7 @@ import { randomUUID } from 'node:crypto'
6
6
  import { OPERATOR_HEARTBEAT_MS, operatorIdentitySchema } from '../store/operator-presence'
7
7
  import { consentReady, consentIdentity, type ConsentReady } from './attention'
8
8
  import { formatReadinessFailure } from '../ports/forge/readiness'
9
+ import { abandonedPreparationDiagnostic } from '../kernel/ticket-preparation'
9
10
  import { readDispatchUpgrade, readBuildDigests } from '../store/reduced-reads'
10
11
  import { readBuildStreamSeed, readRepositoryAttention } from '../store/reduced-reads'
11
12
  import { buildStreamSeedReducer, type BuildStreamSeed } from '../kernel/read-facts'
@@ -112,6 +113,7 @@ const TERMINAL_STATUSES: readonly BuildStatus[] = ['done', 'aborted']
112
113
  export const BUILD_ATTENTION_EVENTS = [
113
114
  'target.rewritten',
114
115
  'build.janitor-failing',
116
+ 'build.janitor-escalated',
115
117
  'build.compatibility-deferred',
116
118
  'escalation.raised',
117
119
  'phase.deferral-escalated',
@@ -462,6 +464,7 @@ export function summarizeEvent(event: AbEvent | RepositoryEvent, state: BuildSta
462
464
  case 'dispatcher.kernel-git-recovered':
463
465
  return `Kernel Git recovered (${event.payload.executable})`
464
466
  case 'phase.deferral-escalated':
467
+ case 'build.janitor-escalated':
465
468
  case 'escalation.raised':
466
469
  return `${event.payload.id}: ${singleLine(event.payload.question)}`
467
470
  case 'build.compatibility-deferred':
@@ -520,13 +523,21 @@ export function summarizeEvent(event: AbEvent | RepositoryEvent, state: BuildSta
520
523
  return `dispatcher config rejected: ${singleLine(event.payload.error)}`
521
524
  case 'dispatcher.harvest-runner-failed':
522
525
  return `harvest runner failed: ${singleLine(event.payload.error)}`
523
- default: {
524
- const compact = singleLine(JSON.stringify(event.payload))
525
- return compact.length > SUMMARY_MAX ? `${compact.slice(0, SUMMARY_MAX - 1)}…` : compact
526
- }
526
+ case 'ticket-preparation.resolved':
527
+ if (event.payload.outcome === 'abandoned') {
528
+ return singleLine(abandonedPreparationDiagnostic(event.payload, event.payload.reason))
529
+ }
530
+ return summarizePayload(event.payload)
531
+ default:
532
+ return summarizePayload(event.payload)
527
533
  }
528
534
  }
529
535
 
536
+ function summarizePayload(payload: unknown): string {
537
+ const compact = singleLine(JSON.stringify(payload))
538
+ return compact.length > SUMMARY_MAX ? `${compact.slice(0, SUMMARY_MAX - 1)}…` : compact
539
+ }
540
+
530
541
  /** The human form: one line, timestamp first, no ANSI anywhere. */
531
542
  export function renderWatchLine(
532
543
  event: AbEvent | RepositoryEvent,
@@ -729,8 +729,23 @@ export type RoleConfig = z.infer<typeof roleSchema>
729
729
 
730
730
  // ── [policy] ─────────────────────────────────────────────────────────────────
731
731
 
732
+ const DISPATCH_LEASE_PAIR_MESSAGE =
733
+ 'policy.dispatchLeaseTimeoutSeconds and policy.dispatchLeaseRenewalSeconds must be positive integers, with dispatchLeaseRenewalSeconds less than dispatchLeaseTimeoutSeconds'
734
+
732
735
  export const policySchema = z.strictObject({
733
736
  upgradeDrainSeconds: z.number().int().positive().default(900),
737
+ /** Repository dispatch lease lifetime without renewal (SPEC §12). */
738
+ dispatchLeaseTimeoutSeconds: z
739
+ .number()
740
+ .int(DISPATCH_LEASE_PAIR_MESSAGE)
741
+ .positive(DISPATCH_LEASE_PAIR_MESSAGE)
742
+ .default(60),
743
+ /** Interval between repository dispatch lease renewals; below the timeout. */
744
+ dispatchLeaseRenewalSeconds: z
745
+ .number()
746
+ .int(DISPATCH_LEASE_PAIR_MESSAGE)
747
+ .positive(DISPATCH_LEASE_PAIR_MESSAGE)
748
+ .default(20),
734
749
  /** Wall-clock bound for an agent phase session; roles may override it. */
735
750
  sessionBudgetSeconds: z.number().int().positive().default(3600),
736
751
  /** Same-finding survival threshold before auto-escalate (§10, §15.4). */
@@ -740,7 +755,7 @@ export const policySchema = z.strictObject({
740
755
  maxDispatchAttempts: z.number().int().positive().default(3),
741
756
  /** Consecutive workspace setup failures before human intervention is required. */
742
757
  maxSetupAttempts: z.number().int().positive().default(3),
743
- /** Consecutive provider lifecycle failures before recovery requires a human retry. */
758
+ /** Consecutive provider lifecycle failures before a setup-targeted escalation; a `retry` answer from any operator, agent or human, re-arms the budget. */
744
759
  maxInfrastructureAttempts: z.number().int().positive().default(3),
745
760
  maxReconcileAttempts: z.number().int().positive().default(3),
746
761
  /** converge's `maxRounds` for the review loops (SPEC §10). */
@@ -749,6 +764,7 @@ export const policySchema = z.strictObject({
749
764
  harvestThreshold: z.number().int().positive().default(5),
750
765
  /** Merged builds after the oldest observation that start harvest; zero disables drift. */
751
766
  janitorFailureAttentionSeconds: z.number().int().positive().default(600),
767
+ janitorFailureEscalationSeconds: z.number().int().positive().default(3600),
752
768
  nodeIdleAfterSeconds: z.number().int().positive().default(600),
753
769
  nodeIdlePollSeconds: z.number().int().positive().default(120),
754
770
  janitorBackoffMaxSeconds: z.number().int().positive().default(300),
@@ -758,6 +774,10 @@ export const policySchema = z.strictObject({
758
774
  documentFields(policySchema, {
759
775
  upgradeDrainSeconds:
760
776
  'Deadline for a retiring generation, relative to handoff start; hot-reloaded during drain.',
777
+ dispatchLeaseTimeoutSeconds:
778
+ "How long the repository dispatch lease survives without renewal. A dispatcher that stalls longer reclaims it on waking unless another run took it; a standby takes over a dead holder within this bound. A change takes effect at the dispatcher's next tick.",
779
+ dispatchLeaseRenewalSeconds:
780
+ 'Interval between repository dispatch lease renewals; adopted together with the timeout.',
761
781
  sessionBudgetSeconds:
762
782
  'Active-time bound for each build agent session unless its logical role overrides it. Native continuation retains the original ceiling; suspension does not consume it.',
763
783
  stallRounds: 'Escalate when the same review finding survives this many rounds.',
@@ -774,12 +794,20 @@ documentFields(policySchema, {
774
794
  'Default bound for each plan/review and implement/review convergence loop. Your agent may replace it for one parked build loop and current spec revision with `ab answer --review-round-ceiling`; other builds are unaffected.',
775
795
  harvestThreshold: 'New unclaimed observation occurrences needed to start one harvest run.',
776
796
  janitorFailureAttentionSeconds: 'Consecutive janitor failure duration before build attention.',
797
+ janitorFailureEscalationSeconds:
798
+ 'Consecutive janitor failure duration before the build raises one escalation; the janitor keeps retrying.',
777
799
  nodeIdleAfterSeconds: 'Quiet period before opened integration nodes enter idle polling.',
778
800
  nodeIdlePollSeconds: 'Interval between idle node checks; durable activity wakes the next tick.',
779
801
  janitorBackoffMaxSeconds: 'Cap on exponential janitor retry delay, starting at 30 seconds.',
780
802
  harvestMaxDrift:
781
803
  'Other builds merged after the oldest unclaimed observation needed to start a run; `0` disables drift.',
782
804
  })
805
+ documentSchema(policySchema.shape.dispatchLeaseTimeoutSeconds, {
806
+ constraints: 'Must be greater than `dispatchLeaseRenewalSeconds`.',
807
+ })
808
+ documentSchema(policySchema.shape.dispatchLeaseRenewalSeconds, {
809
+ constraints: 'Must be less than `dispatchLeaseTimeoutSeconds`.',
810
+ })
783
811
  export type PolicyConfig = z.infer<typeof policySchema>
784
812
 
785
813
  // ── [tickets] ────────────────────────────────────────────────────────────────
@@ -1191,7 +1219,7 @@ documentFields(configRootSchema, {
1191
1219
  upgrade: 'Automatic dispatcher runtime target checks and adoption.',
1192
1220
  baseBranch: 'Branch used to cut builds, target PRs, and merge during reconciliation.',
1193
1221
  capacity:
1194
- 'Concurrent occupied slots for this repository. Paused and blocked work retains slots. Node reconcile and verification exclude their own blocked/paused descendants at admission; new claims use total occupancy. See [integration capacity](integration-tree.md).',
1222
+ 'Builds running work at once for this repository. A build that finished its pipeline holds no slot while it waits for a merge decision; it is admitted ahead of new claims when it must run again. Unfinished paused and blocked work retains slots. Node reconcile and verification exclude their own blocked/paused descendants at admission; new claims use total occupancy. See [integration capacity](integration-tree.md).',
1195
1223
  ticketScanIntervalSeconds:
1196
1224
  'Ticket-source ready scan cadence; tick spacing is the effective minimum.',
1197
1225
  forge:
@@ -1255,6 +1283,14 @@ const normalizedConfigSchema = configRootSchema.transform((input, ctx) => {
1255
1283
  })
1256
1284
 
1257
1285
  export const configSchema = normalizedConfigSchema.superRefine((config, ctx) => {
1286
+ const { dispatchLeaseTimeoutSeconds: leaseTimeout, dispatchLeaseRenewalSeconds: leaseRenewal } =
1287
+ config.policy
1288
+ if (leaseRenewal >= leaseTimeout)
1289
+ ctx.addIssue({
1290
+ code: 'custom',
1291
+ path: ['policy', 'dispatchLeaseRenewalSeconds'],
1292
+ message: `${DISPATCH_LEASE_PAIR_MESSAGE} (dispatchLeaseRenewalSeconds = ${leaseRenewal}, dispatchLeaseTimeoutSeconds = ${leaseTimeout})`,
1293
+ })
1258
1294
  for (const [name, account] of Object.entries(config.accounts)) {
1259
1295
  if (account.kind !== 'chatgpt-subscription') continue
1260
1296
  if (
@@ -47,6 +47,7 @@ export const allowedActorKinds: Record<EventType, readonly ActorKind[]> = {
47
47
  'build.janitor-attempt-failed': ['dispatcher'],
48
48
  'build.janitor-recovered': ['dispatcher'],
49
49
  'build.janitor-failing': ['dispatcher'],
50
+ 'build.janitor-escalated': ['dispatcher'],
50
51
  'landing.application-failed': ['dispatcher', 'kernel'],
51
52
  'landing.decided': ['dispatcher', 'kernel'],
52
53
  'build.hold-requested': ['human'],
@@ -56,6 +57,7 @@ export const allowedActorKinds: Record<EventType, readonly ActorKind[]> = {
56
57
  'landing.forge-merged': ['kernel'],
57
58
  'landing.native-applied': ['dispatcher', 'kernel'],
58
59
  'target.distance': ['dispatcher'],
60
+ 'pipeline.settled': ['dispatcher'],
59
61
  'target.rewritten': ['dispatcher', 'kernel'],
60
62
  'target.rewrite-cleared': ['dispatcher', 'kernel'],
61
63
  'target.moved': ['dispatcher', 'kernel'],
@@ -890,6 +890,16 @@ export const eventPayloadSchemas = {
890
890
  nextAttemptAt: z.iso.datetime(),
891
891
  }),
892
892
  'build.janitor-failing': z.strictObject({ message: z.string().min(1) }),
893
+ /** One per janitor failure episode that outlasts the escalation limit. The
894
+ * reducer opens it as a policy escalation and closes it on recovery. */
895
+ 'build.janitor-escalated': z.strictObject({
896
+ id: z.string().min(1),
897
+ operation: z.string().min(1),
898
+ message: z.string().min(1),
899
+ attempt: z.number().int().positive(),
900
+ firstFailureAt: z.iso.datetime(),
901
+ question: z.string().min(1),
902
+ }),
893
903
  'build.janitor-recovered': empty,
894
904
  'landing.application-failed': z.strictObject({
895
905
  candidate: landingCandidateSchema,
@@ -1216,6 +1226,11 @@ export const eventPayloadSchemas = {
1216
1226
  count: z.number().int().nonnegative().nullable(),
1217
1227
  })
1218
1228
  .refine((sample) => sample.count === null || sample.head !== null),
1229
+ /** The dispatcher observed the engine's leaf `wait awaiting-pr` decision:
1230
+ * every verify step and finalize post-step is done for this settlement key
1231
+ * (max of the verify cycle start and finalize completion seqs). Capacity
1232
+ * evidence only; no pipeline decision reads it. */
1233
+ 'pipeline.settled': z.strictObject({ cycle: z.number().int().positive() }),
1219
1234
  'target.rewritten': z.strictObject({
1220
1235
  branch: z.string().min(1),
1221
1236
  previousSha: gitOid,
@@ -14,6 +14,7 @@ export const buildEventPolicy = {
14
14
  'build.janitor-attempt-failed': 'decisive',
15
15
  'build.janitor-recovered': 'decisive',
16
16
  'build.janitor-failing': 'advisory',
17
+ 'build.janitor-escalated': 'decisive',
17
18
  'landing.application-failed': 'decisive',
18
19
  'landing.decided': 'decisive',
19
20
  'build.hold-requested': 'decisive',
@@ -23,6 +24,7 @@ export const buildEventPolicy = {
23
24
  'landing.forge-merged': 'decisive',
24
25
  'landing.native-applied': 'decisive',
25
26
  'target.distance': 'advisory',
27
+ 'pipeline.settled': 'advisory',
26
28
  'target.rewritten': 'decisive',
27
29
  'target.rewrite-cleared': 'decisive',
28
30
  'target.moved': 'decisive',
@@ -847,6 +847,8 @@ export const ticketPreparationEventPayloadSchemas = {
847
847
  ...preparationIdentity,
848
848
  outcome: z.enum(['lost-claim', 'handed-back', 'bounced', 'owned', 'abandoned']),
849
849
  reason: z.string().min(1).max(4000).optional(),
850
+ /** Written only for `abandoned`: the claim certainty known at resolution. */
851
+ claimed: z.boolean().optional(),
850
852
  }),
851
853
  }
852
854