@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
@@ -3,6 +3,7 @@ import release0 from './1.2.0.json'
3
3
  import release1 from './1.3.0.json'
4
4
  import release2 from './1.4.0.json'
5
5
  import release3 from './1.5.0.json'
6
+ import release4 from './1.6.0.json'
6
7
  import type { ReducerValueCatalog } from '../../reducer-value-validation'
7
8
  export interface ReleasedReducerValues extends ReducerValueCatalog {
8
9
  versions: Record<string, number>
@@ -12,4 +13,5 @@ export const RELEASED_REDUCER_VALUES: Readonly<Record<string, ReleasedReducerVal
12
13
  '1.3.0.json': release1,
13
14
  '1.4.0.json': release2,
14
15
  '1.5.0.json': release3,
16
+ '1.6.0.json': release4,
15
17
  }
@@ -9,6 +9,7 @@ import { REPLACED_HEADS_CAP } from '../kernel/read-facts'
9
9
  import { observeTarget } from '../kernel/target-observation'
10
10
  import { autoMergeDeferralObservation } from '../kernel/auto-merge'
11
11
  import { mkdtemp, writeFile, rm } from 'node:fs/promises'
12
+ import { AsyncLocalStorage } from 'node:async_hooks'
12
13
  import { tmpdir } from 'node:os'
13
14
  import { join } from 'node:path'
14
15
  import { DashboardBuildPollCache } from '../cli/dashboard/poll'
@@ -43,7 +44,9 @@ import {
43
44
  readBuildDigests,
44
45
  readDispatcherRunFacts,
45
46
  readOpenTick,
47
+ readHostedHarvestAuthority,
46
48
  } from '../store/reduced-reads'
49
+ import { decideHostedHarvestAuthority } from '../processes/harvest-execution-state'
47
50
  import { RepoViewStore } from '../processes/repo-view'
48
51
  import { settlePendingPublication } from '../cli/publication-settlement'
49
52
  import {
@@ -1383,6 +1386,7 @@ export async function parkedSweepReadBudget(opts: {
1383
1386
  },
1384
1387
  })
1385
1388
  let seeded = 0
1389
+ const idleRequests: Record<string, number>[] = []
1386
1390
  for (const length of [100, 100_000]) {
1387
1391
  for (; seeded < length; seeded++) {
1388
1392
  await store.append(slugs[0]!, {
@@ -1469,6 +1473,31 @@ export async function parkedSweepReadBudget(opts: {
1469
1473
  expect(metrics.bodies).toBe(slugs.length)
1470
1474
  expect(blobReads).toBe(slugs.length)
1471
1475
  expect(metrics.historicalRows).toBe(0)
1476
+ // Idle admission ticks over settled parked builds: capacity adds no
1477
+ // recurring read and writes nothing, at either history length.
1478
+ reset()
1479
+ await dispatcher.tick({ acceptNewWork: false })
1480
+ const baseline = { meta: metrics.meta, bodies: metrics.bodies }
1481
+ const idle = opts.dispatcher()
1482
+ opts.advance()
1483
+ // Warm intake's own projections and persist their snapshots.
1484
+ for (const _ of [0, 1]) {
1485
+ await idle.tick({ acceptNewWork: true })
1486
+ opts.advance()
1487
+ }
1488
+ for (const _ of [0, 1]) {
1489
+ opts.advance()
1490
+ reset()
1491
+ const requests = await countStoreRequests(store, () =>
1492
+ idle.tick({ acceptNewWork: true }).then(() => undefined),
1493
+ )
1494
+ expect(requests.append ?? 0).toBe(0)
1495
+ expect(requests.appendIfCurrent ?? 0).toBe(0)
1496
+ expect(metrics.historicalRows).toBe(0)
1497
+ expect({ meta: metrics.meta, bodies: metrics.bodies }).toEqual(baseline)
1498
+ if (idleRequests.length) expect(requests).toEqual(idleRequests[0]!)
1499
+ idleRequests.push(requests)
1500
+ }
1472
1501
  console.log('parked sweep read budget', {
1473
1502
  history: length,
1474
1503
  builds: slugs.length,
@@ -1483,6 +1512,35 @@ export async function parkedSweepReadBudget(opts: {
1483
1512
  }
1484
1513
  }
1485
1514
 
1515
+ /** Count every MemoryBuildStore method call made while `run` executes. */
1516
+ async function countStoreRequests(
1517
+ store: import('../store/memory').MemoryBuildStore,
1518
+ run: () => Promise<void>,
1519
+ ): Promise<Record<string, number>> {
1520
+ const counts: Record<string, number> = {}
1521
+ const names = Object.getOwnPropertyNames(Object.getPrototypeOf(store)).filter(
1522
+ (name) => name !== 'constructor' && typeof Reflect.get(store, name) === 'function',
1523
+ )
1524
+ const restore: (() => void)[] = []
1525
+ for (const name of names) {
1526
+ const own = Object.getOwnPropertyDescriptor(store, name)
1527
+ const original = Reflect.get(store, name) as (...args: unknown[]) => unknown
1528
+ Reflect.set(store, name, (...args: unknown[]) => {
1529
+ counts[name] = (counts[name] ?? 0) + 1
1530
+ return original.apply(store, args)
1531
+ })
1532
+ restore.push(() =>
1533
+ own ? Object.defineProperty(store, name, own) : Reflect.deleteProperty(store, name),
1534
+ )
1535
+ }
1536
+ try {
1537
+ await run()
1538
+ } finally {
1539
+ for (const undo of restore) undo()
1540
+ }
1541
+ return counts
1542
+ }
1543
+
1486
1544
  /** Append filler facts to one build until its log holds `length` events. */
1487
1545
  async function seedBuildFiller(
1488
1546
  store: import('../store/memory').MemoryBuildStore,
@@ -2121,21 +2179,39 @@ export async function kernelGitOutageReadBudget(opts: {
2121
2179
  }
2122
2180
  }
2123
2181
 
2124
- /** Expired sampled owners resolve once through exact persisted run values. */
2182
+ /** Expired sampled owners resolve once through exact persisted run values;
2183
+ * historical abandoned preparations never replay and a new one reports once. */
2125
2184
  export async function stoppedOwnerWatchReadBudget() {
2126
2185
  const { MemoryBuildStore } = await import('../store/memory')
2127
2186
  const { manualClock } = await import('./fixed')
2128
2187
  let previousBytes: number | undefined
2188
+ const abandon = (store: BuildStore, attempt: string) =>
2189
+ store.appendRepo(repo, {
2190
+ actor: DISPATCHER,
2191
+ type: 'ticket-preparation.resolved',
2192
+ payload: {
2193
+ attempt,
2194
+ ticket: { source: 'fake', id: attempt },
2195
+ outcome: 'abandoned',
2196
+ reason: 'Ticket no longer exists; ticket unchanged.',
2197
+ claimed: false,
2198
+ },
2199
+ })
2129
2200
  for (const length of [100, 100_000]) {
2130
2201
  const clock = manualClock()
2131
2202
  const store = new MemoryBuildStore({ clock })
2132
2203
  await store.ensureRepo(repo)
2133
- for (let i = 0; i < length; i++)
2204
+ for (let i = 0; i < length; i++) {
2205
+ if (i % 1000 === 50) {
2206
+ await abandon(store, `historical-${i}`)
2207
+ continue
2208
+ }
2134
2209
  await store.appendRepo(repo, {
2135
2210
  actor: humanActor('human'),
2136
2211
  type: 'dispatcher.intake-set',
2137
2212
  payload: { enabled: true },
2138
2213
  })
2214
+ }
2139
2215
  const start = async (run: string) => {
2140
2216
  await store.appendRepo(repo, {
2141
2217
  actor: DISPATCHER,
@@ -2191,6 +2267,7 @@ export async function stoppedOwnerWatchReadBudget() {
2191
2267
  await stop('B')
2192
2268
  await start('C')
2193
2269
  }
2270
+ if (tick === 3) await abandon(store, 'fresh')
2194
2271
  if (tick === 6) {
2195
2272
  counter.reset()
2196
2273
  quietCalls = counter.reducedCalls
@@ -2203,6 +2280,12 @@ export async function stoppedOwnerWatchReadBudget() {
2203
2280
  .filter((r) => r.observation)
2204
2281
  .map((r) => r.observation.run),
2205
2282
  ).toEqual(['C'])
2283
+ expect(
2284
+ output
2285
+ .map((line) => JSON.parse(line))
2286
+ .filter((r) => r.event?.type === 'ticket-preparation.resolved')
2287
+ .map((r) => r.event.payload.attempt),
2288
+ ).toEqual(['fresh'])
2206
2289
  expect(counter.rows).toBe(0)
2207
2290
  expect(counter.reducedCalls - quietCalls).toBeLessThan(20)
2208
2291
  await readDispatcherRunFacts(store, repo, 'missing')
@@ -2947,3 +3030,257 @@ export async function noDispatcherRunDashboardBudget() {
2947
3030
  expect(counter.rows).toBe(0)
2948
3031
  }
2949
3032
  }
3033
+
3034
+ /** Tally the store requests callers make, by method name: every
3035
+ * function-valued store method is counted when entered from outside the store,
3036
+ * never when the adapter calls its own methods. `restore` removes the
3037
+ * instrumentation. */
3038
+ export function memoryStoreRequestCounter(store: BuildStore) {
3039
+ const inside = new AsyncLocalStorage<true>()
3040
+ const counts = new Map<string, number>()
3041
+ const names = new Set<string>()
3042
+ for (
3043
+ let proto: object | null = store;
3044
+ proto && proto !== Object.prototype;
3045
+ proto = Object.getPrototypeOf(proto)
3046
+ )
3047
+ for (const name of Object.getOwnPropertyNames(proto))
3048
+ if (name !== 'constructor' && typeof Reflect.get(store, name) === 'function') names.add(name)
3049
+ const wrapped = new Map<string, { own: boolean; original: (...args: unknown[]) => unknown }>()
3050
+ for (const name of names) {
3051
+ const original = Reflect.get(store, name) as (...args: unknown[]) => unknown
3052
+ wrapped.set(name, { own: Object.hasOwn(store, name), original })
3053
+ Reflect.set(store, name, (...args: unknown[]) => {
3054
+ if (inside.getStore()) return original.apply(store, args)
3055
+ counts.set(name, (counts.get(name) ?? 0) + 1)
3056
+ return inside.run(true, () => original.apply(store, args))
3057
+ })
3058
+ }
3059
+ return {
3060
+ /** Calls since the last reset, by method name, in sorted order. */
3061
+ vector(): Record<string, number> {
3062
+ return Object.fromEntries([...counts].sort(([a], [b]) => a.localeCompare(b)))
3063
+ },
3064
+ reset() {
3065
+ counts.clear()
3066
+ },
3067
+ restore() {
3068
+ for (const [name, { own, original }] of wrapped)
3069
+ if (own) Reflect.set(store, name, original)
3070
+ else Reflect.deleteProperty(store, name)
3071
+ },
3072
+ }
3073
+ }
3074
+
3075
+ /** A janitor that keeps failing for one build costs every fresh-dispatcher tick
3076
+ * the same store requests at 100 and at 100,000 events. The vectors are
3077
+ * returned per tick class so a caller can pin them against an earlier
3078
+ * implementation: episode start, a failure before attention, the attention
3079
+ * failure, a failure before the escalation limit, the threshold failure, a
3080
+ * failure after it, and the recovering attempt. */
3081
+ export async function janitorEscalationRequestBudget(opts: {
3082
+ store: import('../store/memory').MemoryBuildStore
3083
+ repo: string
3084
+ slug: string
3085
+ /** One tick on a fresh dispatcher. */
3086
+ tick: () => Promise<unknown>
3087
+ now: () => Date
3088
+ advance: (ms: number) => void
3089
+ /** Make the build's janitor work fail (true) or succeed (false). */
3090
+ failing: (value: boolean) => void
3091
+ /** Episode age at which the threshold failure is expected. */
3092
+ limitSeconds: number
3093
+ attentionSeconds: number
3094
+ }) {
3095
+ const { store, repo, slug } = opts
3096
+ type Vectors = Record<
3097
+ 'start' | 'preAttention' | 'attention' | 'preLimit' | 'threshold' | 'escalated' | 'recovery',
3098
+ Record<string, number>
3099
+ >
3100
+ const escalations = async () =>
3101
+ (await store.getEvents(slug)).filter(
3102
+ (event) => String(event.type) === 'build.janitor-escalated',
3103
+ ).length
3104
+ const results: { length: number; vectors: Vectors; escalations: number }[] = []
3105
+ await store.ensureRepo(repo)
3106
+ let seeded = 0
3107
+ for (const length of [100, 100_000]) {
3108
+ for (; seeded < length; seeded++) {
3109
+ await store.appendRepo(repo, {
3110
+ actor: humanActor('budget'),
3111
+ type: 'dispatcher.intake-set',
3112
+ payload: { enabled: true },
3113
+ })
3114
+ if (seeded % 10 === 0)
3115
+ await store.append(slug, {
3116
+ actor: KERNEL,
3117
+ type: 'observation.recorded',
3118
+ payload: { id: `obs-${seeded}`, kind: 'followup', summary: `budget padding ${seeded}` },
3119
+ })
3120
+ }
3121
+ // Warm up: a fresh dispatcher folds the padding once while nothing fails.
3122
+ opts.failing(false)
3123
+ await opts.tick()
3124
+ opts.failing(true)
3125
+ const before = await escalations()
3126
+ const counter = memoryStoreRequestCounter(store)
3127
+ const vectors: Partial<Vectors> = {}
3128
+ try {
3129
+ const measure = async () => {
3130
+ counter.reset()
3131
+ await opts.tick()
3132
+ return counter.vector()
3133
+ }
3134
+ const due = async () => {
3135
+ const { state } = (await readBuildFacts(store, slug)).value
3136
+ const next = state.janitor && Date.parse(state.janitor.nextAttemptAt)
3137
+ if (next) opts.advance(Math.max(0, next - opts.now().getTime()))
3138
+ return state.janitor ? Date.parse(state.janitor.firstFailureAt) : undefined
3139
+ }
3140
+ vectors.start = await measure()
3141
+ const first = (await due())!
3142
+ vectors.preAttention = await measure()
3143
+ for (;;) {
3144
+ await due()
3145
+ const age = opts.now().getTime() - first
3146
+ const vector = await measure()
3147
+ if (age >= opts.limitSeconds * 1000) {
3148
+ vectors.threshold = vector
3149
+ break
3150
+ }
3151
+ if (age >= opts.attentionSeconds * 1000 && !vectors.attention) vectors.attention = vector
3152
+ else if (vectors.attention) vectors.preLimit = vector
3153
+ }
3154
+ await due()
3155
+ vectors.escalated = await measure()
3156
+ opts.failing(false)
3157
+ await due()
3158
+ vectors.recovery = await measure()
3159
+ } finally {
3160
+ counter.restore()
3161
+ }
3162
+ expect((await readBuildFacts(store, slug)).value.state.janitor).toBeUndefined()
3163
+ results.push({
3164
+ length,
3165
+ vectors: vectors as Vectors,
3166
+ escalations: (await escalations()) - before,
3167
+ })
3168
+ }
3169
+ expect(results[1]!.vectors).toEqual(results[0]!.vectors)
3170
+ return { vectors: results[0]!.vectors, escalations: results.map((r) => r.escalations) }
3171
+ }
3172
+
3173
+ /** AUT-1152: a prepared hosted guest re-reads its execution authority at its
3174
+ * durable boundaries. Proves the probe is one constant-size served value:
3175
+ * after the one-time reduction per key, an unchanged re-read issues the same
3176
+ * single request and reads zero event rows, and its response is the same size
3177
+ * whether the repository has had one harvest execution or a thousand; one new
3178
+ * fact costs exactly one row. */
3179
+ export async function hostedHarvestAuthorityReadBudget() {
3180
+ const { MemoryBuildStore } = await import('../store/memory')
3181
+ const repo = '/repo'
3182
+ const guest = { execution: 'guest', run: 'h_guest', leaseHolder: 'inv-1' }
3183
+ const sizes = [
3184
+ { cycles: 1, filler: 100 },
3185
+ { cycles: 1_000, filler: 10_000 },
3186
+ ]
3187
+ const results: Array<{
3188
+ warmRows: number
3189
+ unchanged: { vector: Record<string, number>; rows: number; size: number }
3190
+ appended: { rows: number; size: number }
3191
+ replaced: { rows: number; decision: ReturnType<typeof decideHostedHarvestAuthority> }
3192
+ }> = []
3193
+ for (const { cycles, filler } of sizes) {
3194
+ const store = new MemoryBuildStore()
3195
+ await seedPreparationHistory(store, repo, filler)
3196
+ for (let i = 0; i < cycles; i++) {
3197
+ const run = `h_old_${i}`
3198
+ const execution = `old-${i}`
3199
+ await store.appendRepo(repo, {
3200
+ actor: KERNEL,
3201
+ type: 'harvest.started',
3202
+ payload: {
3203
+ run,
3204
+ observations: [{ build: `b-${i}`, seq: 1 }],
3205
+ scan: { kind: 'harvest-scan', rev: i },
3206
+ },
3207
+ })
3208
+ await store.appendRepo(repo, {
3209
+ actor: DISPATCHER,
3210
+ type: 'harvest.execution.authorized',
3211
+ payload: { execution, run, launch: 'started', leaseHolder: `inv-old-${i}` },
3212
+ })
3213
+ await store.appendRepo(repo, {
3214
+ actor: DISPATCHER,
3215
+ type: 'harvest.execution.started',
3216
+ payload: { execution, provider: 'p', environmentId: `env-${i}` },
3217
+ })
3218
+ await store.appendRepo(repo, {
3219
+ actor: DISPATCHER,
3220
+ type: 'harvest.execution.released',
3221
+ payload: { execution, environmentId: `env-${i}`, snapshots: { outcome: 'confirmed' } },
3222
+ })
3223
+ }
3224
+ await store.appendRepo(repo, {
3225
+ actor: DISPATCHER,
3226
+ type: 'harvest.execution.authorized',
3227
+ payload: { ...guest, launch: 'started' },
3228
+ })
3229
+ const rows = memoryRepositoryReadCounter(store, repo)
3230
+ const requests = memoryStoreRequestCounter(store)
3231
+ try {
3232
+ const probe = async () => {
3233
+ rows.reset()
3234
+ requests.reset()
3235
+ const { value } = await readHostedHarvestAuthority(store, repo)
3236
+ return {
3237
+ vector: requests.vector(),
3238
+ rows: rows.rows,
3239
+ size: JSON.stringify(value).length,
3240
+ decision: decideHostedHarvestAuthority(value, guest),
3241
+ }
3242
+ }
3243
+ // The one-time reduction of this (repo, reducer) key.
3244
+ const warm = await probe()
3245
+ const unchanged = await probe()
3246
+ expect(unchanged.decision).toEqual({ kind: 'authorized' })
3247
+ await store.appendRepo(repo, {
3248
+ actor: humanActor('budget'),
3249
+ type: 'dispatcher.intake-set',
3250
+ payload: { enabled: true },
3251
+ })
3252
+ const appended = await probe()
3253
+ expect(appended.decision).toEqual({ kind: 'authorized' })
3254
+ await store.appendRepo(repo, {
3255
+ actor: DISPATCHER,
3256
+ type: 'harvest.execution.authorized',
3257
+ payload: {
3258
+ execution: 'successor',
3259
+ run: guest.run,
3260
+ launch: 'resumed',
3261
+ leaseHolder: 'inv-2',
3262
+ },
3263
+ })
3264
+ const replaced = await probe()
3265
+ results.push({
3266
+ warmRows: warm.rows,
3267
+ unchanged: { vector: unchanged.vector, rows: unchanged.rows, size: unchanged.size },
3268
+ appended: { rows: appended.rows, size: appended.size },
3269
+ replaced: { rows: replaced.rows, decision: replaced.decision },
3270
+ })
3271
+ } finally {
3272
+ requests.restore()
3273
+ }
3274
+ }
3275
+ const [small, large] = results as [(typeof results)[0], (typeof results)[0]]
3276
+ for (const result of results) {
3277
+ expect(result.unchanged.vector).toEqual({ getReducerValue: 1 })
3278
+ expect(result.unchanged.rows).toBe(0)
3279
+ expect(result.appended.rows).toBe(1)
3280
+ expect(result.replaced.rows).toBe(1)
3281
+ expect(result.replaced.decision).toEqual({ kind: 'fenced', reason: 'replaced' })
3282
+ }
3283
+ expect(large.unchanged.size).toBe(small.unchanged.size)
3284
+ expect(large.appended.size).toBe(small.appended.size)
3285
+ return { small, large }
3286
+ }
@@ -83,15 +83,20 @@ spec → plan ⇄ plan-review → implement ⇄ code-review → verify:* → fin
83
83
  gate — urgent tickets first, then normal ones, each in the source's order —
84
84
  chooses a short immutable slug from the final conforming spec, and
85
85
  starts builds up to the top-level `capacity` bound, after slots reserved for
86
- integration nodes awaiting verification or reconcile. Priority never preempts
87
- a running build.
86
+ integration nodes awaiting verification or reconcile and for finished builds
87
+ waiting to re-verify or reconcile. `capacity` counts builds running work: a
88
+ build that finished its pipeline holds no slot while it waits for a merge
89
+ decision, though it keeps its workspace until it merges or closes. Priority
90
+ never preempts a running build.
88
91
  - **Failed preparation.** Durable preparation facts protect the claim-to-build
89
92
  interval. Caught failures return tickets to Ready (invalid specs to Triage),
90
93
  after exact build-ownership readback. Unresolved attempts stay withheld and
91
94
  retry before intake, even at full capacity or with intake disabled. Unsafe
92
95
  ownership or externally changed/missing tickets end automatic recovery with
93
96
  a diagnostic `abandoned` resolution, reported once in that tick's dispatcher
94
- diagnostics, leaving the ticket unchanged. See
97
+ diagnostics and once as default `ab watch` repository attention, leaving the
98
+ ticket unchanged. The resolution records whether the claim was confirmed; an
99
+ unconfirmed claim's provider outcome is unknown. See
95
100
  [Ticket preparation recovery](references/restacking.md#ticket-preparation-before-build-creation).
96
101
  - **Ticket assets** — files or folders attached to a ticket (see
97
102
  [Ticket assets](#ticket-assets)) are frozen into the build at claim and
@@ -488,7 +493,7 @@ under the preceding table.
488
493
  |---|---|---|---|
489
494
  | `baseBranch` | `"main"` | nonempty string | The branch builds branch from and target with their PR; what `reconcile` replays the build change onto. |
490
495
  | `ticketScanIntervalSeconds` | `60` | positive integer seconds | Hot-reloaded ready scan cadence; tick spacing is the floor, and same-repository merge/completion/abort forces an early scan. |
491
- | `capacity` | `1` | positive integer | Maximum concurrent builds for this repository. |
496
+ | `capacity` | `1` | positive integer | Maximum builds running work at once for this repository; builds parked for a merge decision hold no slot. |
492
497
  | `forge` | `"github"` | nonblank string | Selects shipped `github` or `local-git`, or a plugin-registered Forge adapter. `github` authenticates with `GITHUB_TOKEN`, then `GH_TOKEN`, then the gh CLI's stored login. |
493
498
  | `plugins` | `[]` | array of unique nonblank module specifiers | Trusted Bun plugin modules loaded before dispatch, `ab ticket`, and scoped phase wiring. |
494
499
 
@@ -933,7 +938,9 @@ non-destructive execution fence for the exact workspace and execution generation
933
938
  It preserves unpublished branch commits and distinct detached producer candidates
934
939
  under immutable `refs/autobuild/archive/<build>/<sha>` refs, verifies their exact
935
940
  readback, and records `workspace.commits-preserved` before cleanup. Replacement
936
- provisioning restores those exact refs before starting an agent. A preserved
941
+ provisioning restores those exact refs before starting an agent, reading them
942
+ from the local repository with the local-git forge and fetching each exact ref
943
+ from the remote otherwise. A preserved
937
944
  branch head that the build's latest 64 replaced heads cover, as the replaced
938
945
  head itself or one of its ancestors, is kept only as archived objects: it is
939
946
  never preserved or restored as the branch, and provisioning records the skip as
@@ -1215,6 +1222,8 @@ nonnegative integer so zero can disable that trigger.
1215
1222
  | Field | Default | Allowed / constraints | Effect |
1216
1223
  |---|---|---|---|
1217
1224
  | `upgradeDrainSeconds` | `900` | positive integer | Local generation drain deadline from handoff start; hot-reloaded while draining. |
1225
+ | `dispatchLeaseTimeoutSeconds` | `60` | positive integer, greater than `dispatchLeaseRenewalSeconds` | How long the repository dispatch lease survives without renewal. A dispatcher that stalls longer reclaims it on waking unless another dispatcher took it, in which case it stops as `superseded`; a standby takes over a dead holder within this bound. Adopted at the dispatcher's next tick. |
1226
+ | `dispatchLeaseRenewalSeconds` | `20` | positive integer, less than `dispatchLeaseTimeoutSeconds` | Interval between repository dispatch lease renewals; adopted together with the timeout. Configuration with renewal at or above the timeout is refused when it loads. |
1218
1227
  | `sessionBudgetSeconds` | `3600` | positive integer | Active-time bound for each build agent session unless its logical role overrides it; native continuation retains accumulated time and excludes suspension. |
1219
1228
  | `stallRounds` | `3` | positive integer | The same finding surviving this many review rounds auto-escalates for external judgment — the anti-loop guard. |
1220
1229
  | `maxVerifyAttempts` | `3` | positive integer | Caps distinct failed verify cycles since the latest spec revision; passed and skipped cycles cost zero. |
@@ -1225,6 +1234,7 @@ nonnegative integer so zero can disable that trigger.
1225
1234
  | `maxReviewRounds` | `6` | positive integer | Default `maxRounds` for the `plan ⇄ plan-review` and `implement ⇄ code-review` convergence loops. When that cap parks a build, `ab answer <slug> --review-round-ceiling <n>` may replace it for only the escalation's loop and current spec revision. |
1226
1235
  | `harvestThreshold` | `5` | positive integer | Newly unclaimed `observation.recorded` occurrences required to start one repository harvest run. |
1227
1236
  | `janitorFailureAttentionSeconds` | `600` | positive integer | Consecutive janitor failure duration before build attention. |
1237
+ | `janitorFailureEscalationSeconds` | `3600` | positive integer | Consecutive janitor failure duration before the build raises one escalation; the janitor keeps retrying. |
1228
1238
  | `nodeIdleAfterSeconds` | `600` | positive integer | Quiet period before opened integration nodes enter idle polling. |
1229
1239
  | `nodeIdlePollSeconds` | `120` | positive integer | Interval between idle node checks; durable activity wakes the next tick. |
1230
1240
  | `janitorBackoffMaxSeconds` | `300` | positive integer | Cap on exponential janitor retry delay, starting at 30 seconds. |
@@ -2101,6 +2111,8 @@ restack state and conflicting files remain in detail, along with every child's
2101
2111
  ticket id, title and live phase (or queued/merged), open-first counts, verification
2102
2112
  steps and current outcomes, repair instructions, and the merge rule. Cancelled
2103
2113
  children are omitted; historical missing titles or filenames are explicit.
2114
+ A work build that finished its pipeline and must re-verify or reconcile shows
2115
+ the same slot-wait alert on its row, and `ab builds` appends it to the phase.
2104
2116
 
2105
2117
 
2106
2118
  On a TTY, execution-mode `ab dispatch` renders one fixed interactive frame that fills the
@@ -2127,8 +2139,8 @@ the configured source's bounded state count itself, at most once per 60 s
2127
2139
  while it runs. It keeps its last good value through failed reads and through
2128
2140
  headless ticks that publish no count, and shows `–` until its first read
2129
2141
  succeeds or when the source has no state counts (Linear). `queue` is the
2130
- ready-ticket queue depth, and `active` is the current nonterminal-build count
2131
- against root `capacity`. Observation pressure is not a header counter: the
2142
+ ready-ticket queue depth, and `active` is occupied capacity (every unfinished
2143
+ build, plus finished builds running work again) against root `capacity`. Observation pressure is not a header counter: the
2132
2144
  Harvest row shows a run's observations, and `ab harvest status` reports
2133
2145
  Harvest state.
2134
2146
  The execution-mode frontend checkpoints dashboard facts, the latest run start and the sampled
@@ -2462,8 +2474,9 @@ Every command requires an applicable target in this repository. Pause and
2462
2474
  resume require an active build; abort and hold also accept queued builds.
2463
2475
  Merge requires a ready candidate and cannot bypass verification or merge gates;
2464
2476
  a merge that is not ready is refused with code `merge-not-ready` (or
2465
- `node-incomplete` for an incomplete node) and a reason, and records nothing;
2466
- `ab answer` requires an open escalation except for eligible node spec revisions. A stale, missing, done,
2477
+ `node-incomplete` for an incomplete node) and a reason. A refusal records no
2478
+ merge consent and no landing; a node's live completeness check may still save
2479
+ an `integration.observed` diagnostic before it refuses. `ab answer` requires an open escalation except for eligible node spec revisions. A stale, missing, done,
2467
2480
  aborted, or otherwise inapplicable target is an error and gets no new event. Attribution uses `USER`, then `USERNAME`, then the
2468
2481
  same stable fallback on both surfaces. These commands run sessionless and
2469
2482
  accept `--store <ref>` with the usual explicit flag > `AB_STORE` > `[store] url` > repository
@@ -2477,10 +2490,12 @@ is inside the walk.
2477
2490
  These commands request normal kernel work; they do not wake a runner, operate
2478
2491
  the forge, or bypass the lease sweep. Resume is therefore an attempt, not a
2479
2492
  guarantee: if the condition still fails, a phase may raise a new escalation and
2480
- block again. Every open escalation, including all policy and setup causes,
2493
+ block again. Every open phase and policy escalation, including all setup causes,
2481
2494
  survives `ab dispatch` and `ab dispatch --once` startup until your operator agent or you
2482
- answer it. Startup still recovers actionable builds and delivers pending operator
2483
- commands, but it never records an answer or re-arms a budget.
2495
+ answer it. A janitor escalation is the exception: ordinary janitor retries continue
2496
+ across startup, a successful attempt closes it unanswered, and a bare retry only
2497
+ brings the next attempt forward. Startup still recovers actionable builds and
2498
+ delivers pending operator commands, but it never records an answer or re-arms a budget.
2484
2499
 
2485
2500
  Durable repository intake has launch-flag setters and a global-row toggle.
2486
2501
  Merge policy is configured through ordered rules, with per-merge hold/merge
@@ -2642,10 +2657,13 @@ The default watch reports actionable conditions only:
2642
2657
  - `integration.verification-failed`: failed node verification, once per prepared cycle, with failed steps, verified head and parent, and guidance to file a repair child targeting the node. Recovery reports only the latest prepared cycle while its head and parent remain current; superseded failures are not backfilled.
2643
2658
 
2644
2659
  - `build.janitor-failing`: a build has failed janitor attempts for the configured attention threshold. A successful attempt clears it.
2660
+ - `build.janitor-escalated`: a build's janitor failure episode outlasted the escalation threshold and raised one escalation. The janitor keeps retrying; a successful attempt closes it unanswered, and a bare retry answer attempts on the next tick.
2645
2661
  - `dispatcher.forge-persistent`: forge degradation remains after a post-reset retry tick; recovery clears the episode.
2646
2662
 
2647
2663
  - Build `escalation.raised` or `phase.deferral-escalated`: an operator answer
2648
2664
  is required. A read deferral asks for CLI/store repair before retry or guidance.
2665
+ A `build.janitor-escalated` escalation needs no answer to recover; a bare
2666
+ retry answer only brings the next attempt forward.
2649
2667
  - Build `build.merge-decision`: a finalized open PR
2650
2668
  with a recorded consent decision awaiting consent, an explicit hold, or a
2651
2669
  current actionable merge-gate deferral. Policy decisions not yet recorded and
@@ -2654,6 +2672,13 @@ The default watch reports actionable conditions only:
2654
2672
  `dispatcher.config-rejected`, `dispatcher.config-reloaded` with nonempty
2655
2673
  `restartRequired`, `dispatcher.upgrade-failed`, `dispatcher.runtime-rolled-back`,
2656
2674
  `dispatcher.kernel-git-unavailable`, abnormal `dispatcher.run-stopped`, and `dispatcher.lost`.
2675
+ - Repository `ticket-preparation.resolved` with outcome `abandoned`: automatic
2676
+ preparation recovery stopped and left the ticket unchanged. The line names the
2677
+ ticket, attempt and recorded reason; the payload's `claimed` says whether the
2678
+ claim was confirmed. An unconfirmed claim's provider outcome is unknown, and
2679
+ events written before `claimed` existed report the certainty as not recorded.
2680
+ Each abandonment reports once as it lands; a fresh watch does not replay
2681
+ historical ones, and nothing clears or acknowledges it.
2657
2682
  - `dispatcher.ticket-source-persistent`: degradation past its advertised
2658
2683
  reset time, once a tick started at or after reset has completed or failed
2659
2684
  with the episode still open; crossing reset alone is silent. Without a reset,
@@ -3093,11 +3118,22 @@ errors retain their existing behavior.
3093
3118
  Janitor failures are durable per-build episodes. Eligible failures retry after
3094
3119
  30, 60, 120, 240 seconds, then at the configured cap (300 seconds by default).
3095
3120
  A classified forge rate limit is repository cooldown, not a janitor failure:
3096
- neither the first limited response nor the cooldown that follows starts or ages
3097
- an episode. Skipped polls preserve the episode across restart. After
3098
- `policy.janitorFailureAttentionSeconds` (600 by default), `build.janitor-failing`
3099
- notifies default watchers and appears on the build row. A successful attempt
3100
- clears it. `policy.janitorBackoffMaxSeconds` sets the positive integer cap.
3121
+ neither the first limited response nor the cooldown that follows starts an
3122
+ episode or records an attempt, so a build that only waits out cooldown never
3123
+ escalates. Skipped polls preserve the episode across restart. Both thresholds
3124
+ below are wall-clock from the episode's first failed attempt and are checked
3125
+ when an attempt fails, so cooldown inside an episode that already started still
3126
+ counts. After `policy.janitorFailureAttentionSeconds` (600 by default),
3127
+ `build.janitor-failing` notifies default watchers and appears on the build row.
3128
+ After `policy.janitorFailureEscalationSeconds` (3600 by default), the build
3129
+ raises one escalation through `build.janitor-escalated`, naming the failing
3130
+ operation, the last error, the failed attempt count and when the episode
3131
+ started. The build is then blocked and shows wherever open escalations show.
3132
+ The janitor keeps retrying on its backoff underneath; a successful attempt
3133
+ clears the attention, closes the escalation unanswered and the build continues.
3134
+ Answering it with a bare retry makes the janitor attempt on its next tick. An
3135
+ episode raises at most one escalation; a new episode after recovery can raise
3136
+ another. `policy.janitorBackoffMaxSeconds` sets the positive integer cap.
3101
3137
  A dispatcher that cannot execute Git for kernel node work (a missing or
3102
3138
  unloadable `git` for the bare clone) records no janitor failures. It records
3103
3139
  one durable `dispatcher.kernel-git-unavailable` repository condition, node work
@@ -268,6 +268,9 @@ expiry. Successor loss and upgrade-failure/rollback attention remain independent
268
268
  `observation` instead of `event`, with run, observedAt, leaseExpiresAt and available
269
269
  identity, plus the usual repo/build/state/cursor fields. It invents no durable
270
270
  sequence or actor. Retain the cursor to avoid repeat reports across invocations.
271
+ A loss can be transient: a holder that stalled past
272
+ `policy.dispatchLeaseTimeoutSeconds` with no successor reclaims its lease on
273
+ waking and returns to `held`.
271
274
  A watch retains sampled owners after authoritative lease release. Once-run teardown
272
275
  stops heartbeat and releases only its own lease; release is best effort because
273
276
  expiry fences ambiguous ownership. A retained sample or failed release cannot
@@ -282,6 +285,7 @@ The default watch reports actionable conditions only:
282
285
  - `integration.verification-failed`: failed node verification, once per prepared cycle, with failed steps, verified head and parent, and guidance to file a repair child targeting the node. Recovery reports only the latest prepared cycle while its head and parent remain current; superseded failures are not backfilled.
283
286
 
284
287
  - `build.janitor-failing`: a build has reached the configured consecutive-failure threshold; a successful janitor attempt clears it.
288
+ - `build.janitor-escalated`: a build's janitor failure episode outlasted `policy.janitorFailureEscalationSeconds` and raised one escalation naming the operation, last error, attempt count and episode start. The janitor keeps retrying; a successful attempt closes the escalation, and a bare retry answer attempts on the next tick.
285
289
  - `dispatcher.forge-persistent`: forge degradation remains after a completed post-reset retry opportunity; successful recovery clears it.
286
290
 
287
291
  - Build `escalation.raised`, `integration.landed`, `node.item-conflicted`, `target.rewritten`, or
@@ -295,6 +299,13 @@ The default watch reports actionable conditions only:
295
299
  `dispatcher.config-rejected`, `dispatcher.config-reloaded` with nonempty
296
300
  `restartRequired`, `dispatcher.upgrade-failed`, `dispatcher.runtime-rolled-back`,
297
301
  `dispatcher.kernel-git-unavailable`, abnormal `dispatcher.run-stopped`, and `dispatcher.lost`.
302
+ - Repository `ticket-preparation.resolved` with outcome `abandoned`: automatic
303
+ preparation recovery stopped and left the ticket unchanged. The line names the
304
+ ticket, attempt and recorded reason; the payload's `claimed` says whether the
305
+ claim was confirmed. An unconfirmed claim's provider outcome is unknown, and
306
+ events written before `claimed` existed report the certainty as not recorded.
307
+ Each abandonment reports once as it lands; a fresh watch does not replay
308
+ historical ones, and nothing clears or acknowledges it.
298
309
  - `dispatcher.ticket-source-persistent`: degradation past its advertised
299
310
  reset time, once a tick started at or after reset has completed or failed
300
311
  with the episode still open; crossing reset alone is silent. Without a reset,
@@ -377,10 +388,11 @@ HTTP merge controls retain the wire actions `land` and `hold` with acknowledged
377
388
  requires readiness and survives restacks; hold persists until merge. Repository
378
389
  auto-merge settings are retired; configure ordered `[[merge]]` rules.
379
390
 
380
- Default attention includes `build.janitor-failing` and
391
+ Default attention includes `build.janitor-failing`, `build.janitor-escalated` and
381
392
  `dispatcher.forge-persistent`. Raw `dispatcher.forge-degraded` and
382
393
  `dispatcher.forge-recovered` facts are available through explicit event filters.
383
- Active janitor attention clears on a successful attempt. Repository status
394
+ Active janitor attention and an open janitor escalation clear on a successful
395
+ attempt. Repository status
384
396
  includes forge degradation/reset and available request counts; `dispatcher.forge-persistent` requires a completed retry opportunity past
385
397
  the original reset, which later rate limits cannot postpone indefinitely.
386
398
 
@@ -120,6 +120,10 @@ confirmed, absent, or unknown without deleting an environment or its snapshots.
120
120
  Only dispatcher-authorized reap follows the durable fence and preservation/loss
121
121
  receipt. `provision` accepts exact `restoration` heads; branch ancestry must be
122
122
  verified, and detached producer objects must never overwrite the named branch.
123
+ `provision` also receives `restorationArchives`: `local` for the local-git
124
+ forge, whose repository already holds the archive refs and must not be fetched
125
+ from, and `remote` otherwise, in which case a provider sharing the repository
126
+ must fetch each exact archive ref from origin before verifying it.
123
127
  `preserve` receives `replaced`, and `provision` receives `restorationReplaced`:
124
128
  the build's bounded record of the latest 64 shas recorded rewrites replaced.
125
129
  A branch head equal to or contained in one of them is superseded. Preserve