@defrex/autobuild 1.12.0 → 1.13.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 (159) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +435 -160
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +25 -3
  5. package/docs/architecture.md +124 -53
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +110 -15
  8. package/docs/dispatcher.md +19 -8
  9. package/docs/integration-overview.md +1 -1
  10. package/docs/integration-tree.md +12 -9
  11. package/docs/merge-policy.md +7 -2
  12. package/docs/operating.md +5 -3
  13. package/docs/operator-api.md +46 -23
  14. package/docs/operator-surfaces.md +7 -6
  15. package/docs/optimization-nodes.md +7 -6
  16. package/docs/plugin-authoring.md +46 -18
  17. package/docs/remote-store-protocol.md +51 -12
  18. package/docs/remote-ticket-protocol.md +85 -38
  19. package/docs/restacking.md +48 -3
  20. package/docs/setup.md +2 -1
  21. package/docs/ticket-migration.md +2 -2
  22. package/docs/ticket-sources.md +23 -8
  23. package/docs/tickets.md +4 -4
  24. package/docs/troubleshooting.md +17 -2
  25. package/docs/verification.md +3 -1
  26. package/package.json +3 -3
  27. package/packages/core/src/cli/build-control.ts +72 -6
  28. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  29. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  30. package/packages/core/src/cli/dashboard/model.ts +14 -8
  31. package/packages/core/src/cli/dashboard/poll.ts +218 -10
  32. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  33. package/packages/core/src/cli/dashboard/row-text.ts +2 -1
  34. package/packages/core/src/cli/dashboard/vocabulary.ts +5 -1
  35. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  36. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  37. package/packages/core/src/cli/dispatch.ts +527 -144
  38. package/packages/core/src/cli/help.ts +38 -24
  39. package/packages/core/src/cli/main.ts +7 -5
  40. package/packages/core/src/cli/publication-settlement.ts +4 -0
  41. package/packages/core/src/cli/remote-poll.ts +22 -5
  42. package/packages/core/src/cli/repository-status.ts +19 -9
  43. package/packages/core/src/cli/status.ts +23 -11
  44. package/packages/core/src/cli/store-opening.ts +12 -0
  45. package/packages/core/src/cli/ticket-start.ts +3 -3
  46. package/packages/core/src/cli/ticket.ts +12 -11
  47. package/packages/core/src/cli/wait.ts +8 -28
  48. package/packages/core/src/cli/watch.ts +113 -50
  49. package/packages/core/src/config/reference-metadata.ts +7 -1
  50. package/packages/core/src/config/reference.ts +5 -2
  51. package/packages/core/src/config/schema.ts +51 -16
  52. package/packages/core/src/events/payloads.ts +74 -14
  53. package/packages/core/src/events/repository.ts +14 -3
  54. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +27 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  61. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  62. package/packages/core/src/kernel/dispatch-capacity.ts +243 -107
  63. package/packages/core/src/kernel/done-escalations.ts +269 -0
  64. package/packages/core/src/kernel/engine.ts +28 -9
  65. package/packages/core/src/kernel/integration-landing.ts +24 -4
  66. package/packages/core/src/kernel/integration-stack.ts +39 -0
  67. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  68. package/packages/core/src/kernel/log-index-value.ts +3 -0
  69. package/packages/core/src/kernel/log-index.ts +41 -2
  70. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  71. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  72. package/packages/core/src/kernel/reducer-revisions.ts +15 -0
  73. package/packages/core/src/kernel/reducer.ts +27 -7
  74. package/packages/core/src/kernel/repository-attention.ts +14 -5
  75. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  76. package/packages/core/src/kernel/verify-stages.ts +46 -7
  77. package/packages/core/src/operator/attention.ts +28 -3
  78. package/packages/core/src/operator/done-escalations.ts +38 -0
  79. package/packages/core/src/operator/presentation.ts +1 -1
  80. package/packages/core/src/operator/protocol.ts +8 -5
  81. package/packages/core/src/operator/query.ts +33 -19
  82. package/packages/core/src/operator/registry.ts +17 -13
  83. package/packages/core/src/operator/ticket-start.ts +8 -7
  84. package/packages/core/src/operator/tickets.ts +28 -9
  85. package/packages/core/src/plugin-sdk/index.ts +10 -0
  86. package/packages/core/src/plugins/manifest.ts +14 -1
  87. package/packages/core/src/ports/forge/create.ts +8 -0
  88. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  89. package/packages/core/src/ports/forge/github.ts +3 -0
  90. package/packages/core/src/ports/tickets/contract.ts +147 -76
  91. package/packages/core/src/ports/tickets/create.ts +47 -7
  92. package/packages/core/src/ports/tickets/fake.ts +8 -4
  93. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  94. package/packages/core/src/ports/tickets/file.ts +7 -3
  95. package/packages/core/src/ports/tickets/github.ts +1 -0
  96. package/packages/core/src/ports/tickets/grants.ts +11 -3
  97. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  98. package/packages/core/src/ports/tickets/linear.ts +28 -9
  99. package/packages/core/src/ports/tickets/migration.ts +4 -4
  100. package/packages/core/src/ports/tickets/operations.ts +4 -2
  101. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  102. package/packages/core/src/ports/tickets/priority.ts +127 -21
  103. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  104. package/packages/core/src/ports/tickets/remote.ts +104 -11
  105. package/packages/core/src/ports/tickets/revision.ts +5 -3
  106. package/packages/core/src/ports/tickets/search.ts +9 -0
  107. package/packages/core/src/ports/tickets/tree.ts +8 -6
  108. package/packages/core/src/ports/types.ts +30 -15
  109. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  110. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  111. package/packages/core/src/ports/workspace/create.ts +16 -3
  112. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  113. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  114. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  115. package/packages/core/src/processes/build-execution-state.ts +4 -0
  116. package/packages/core/src/processes/build-runner.ts +14 -1
  117. package/packages/core/src/processes/dispatcher.ts +544 -212
  118. package/packages/core/src/processes/execution-settlement.ts +1 -0
  119. package/packages/core/src/processes/harvest-runner.ts +12 -7
  120. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  121. package/packages/core/src/processes/invocation-budget.ts +176 -0
  122. package/packages/core/src/processes/publication-loss.ts +38 -3
  123. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  124. package/packages/core/src/store/contract.ts +81 -3
  125. package/packages/core/src/store/event-reads.ts +30 -1
  126. package/packages/core/src/store/reduced-reads.ts +23 -0
  127. package/packages/core/src/store/reducer-value-shapes.json +6628 -6469
  128. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  129. package/packages/core/src/store/remote/client.ts +169 -29
  130. package/packages/core/src/store/remote/compatibility.ts +113 -56
  131. package/packages/core/src/store/remote/credentials.ts +4 -1
  132. package/packages/core/src/store/remote/protocol.ts +3 -0
  133. package/packages/core/src/store/remote/released-clients.json +11 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  135. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  136. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  137. package/packages/core/src/store/remote/retry.ts +406 -0
  138. package/packages/core/src/testing/dispatch-read-budget.ts +144 -10
  139. package/packages/core/src/testing/index.ts +2 -0
  140. package/packages/core/src/testing/invocation-budget.ts +42 -0
  141. package/packages/core/src/testing/reduced-read-budget.ts +381 -18
  142. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  143. package/packages/core/src/web/overview-source.ts +19 -6
  144. package/skills/guide/SKILL.md +138 -67
  145. package/skills/guide/references/integration-tree.md +12 -9
  146. package/skills/guide/references/merge-policy.md +7 -2
  147. package/skills/guide/references/operator-api.md +46 -23
  148. package/skills/guide/references/optimization-nodes.md +7 -6
  149. package/skills/guide/references/plugin-authoring.md +46 -18
  150. package/skills/guide/references/remote-store-protocol.md +51 -12
  151. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  152. package/skills/guide/references/restacking.md +48 -3
  153. package/skills/guide/references/setup.md +2 -1
  154. package/skills/guide/references/ticket-migration.md +2 -2
  155. package/skills/operate/SKILL.md +82 -51
  156. package/skills/plan/SKILL.md +4 -3
  157. package/skills/spec/SKILL.md +9 -5
  158. package/skills/tickets/SKILL.md +25 -17
  159. package/templates/hosted-service/package.json +2 -2
@@ -1,3 +1,4 @@
1
+ import type { TicketPriority } from '../ports/types'
1
2
  import { upgradeGenerationWrites } from './upgrade-generations'
2
3
  import { restoreReplay } from '../kernel/replay-retention'
3
4
  import { reducerValueForClient } from '../store/remote/compatibility'
@@ -16,6 +17,7 @@ import { tmpdir } from 'node:os'
16
17
  import { join } from 'node:path'
17
18
  import { DashboardBuildPollCache } from '../cli/dashboard/poll'
18
19
  import { abDispatch } from '../cli/dispatch'
20
+ import { createInvocationBudget } from '../processes/invocation-budget'
19
21
  import { createTerminalModeController } from '../cli/terminal-restore'
20
22
  import { randomUuids } from '../ids'
21
23
  import { ScriptedAgentRunner, defaultTurnResult } from '../ports/runner/fake'
@@ -43,6 +45,7 @@ import {
43
45
  readDispatchBudget,
44
46
  readRepositoryFacts,
45
47
  readForgeHealth,
48
+ readDoneEscalations,
46
49
  readRepositoryAttention,
47
50
  readBuildDigests,
48
51
  readDispatcherRunFacts,
@@ -414,7 +417,9 @@ export async function reducedReadBudget(opts: {
414
417
  expect(costs.events).toBe(0)
415
418
  // A new dashboard on every invocation must use canonical persisted facts,
416
419
  // even after the build exceeds the hosted page cap. Warm and cold polls
417
- // select zero event rows at either history length.
420
+ // select zero event rows at either history length once the
421
+ // `doneEscalations` rollup has its one saved reduction.
422
+ await readDoneEscalations(store, repo)
418
423
  reset()
419
424
  for (let invocation = 0; invocation < 3; invocation++) {
420
425
  const dashboard = new DashboardBuildPollCache(cold, repo, config)
@@ -426,6 +431,7 @@ export async function reducedReadBudget(opts: {
426
431
  await coldDispatchOnceBudget(store, cold, length, costs)
427
432
  await coldDispatchOnceBudget(store, cold, length, costs, true)
428
433
  await coldDispatchOnceBudget(store, cold, length, costs, true, true)
434
+ await coldDispatchOnceBudget(store, cold, length, costs, false, false, true)
429
435
  reset()
430
436
  const view = new RepoViewStore(cold, { repo })
431
437
  await view.refresh()
@@ -1087,12 +1093,17 @@ async function coldDispatchOnceBudget(
1087
1093
  costs: ReducedReadCosts,
1088
1094
  interactive = false,
1089
1095
  outage = false,
1096
+ /** A bounded invocation whose work deadline passes during the tick's
1097
+ * first digest read: the stop adds no reads and still records the stop. */
1098
+ budgetStop = false,
1090
1099
  ) {
1091
1100
  const onceRepo = outage
1092
1101
  ? 'https://github.com/budget/outage-ticks'
1093
1102
  : interactive
1094
1103
  ? 'https://github.com/budget/interactive-ticks'
1095
- : 'https://github.com/budget/cold-once'
1104
+ : budgetStop
1105
+ ? 'https://github.com/budget/budget-stopped-once'
1106
+ : 'https://github.com/budget/cold-once'
1096
1107
  await store.ensureRepo(onceRepo)
1097
1108
  for (let i = 0; i < length; i++)
1098
1109
  await store.appendRepo(onceRepo, {
@@ -1118,6 +1129,18 @@ steps = []
1118
1129
  `,
1119
1130
  )
1120
1131
  const acquisitions = { facts: 0, digests: 0 }
1132
+ const deadlines: (() => void)[] = []
1133
+ const budget = budgetStop
1134
+ ? createInvocationBudget({
1135
+ workDeadlineAt: 1000 + 210_000,
1136
+ hardDeadlineAt: 1000 + 240_000,
1137
+ now: () => 1000,
1138
+ timers: {
1139
+ setTimeout: (handler) => deadlines.push(handler),
1140
+ clearTimeout: () => {},
1141
+ },
1142
+ })
1143
+ : undefined
1121
1144
  const stop = new AbortController()
1122
1145
  let ticks = 0
1123
1146
  let ticketScanWrites = 0
@@ -1179,6 +1202,12 @@ steps = []
1179
1202
  if (key === 'getRepoBuildDigests')
1180
1203
  return (...args: Parameters<BuildStore['getRepoBuildDigests']>) => {
1181
1204
  acquisitions.digests++
1205
+ if (budget !== undefined && acquisitions.digests === 1) {
1206
+ // The work deadline passes while this read is on the wire; the
1207
+ // budgeted fetch would reject it with the deadline.
1208
+ deadlines[0]!()
1209
+ return Promise.reject(budget.work.reason)
1210
+ }
1182
1211
  return target.getRepoBuildDigests(...args)
1183
1212
  }
1184
1213
  if (key === 'getReducerValue')
@@ -1250,6 +1279,7 @@ steps = []
1250
1279
  },
1251
1280
  kernelRunId: run,
1252
1281
  ...(interactive ? { frontendStatus: true } : {}),
1282
+ ...(budget !== undefined ? { invocationBudget: budget } : {}),
1253
1283
  storeRef: '/budget',
1254
1284
  wire: () => ({
1255
1285
  store: checked,
@@ -1278,9 +1308,12 @@ steps = []
1278
1308
  const finished = (await readRepositoryFacts(checked, onceRepo)).value.recentRuns.find(
1279
1309
  ([id]) => id === run,
1280
1310
  )?.[1]
1281
- expect(finished?.completed?.type).toBe('dispatcher.tick-completed')
1311
+ if (budget !== undefined) {
1312
+ expect(budget.work.aborted).toBe(true)
1313
+ expect(finished?.stop?.payload).toMatchObject({ outcome: 'normal', exitCode: 0 })
1314
+ } else expect(finished?.completed?.type).toBe('dispatcher.tick-completed')
1282
1315
  if (interactive) expect(finished?.completed?.payload).toMatchObject({ triage: 2 })
1283
- else expect(finished?.completed?.payload).not.toHaveProperty('triage')
1316
+ else if (budget === undefined) expect(finished?.completed?.payload).not.toHaveProperty('triage')
1284
1317
  expect(finished?.stop?.type).toBe('dispatcher.run-stopped')
1285
1318
  // The same fresh invocation may fail before writing its start fact.
1286
1319
  expect(
@@ -2841,12 +2874,40 @@ export function memoryRepositoryReadCounter(
2841
2874
  },
2842
2875
  })
2843
2876
  }
2877
+ let seedCalls = 0
2878
+ const reducedCallsBySlug = new Map<string, number>()
2879
+ const pageCallsBySlug = new Map<string, number>()
2880
+ const bump = (map: Map<string, number>, key: string) => map.set(key, (map.get(key) ?? 0) + 1)
2881
+ // Per-build digests served inside the repository's batch digest read are
2882
+ // the listing's cost, not a point read of that build.
2883
+ let inDigestBatch = 0
2884
+ const getRepoBuildDigests = store.getRepoBuildDigests.bind(store)
2885
+ store.getRepoBuildDigests = async (r) => {
2886
+ inDigestBatch++
2887
+ try {
2888
+ return await getRepoBuildDigests(r)
2889
+ } finally {
2890
+ inDigestBatch--
2891
+ }
2892
+ }
2844
2893
  const getReducerValue = store.getReducerValue.bind(store)
2845
2894
  store.getReducerValue = async (scope, request) => {
2846
2895
  reducedCalls++
2847
2896
  if (scope.kind === 'build' && request.reducer === 'buildReadFacts') buildFactsCalls++
2897
+ if (scope.kind === 'build' && request.reducer === 'buildStreamSeed') seedCalls++
2898
+ if (scope.kind === 'build' && inDigestBatch === 0) bump(reducedCallsBySlug, scope.slug)
2848
2899
  return getReducerValue(scope, request)
2849
2900
  }
2901
+ const getBuildEventPage = store.getBuildEventPage.bind(store)
2902
+ store.getBuildEventPage = async (build, since, opts) => {
2903
+ bump(pageCallsBySlug, build)
2904
+ return getBuildEventPage(build, since, opts)
2905
+ }
2906
+ const getEvents = store.getEvents.bind(store)
2907
+ store.getEvents = async (build, since, opts) => {
2908
+ bump(pageCallsBySlug, build)
2909
+ return getEvents(build, since, opts)
2910
+ }
2850
2911
  return {
2851
2912
  get rows() {
2852
2913
  return rows
@@ -2863,12 +2924,27 @@ export function memoryRepositoryReadCounter(
2863
2924
  get buildFactsCalls() {
2864
2925
  return buildFactsCalls
2865
2926
  },
2927
+ /** Build-scope `buildStreamSeed` reduced reads. */
2928
+ get seedCalls() {
2929
+ return seedCalls
2930
+ },
2931
+ /** Build-scope reduced reads per slug, outside the repository digest batch. */
2932
+ get reducedCallsBySlug() {
2933
+ return new Map(reducedCallsBySlug)
2934
+ },
2935
+ /** Event reads (`getBuildEventPage`, `getEvents`) per slug. */
2936
+ get pageCallsBySlug() {
2937
+ return new Map(pageCallsBySlug)
2938
+ },
2866
2939
  reset() {
2867
2940
  rows = 0
2868
2941
  buildRows = 0
2869
2942
  buildRowsBySlug.clear()
2870
2943
  reducedCalls = 0
2871
2944
  buildFactsCalls = 0
2945
+ seedCalls = 0
2946
+ reducedCallsBySlug.clear()
2947
+ pageCallsBySlug.clear()
2872
2948
  },
2873
2949
  }
2874
2950
  }
@@ -3567,6 +3643,201 @@ export async function cliWatchDiscoveryReadBudget() {
3567
3643
  expect(costs[1]).toEqual(costs[0]!)
3568
3644
  }
3569
3645
 
3646
+ /**
3647
+ * A re-armed `ab watch --since` over many settled builds (#1288). At 100 and
3648
+ * 100,000 journal and build events, 40 builds are tracked, then 38 finish
3649
+ * while no watch runs. Re-arming delivers each finished build's completion
3650
+ * exactly once and drops it from the cursor; afterwards a retired build costs
3651
+ * no read of any kind, and an idle active build costs one event read per
3652
+ * pass with no `buildStreamSeed` read — locally per tick, and remotely per
3653
+ * wait window, where a retired build never opens a held read and the seed
3654
+ * count does not grow with the number of windows.
3655
+ */
3656
+ export async function cliWatchSettledRetirementReadBudget() {
3657
+ const { MemoryBuildStore } = await import('../store/memory')
3658
+ const { manualClock } = await import('./fixed')
3659
+ const builds = Array.from({ length: 40 }, (_, i) => `b${String(i).padStart(2, '0')}`)
3660
+ const settled = builds.slice(0, 38)
3661
+ const [active, finishing] = builds.slice(38) as [string, string]
3662
+ const complete = (store: InstanceType<typeof MemoryBuildStore>, build: string) =>
3663
+ store.append(build, {
3664
+ actor: DISPATCHER,
3665
+ type: 'build.completed',
3666
+ payload: { outcome: 'merged' },
3667
+ })
3668
+ type Cost = { rows: number; buildRows: number; seedCalls: number; reducedCalls: number }
3669
+ const costs: Record<string, Cost>[] = []
3670
+ for (const length of [100, 100_000]) {
3671
+ const clock = manualClock()
3672
+ const store = new MemoryBuildStore({ clock })
3673
+ await store.ensureRepo(repo)
3674
+ await seedRepoFiller(store, repo, length)
3675
+ for (const build of builds) {
3676
+ await store.createBuild({ slug: build, repo })
3677
+ await store.append(build, {
3678
+ actor: KERNEL,
3679
+ type: 'runner.attached',
3680
+ payload: { instance: 'i1', host: 'h1', resumedFromSeq: 0 },
3681
+ })
3682
+ }
3683
+ await seedBuildFiller(store, settled[0]!, length)
3684
+ // Served values exist before the watch, as on any running repository.
3685
+ await readRepositoryFacts(store, repo)
3686
+ await readRepositoryAttention(store, repo)
3687
+ await readBuildDigests(store, repo)
3688
+ for (const build of builds) await readBuildStreamSeed(store, build)
3689
+ const output: string[] = []
3690
+ const watch = (opts: {
3691
+ store?: BuildStore
3692
+ storeRef?: string
3693
+ since?: string
3694
+ timeout?: string
3695
+ signal?: AbortSignal
3696
+ delay?: () => Promise<void>
3697
+ }) =>
3698
+ abWatch({
3699
+ targetRepo: repo,
3700
+ env: {},
3701
+ exec,
3702
+ storeRef: opts.storeRef ?? '/budget',
3703
+ openStore: () => opts.store ?? store,
3704
+ json: true,
3705
+ events: ['build.completed'],
3706
+ now: clock,
3707
+ stdout: (line) => output.push(line),
3708
+ stderr: (line) => {
3709
+ throw new Error(line)
3710
+ },
3711
+ delay: opts.delay ?? (async () => clock.advance(1000)),
3712
+ ...(opts.since !== undefined ? { since: opts.since } : {}),
3713
+ ...(opts.timeout !== undefined ? { timeout: opts.timeout } : {}),
3714
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
3715
+ })
3716
+ const lastCursor = () => (JSON.parse(output.at(-1)!) as { cursor: string }).cursor
3717
+ const delivered = () =>
3718
+ output
3719
+ .map((line) => JSON.parse(line) as { id?: string })
3720
+ .flatMap((record) => (record.id === undefined ? [] : [record.id]))
3721
+ const tracked = (cursor: string, storeRef = '/budget') =>
3722
+ Object.keys(decodeCursor(cursor, { store: storeRef, repo }).streams).toSorted()
3723
+
3724
+ await watch({ signal: AbortSignal.abort() })
3725
+ const armed = lastCursor()
3726
+ expect(tracked(armed)).toEqual(['#repo', ...builds].toSorted())
3727
+ for (const build of settled) await complete(store, build)
3728
+
3729
+ // ── Local re-arm: one sequential pass per tick ──
3730
+ const counter = memoryRepositoryReadCounter(store, repo)
3731
+ const sample: Record<string, Cost> = {}
3732
+ const retiredCosts: { pages: number; reduced: number }[] = []
3733
+ const cost = (): Cost => ({
3734
+ rows: counter.rows,
3735
+ buildRows: counter.buildRows,
3736
+ seedCalls: counter.seedCalls,
3737
+ reducedCalls: counter.reducedCalls,
3738
+ })
3739
+ const retiredReads = (retired: readonly string[]) => ({
3740
+ pages: retired.reduce((n, b) => n + (counter.pageCallsBySlug.get(b) ?? 0), 0),
3741
+ reduced: retired.reduce((n, b) => n + (counter.reducedCallsBySlug.get(b) ?? 0), 0),
3742
+ })
3743
+ let tick = 0
3744
+ output.length = 0
3745
+ await watch({
3746
+ since: armed,
3747
+ timeout: '6',
3748
+ delay: async () => {
3749
+ clock.advance(1000)
3750
+ tick++
3751
+ if (tick === 1) sample.attach = cost()
3752
+ if (tick >= 2)
3753
+ retiredCosts.push(retiredReads(tick >= 5 ? [...settled, finishing] : settled))
3754
+ if (tick === 2) sample.quiet = cost()
3755
+ if (tick === 3) {
3756
+ sample.quiet2 = cost()
3757
+ await complete(store, finishing)
3758
+ }
3759
+ if (tick === 4) sample.finishing = cost()
3760
+ if (tick === 5) sample.settled = cost()
3761
+ counter.reset()
3762
+ },
3763
+ })
3764
+ const ids = delivered()
3765
+ expect(ids.toSorted()).toEqual(
3766
+ [...settled, finishing].map((b) => `build:${b}:${b === settled[0] ? length + 1 : 2}`).sort(),
3767
+ )
3768
+ expect(new Set(ids).size).toBe(ids.length)
3769
+ const localFinal = lastCursor()
3770
+ expect(tracked(localFinal)).toEqual(['#repo', active])
3771
+ for (const key of ['quiet', 'quiet2', 'settled']) {
3772
+ expect(sample[key]!.rows).toBe(0)
3773
+ expect(sample[key]!.buildRows).toBe(0)
3774
+ expect(sample[key]!.seedCalls).toBe(0)
3775
+ }
3776
+ // The finishing build costs its one new row: read by its poll, and
3777
+ // folded once by the digest its retirement check advances.
3778
+ expect(sample.finishing!.buildRows).toBe(2)
3779
+ expect(sample.finishing!.seedCalls).toBe(0)
3780
+ for (const retired of retiredCosts) expect(retired).toEqual({ pages: 0, reduced: 0 })
3781
+
3782
+ // ── Remote re-arm: concurrent held reads per stream ──
3783
+ // The memory adapter holds on wall time; drop the hold so the injected
3784
+ // delay drives every window on the manual clock, recording held reads.
3785
+ const remoteRef = 'https://budget.example.test'
3786
+ const remote = async (timeout: string) => {
3787
+ const held = new Map<string, number>()
3788
+ const holding = new Proxy(store, {
3789
+ get(target, key) {
3790
+ const value = Reflect.get(target, key, target)
3791
+ if (typeof value !== 'function') return value
3792
+ if (!['getBuildEventPage', 'getEvents', 'getRepoEvents'].includes(key as string))
3793
+ return value.bind(target)
3794
+ return (build: string, since?: number, opts?: { waitSeconds?: number }) => {
3795
+ if ((opts?.waitSeconds ?? 0) > 0) held.set(build, (held.get(build) ?? 0) + 1)
3796
+ return value.call(target, build, since, { ...opts, waitSeconds: 0 })
3797
+ }
3798
+ },
3799
+ })
3800
+ counter.reset()
3801
+ output.length = 0
3802
+ await watch({
3803
+ store: holding,
3804
+ storeRef: remoteRef,
3805
+ since: encodeCursorFor(armed, remoteRef),
3806
+ timeout,
3807
+ })
3808
+ expect(tracked(lastCursor(), remoteRef)).toEqual(['#repo', active])
3809
+ return {
3810
+ held,
3811
+ seedCalls: counter.seedCalls,
3812
+ pages: counter.pageCallsBySlug,
3813
+ delivered: delivered().length,
3814
+ }
3815
+ }
3816
+ const short = await remote('8')
3817
+ const long = await remote('40')
3818
+ // The local run finished the last build too: 39 settled builds re-arm.
3819
+ for (const run of [short, long]) {
3820
+ expect(run.delivered).toBe(settled.length + 1)
3821
+ for (const build of [...settled, finishing]) {
3822
+ expect(run.pages.get(build)).toBe(1)
3823
+ expect(run.held.get(build)).toBeUndefined()
3824
+ }
3825
+ }
3826
+ expect(long.held.get(active)!).toBeGreaterThan(short.held.get(active)!)
3827
+ // Attach-time seed reads only: more windows add none.
3828
+ expect(long.seedCalls).toBe(short.seedCalls)
3829
+ costs.push(sample)
3830
+ }
3831
+ // History-independent: every pass costs the same at both lengths.
3832
+ expect(costs[1]).toEqual(costs[0]!)
3833
+ }
3834
+
3835
+ /** Re-issue a cursor's positions for another store reference. */
3836
+ function encodeCursorFor(cursor: string, storeRef: string): string {
3837
+ const payload = JSON.parse(Buffer.from(cursor.slice(3), 'base64url').toString('utf8'))
3838
+ return `v1.${Buffer.from(JSON.stringify({ ...payload, store: storeRef }), 'utf8').toString('base64url')}`
3839
+ }
3840
+
3570
3841
  /** Fresh operator backends must not turn canonical build history into ticket requests. */
3571
3842
  export async function operatorTicketAssociationBudget() {
3572
3843
  const { MemoryBuildStore } = await import('../store/memory')
@@ -4136,8 +4407,9 @@ export async function ticketRoleTickBudget(
4136
4407
  return baseline!
4137
4408
  }
4138
4409
 
4139
- /** Urgent intake order (AUT-1027) is an in-memory partition of the one ready
4140
- * listing a due scan already reads: with and without an urgent ticket present,
4410
+ /** Intake order by level (AUT-1027, #1354) is an in-memory sort of the one
4411
+ * ready listing a due scan already reads: whatever the levels of the ready
4412
+ * tickets (all normal, one urgent, high or low, or all four levels at once),
4141
4413
  * a quiet intake tick makes the same source calls and the same store reads, at
4142
4414
  * 100 and 100,000 repository events, and an unchanged follow-up read costs zero
4143
4415
  * rows. Returns the per-method source calls of one tick. */
@@ -4153,12 +4425,19 @@ export async function urgentIntakeReadBudget() {
4153
4425
  const methods = ['listReady', 'get', 'dependencyStates', 'listAll'] as const
4154
4426
  const results = new Map<string, { calls: Record<string, number>[]; rows: number[] }>()
4155
4427
  const profileResults = new Map<string, { calls: Record<string, number>[]; rows: number[] }>()
4156
- for (const [urgent, profiles] of [
4157
- [false, false],
4158
- [true, false],
4159
- [false, true],
4160
- [true, true],
4161
- ] as const) {
4428
+ // The levels of N1, N2 and U1 in each variant.
4429
+ type Levels = readonly [TicketPriority, TicketPriority, TicketPriority]
4430
+ const normal: Levels = ['normal', 'normal', 'normal']
4431
+ const variants: (readonly [string, Levels, boolean])[] = [
4432
+ ['normal', normal, false],
4433
+ ['urgent', ['normal', 'normal', 'urgent'], false],
4434
+ ['high', ['normal', 'normal', 'high'], false],
4435
+ ['low', ['normal', 'normal', 'low'], false],
4436
+ ['mixed', ['high', 'low', 'urgent'], false],
4437
+ ['normal', normal, true],
4438
+ ['urgent', ['normal', 'normal', 'urgent'], true],
4439
+ ]
4440
+ for (const [urgent, levels, profiles] of variants) {
4162
4441
  const config = parseConfig(profiles ? profiled : plain)
4163
4442
  for (const length of [100, 100_000]) {
4164
4443
  const source = new FakeTicketSource([], { createState: 'triage', doneState: 'done' })
@@ -4179,7 +4458,7 @@ export async function urgentIntakeReadBudget() {
4179
4458
  const ticket = await source.create({
4180
4459
  title,
4181
4460
  body: 'Budget',
4182
- ...(urgent && index === 2 ? { priority: 'urgent' as const } : {}),
4461
+ ...(levels[index] !== 'normal' ? { priority: levels[index] } : {}),
4183
4462
  ...(profiles
4184
4463
  ? { labels: index === 0 ? ['deep'] : index === 1 ? ['deep', 'cheap'] : [] }
4185
4464
  : {}),
@@ -5540,9 +5819,10 @@ export async function hookReadBudget(): Promise<void> {
5540
5819
  requests: requests.vector(),
5541
5820
  }
5542
5821
  expect(delivered.slice(deliveredBefore)).toHaveLength(2)
5543
- // Each new row is read once per hook, plus once by the shared reduced
5544
- // value's incremental advance.
5545
- expect(changed.bySlug).toEqual({ 'active-a': 3, 'new-c': 9 })
5822
+ // Each new row on a followed build is read once per hook: following a
5823
+ // tail reads no per-poll stream seed. An announced build also replays
5824
+ // from its seed.
5825
+ expect(changed.bySlug).toEqual({ 'active-a': 2, 'new-c': 9 })
5546
5826
  expect(listing(changed.requests)).toEqual([0, 0, 0])
5547
5827
  requests.restore()
5548
5828
 
@@ -7479,6 +7759,8 @@ export async function ticketStartReadBudget(): Promise<{
7479
7759
  label: string,
7480
7760
  /** AB-0 waits on a blocker whose dependency read fails. */
7481
7761
  blocked = false,
7762
+ /** Further ready tickets, as `[id, level]`. */
7763
+ extra: readonly (readonly [string, import('../ports/types').TicketPriority])[] = [],
7482
7764
  ) => {
7483
7765
  let now = 1_800_000_000_000
7484
7766
  const clock = () => new Date(now)
@@ -7506,6 +7788,10 @@ export async function ticketStartReadBudget(): Promise<{
7506
7788
  { ...ticket('AB-W'), state: 'doing' },
7507
7789
  ticket('AB-S'),
7508
7790
  ...Array.from({ length: builds }, (_, i) => ticket(`AB-${i + 1}`)),
7791
+ ...extra.map(([id, level]) => ({
7792
+ ...ticket(id),
7793
+ ...(level === 'normal' ? {} : { priority: level }),
7794
+ })),
7509
7795
  ],
7510
7796
  { doneState: 'done' },
7511
7797
  )
@@ -7942,6 +8228,52 @@ export async function ticketStartReadBudget(): Promise<{
7942
8228
  }
7943
8229
  expect(tiers.get(5_000)).toEqual(tiers.get(100))
7944
8230
  for (const calls of tiers.get(100)!) expect(calls).toEqual({})
8231
+
8232
+ // More start requests than one tick evaluates, beside ready tickets at
8233
+ // every level, with free slots for all of them. Intake runs a late pass
8234
+ // before each level's first ready ticket, yet a tick evaluates at most eight
8235
+ // early-tier and eight late-tier requests; a request left unevaluated stays
8236
+ // ahead of ready tickets at its level and below until a later scan.
8237
+ const ids = (tier: string, from: number, to: number) =>
8238
+ Array.from({ length: to - from + 1 }, (_, i) => `R-${tier}-${from + i}`)
8239
+ const requested = [
8240
+ ...ids('urgent', 1, 8).map((id) => [id, 'urgent'] as const),
8241
+ ...(['high', 'normal', 'low'] as const).flatMap((tier) =>
8242
+ ids(tier, 1, 9).map((id) => [id, tier] as const),
8243
+ ),
8244
+ ]
8245
+ for (const history of [100, 5_000]) {
8246
+ const world = await open(0, history, 64, 'levels', false, [
8247
+ ...requested.map(([id]) => [id, 'normal'] as const),
8248
+ ['RU', 'urgent'],
8249
+ ['RH', 'high'],
8250
+ ['RL', 'low'],
8251
+ ])
8252
+ for (const [id, tier] of requested)
8253
+ await requestTicketStart({
8254
+ store: world.store,
8255
+ repo: world.repo,
8256
+ source: world.tickets,
8257
+ id,
8258
+ user: 'budget',
8259
+ priority: tier,
8260
+ })
8261
+ // The first tick, before any build exists whose identity a later tick
8262
+ // projects: a started request's claim reads its ticket again, so count
8263
+ // each evaluated request once.
8264
+ const measured = await world.tick(true)
8265
+ expect([...new Set(measured.gets.filter((id) => id.startsWith('R-')))]).toEqual([
8266
+ ...ids('urgent', 1, 8),
8267
+ ...ids('high', 1, 8),
8268
+ ])
8269
+ // R-high-9 was not evaluated: RH and every lower ready ticket wait.
8270
+ expect(world.claims).toEqual([...ids('urgent', 1, 8), 'RU', ...ids('high', 1, 8)])
8271
+ world.claims.length = 0
8272
+ await world.tick(true)
8273
+ // R-normal-8 and R-normal-9 were not evaluated: normal and low wait.
8274
+ expect(world.claims).toEqual(['R-high-9', 'RH', ...ids('normal', 1, 7)])
8275
+ await world.store.close()
8276
+ }
7945
8277
  return baseline
7946
8278
  }
7947
8279
 
@@ -8360,6 +8692,31 @@ export async function openBuildListingReadBudget(opts: { commands?: boolean } =
8360
8692
  })
8361
8693
  await store.createBuild({ slug: 'open-aborted', repo, created: created('open-aborted') })
8362
8694
  await store.append('open-aborted', { actor: KERNEL, type: 'build.aborted', payload: {} })
8695
+ // Done builds with a post-completion escalation: one still open, one
8696
+ // acknowledged. Only the open one is listed, through `doneEscalations`.
8697
+ for (const slug of ['done-escalated', 'done-acknowledged']) {
8698
+ await store.createBuild({ slug, repo, created: created(slug) })
8699
+ await store.append(slug, {
8700
+ actor: DISPATCHER,
8701
+ type: 'build.completed',
8702
+ payload: { outcome: 'merged' },
8703
+ })
8704
+ await store.append(slug, {
8705
+ actor: KERNEL,
8706
+ type: 'escalation.raised',
8707
+ payload: {
8708
+ id: 'integration-audit-op',
8709
+ phase: 'verify:integration',
8710
+ source: 'agent',
8711
+ question: 'Integration result requires attention',
8712
+ },
8713
+ })
8714
+ }
8715
+ await store.append('done-acknowledged', {
8716
+ actor: humanActor('op'),
8717
+ type: 'escalation.answered',
8718
+ payload: { id: 'integration-audit-op', answer: 'ack', resolution: 'retry' },
8719
+ })
8363
8720
  for (let i = 0; i < settled; i++) {
8364
8721
  const slug = `settled-${i}`
8365
8722
  await store.createBuild({ slug, repo, created: created(slug) })
@@ -8469,11 +8826,17 @@ export async function openBuildListingReadBudget(opts: { commands?: boolean } =
8469
8826
  expect([got.detail.slot, got.dashboardRow?.slot]).toEqual([held, held])
8470
8827
  expect(
8471
8828
  (await surfaces.dashboard(store)).model.builds.map((build) => build.slug).sort(),
8472
- ).toEqual(['open-aborted', 'open-consent', 'open-queued'])
8829
+ ).toEqual(['done-escalated', 'open-aborted', 'open-consent', 'open-queued'])
8830
+ // The escalated done build is a blocked row that holds no slot.
8831
+ const escalatedRow = dashboardRows.find((row) => row.slug === 'done-escalated')
8832
+ expect(escalatedRow).toMatchObject({ status: 'blocked', statusBasis: { done: true } })
8833
+ expect(escalatedRow).not.toHaveProperty('slot')
8473
8834
  expect((await surfaces.status(store)).capacity).toBeDefined()
8474
8835
  const digest = await surfaces.attention(store)
8475
8836
  expect(digest.merges.map((merge) => merge.slug)).toEqual(['open-consent'])
8476
- expect(digest.escalations).toEqual([])
8837
+ expect(digest.escalations.map(({ slug, status }) => ({ slug, status }))).toEqual([
8838
+ { slug: 'done-escalated', status: 'done' },
8839
+ ])
8477
8840
  expect(JSON.stringify(digest)).not.toMatch(/open-aborted|settled-/)
8478
8841
  const rows = memoryRepositoryReadCounter(store, repo)
8479
8842
  const entries = memoryListingEntryCounter(store)