@defrex/autobuild 1.11.1 → 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 (213) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +601 -203
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +32 -2
  5. package/docs/architecture.md +188 -57
  6. package/docs/assets/headline-wide.png +0 -0
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +120 -23
  9. package/docs/dispatcher.md +19 -8
  10. package/docs/integration-overview.md +1 -1
  11. package/docs/integration-tree.md +33 -18
  12. package/docs/merge-policy.md +7 -2
  13. package/docs/operating.md +5 -3
  14. package/docs/operator-api.md +48 -25
  15. package/docs/operator-surfaces.md +39 -3
  16. package/docs/optimization-nodes.md +10 -8
  17. package/docs/plugin-authoring.md +46 -18
  18. package/docs/remote-store-protocol.md +51 -12
  19. package/docs/remote-ticket-protocol.md +85 -38
  20. package/docs/restacking.md +48 -3
  21. package/docs/setup.md +2 -1
  22. package/docs/ticket-migration.md +2 -2
  23. package/docs/ticket-sources.md +23 -8
  24. package/docs/tickets.md +4 -4
  25. package/docs/troubleshooting.md +17 -2
  26. package/docs/verification.md +3 -1
  27. package/package.json +3 -3
  28. package/packages/core/src/cli/ambient-errors.ts +17 -0
  29. package/packages/core/src/cli/bounded-io.ts +174 -0
  30. package/packages/core/src/cli/build-control.ts +72 -6
  31. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  32. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  33. package/packages/core/src/cli/dashboard/model.ts +93 -29
  34. package/packages/core/src/cli/dashboard/poll.ts +231 -34
  35. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  36. package/packages/core/src/cli/dashboard/render.ts +14 -37
  37. package/packages/core/src/cli/dashboard/row-text.ts +26 -8
  38. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  39. package/packages/core/src/cli/dashboard/vocabulary.ts +165 -20
  40. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  41. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  42. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  43. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  44. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  45. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  46. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  47. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  48. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  49. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  50. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  51. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  52. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  53. package/packages/core/src/cli/dispatch.ts +595 -149
  54. package/packages/core/src/cli/env.ts +2 -15
  55. package/packages/core/src/cli/help.ts +43 -28
  56. package/packages/core/src/cli/main.ts +11 -7
  57. package/packages/core/src/cli/production-store.ts +102 -0
  58. package/packages/core/src/cli/publication-settlement.ts +4 -0
  59. package/packages/core/src/cli/remote-poll.ts +22 -5
  60. package/packages/core/src/cli/repo-state.ts +2 -3
  61. package/packages/core/src/cli/repository-status.ts +44 -28
  62. package/packages/core/src/cli/sessionless-store.ts +26 -0
  63. package/packages/core/src/cli/status.ts +188 -47
  64. package/packages/core/src/cli/store-opening.ts +26 -57
  65. package/packages/core/src/cli/store-ref.ts +6 -1
  66. package/packages/core/src/cli/ticket-start.ts +3 -3
  67. package/packages/core/src/cli/ticket.ts +12 -11
  68. package/packages/core/src/cli/wait.ts +8 -28
  69. package/packages/core/src/cli/watch.ts +113 -50
  70. package/packages/core/src/config/reference-metadata.ts +7 -1
  71. package/packages/core/src/config/reference.ts +5 -2
  72. package/packages/core/src/config/schema.ts +51 -16
  73. package/packages/core/src/distribution-packaging.ts +156 -18
  74. package/packages/core/src/events/catalog-identity.ts +28 -0
  75. package/packages/core/src/events/catalog.ts +3 -9
  76. package/packages/core/src/events/compatibility.ts +2 -30
  77. package/packages/core/src/events/payloads.ts +85 -14
  78. package/packages/core/src/events/policy.ts +3 -0
  79. package/packages/core/src/events/repository.ts +15 -4
  80. package/packages/core/src/events/sessions.ts +1 -1
  81. package/packages/core/src/events/validation-error.ts +12 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +36 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  92. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  93. package/packages/core/src/kernel/capacity-build.ts +21 -0
  94. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  95. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +578 -235
  97. package/packages/core/src/kernel/done-escalations.ts +269 -0
  98. package/packages/core/src/kernel/engine.ts +30 -17
  99. package/packages/core/src/kernel/integration-landing.ts +24 -4
  100. package/packages/core/src/kernel/integration-stack.ts +39 -0
  101. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  102. package/packages/core/src/kernel/log-index-value.ts +3 -0
  103. package/packages/core/src/kernel/log-index.ts +41 -2
  104. package/packages/core/src/kernel/measurement.ts +24 -0
  105. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  106. package/packages/core/src/kernel/read-facts.ts +8 -370
  107. package/packages/core/src/kernel/reducer-registry.ts +43 -125
  108. package/packages/core/src/kernel/reducer-revisions.ts +18 -0
  109. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  110. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  111. package/packages/core/src/kernel/reducer.ts +84 -16
  112. package/packages/core/src/kernel/reopen-state.ts +10 -0
  113. package/packages/core/src/kernel/repository-attention.ts +14 -5
  114. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  115. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  116. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  117. package/packages/core/src/kernel/verify-stages.ts +46 -7
  118. package/packages/core/src/operator/attention.ts +28 -3
  119. package/packages/core/src/operator/done-escalations.ts +38 -0
  120. package/packages/core/src/operator/presentation.ts +14 -1
  121. package/packages/core/src/operator/protocol.ts +8 -5
  122. package/packages/core/src/operator/query.ts +72 -57
  123. package/packages/core/src/operator/registry.ts +19 -15
  124. package/packages/core/src/operator/ticket-start.ts +8 -7
  125. package/packages/core/src/operator/tickets.ts +28 -9
  126. package/packages/core/src/plugin-sdk/index.ts +10 -0
  127. package/packages/core/src/plugins/manifest.ts +14 -1
  128. package/packages/core/src/ports/forge/create.ts +8 -0
  129. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  130. package/packages/core/src/ports/forge/github.ts +3 -0
  131. package/packages/core/src/ports/tickets/contract.ts +147 -76
  132. package/packages/core/src/ports/tickets/create.ts +47 -7
  133. package/packages/core/src/ports/tickets/fake.ts +8 -4
  134. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  135. package/packages/core/src/ports/tickets/file.ts +7 -3
  136. package/packages/core/src/ports/tickets/github.ts +1 -0
  137. package/packages/core/src/ports/tickets/grants.ts +11 -3
  138. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  139. package/packages/core/src/ports/tickets/linear.ts +28 -9
  140. package/packages/core/src/ports/tickets/migration.ts +4 -4
  141. package/packages/core/src/ports/tickets/operations.ts +4 -2
  142. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  143. package/packages/core/src/ports/tickets/priority.ts +127 -21
  144. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  145. package/packages/core/src/ports/tickets/remote.ts +104 -11
  146. package/packages/core/src/ports/tickets/revision.ts +5 -3
  147. package/packages/core/src/ports/tickets/search.ts +9 -0
  148. package/packages/core/src/ports/tickets/tree.ts +8 -6
  149. package/packages/core/src/ports/types.ts +30 -15
  150. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  151. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  152. package/packages/core/src/ports/workspace/create.ts +16 -3
  153. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  154. package/packages/core/src/ports/workspace/fake.ts +15 -3
  155. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  156. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  157. package/packages/core/src/processes/build-execution-state.ts +4 -0
  158. package/packages/core/src/processes/build-runner.ts +14 -1
  159. package/packages/core/src/processes/dispatcher.ts +777 -288
  160. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  161. package/packages/core/src/processes/execution-settlement.ts +1 -0
  162. package/packages/core/src/processes/harvest-runner.ts +12 -7
  163. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  164. package/packages/core/src/processes/invocation-budget.ts +176 -0
  165. package/packages/core/src/processes/publication-loss.ts +38 -3
  166. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  167. package/packages/core/src/store/contract.ts +81 -3
  168. package/packages/core/src/store/event-reads.ts +30 -1
  169. package/packages/core/src/store/local/capabilities.ts +115 -0
  170. package/packages/core/src/store/local/store.ts +86 -56
  171. package/packages/core/src/store/reduced-reads.ts +32 -1
  172. package/packages/core/src/store/reducer-value-read.ts +235 -0
  173. package/packages/core/src/store/reducer-value-shapes.json +6722 -6475
  174. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  175. package/packages/core/src/store/reducer-values.ts +36 -204
  176. package/packages/core/src/store/remote/client.ts +169 -29
  177. package/packages/core/src/store/remote/compatibility.ts +113 -56
  178. package/packages/core/src/store/remote/credentials.ts +4 -1
  179. package/packages/core/src/store/remote/protocol.ts +3 -0
  180. package/packages/core/src/store/remote/released-clients.json +22 -0
  181. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  182. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  183. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  184. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  185. package/packages/core/src/store/remote/retry.ts +406 -0
  186. package/packages/core/src/store/rollup-lease.ts +41 -0
  187. package/packages/core/src/store/rollups.ts +7 -38
  188. package/packages/core/src/store/snapshots.ts +1 -1
  189. package/packages/core/src/testing/dispatch-read-budget.ts +409 -14
  190. package/packages/core/src/testing/import-graph.ts +78 -0
  191. package/packages/core/src/testing/index.ts +2 -0
  192. package/packages/core/src/testing/invocation-budget.ts +42 -0
  193. package/packages/core/src/testing/reduced-read-budget.ts +602 -40
  194. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  195. package/packages/core/src/testing/slot-agreement.ts +52 -0
  196. package/packages/core/src/web/assets/app.js +5 -5
  197. package/packages/core/src/web/overview-source.ts +19 -6
  198. package/skills/guide/SKILL.md +245 -103
  199. package/skills/guide/references/integration-tree.md +33 -18
  200. package/skills/guide/references/merge-policy.md +7 -2
  201. package/skills/guide/references/operator-api.md +48 -25
  202. package/skills/guide/references/optimization-nodes.md +10 -8
  203. package/skills/guide/references/plugin-authoring.md +46 -18
  204. package/skills/guide/references/remote-store-protocol.md +51 -12
  205. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  206. package/skills/guide/references/restacking.md +48 -3
  207. package/skills/guide/references/setup.md +2 -1
  208. package/skills/guide/references/ticket-migration.md +2 -2
  209. package/skills/operate/SKILL.md +114 -65
  210. package/skills/plan/SKILL.md +4 -3
  211. package/skills/spec/SKILL.md +9 -5
  212. package/skills/tickets/SKILL.md +25 -17
  213. 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(
@@ -2152,7 +2185,6 @@ async function measureProposerStages(
2152
2185
  admitProposers(
2153
2186
  builds: unknown[],
2154
2187
  now: Date,
2155
- admitted: number,
2156
2188
  report: unknown,
2157
2189
  launched: Set<string>,
2158
2190
  opts: object,
@@ -2168,7 +2200,7 @@ async function measureProposerStages(
2168
2200
  await stages.advanceOptimizationNodes(report, {}, entries, now)
2169
2201
  await stages.optimizationCreationHolds()
2170
2202
  await stages.releaseStrandedNodeWorkspaces(builds, now, new Set(), report, {})
2171
- await stages.admitProposers(builds, now, 0, report, new Set(), {})
2203
+ await stages.admitProposers(builds, now, report, new Set(), {})
2172
2204
  })
2173
2205
  }
2174
2206
 
@@ -2842,12 +2874,40 @@ export function memoryRepositoryReadCounter(
2842
2874
  },
2843
2875
  })
2844
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
+ }
2845
2893
  const getReducerValue = store.getReducerValue.bind(store)
2846
2894
  store.getReducerValue = async (scope, request) => {
2847
2895
  reducedCalls++
2848
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)
2849
2899
  return getReducerValue(scope, request)
2850
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
+ }
2851
2911
  return {
2852
2912
  get rows() {
2853
2913
  return rows
@@ -2864,12 +2924,27 @@ export function memoryRepositoryReadCounter(
2864
2924
  get buildFactsCalls() {
2865
2925
  return buildFactsCalls
2866
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
+ },
2867
2939
  reset() {
2868
2940
  rows = 0
2869
2941
  buildRows = 0
2870
2942
  buildRowsBySlug.clear()
2871
2943
  reducedCalls = 0
2872
2944
  buildFactsCalls = 0
2945
+ seedCalls = 0
2946
+ reducedCallsBySlug.clear()
2947
+ pageCallsBySlug.clear()
2873
2948
  },
2874
2949
  }
2875
2950
  }
@@ -2887,6 +2962,10 @@ export async function nodePollingReadBudget(opts: {
2887
2962
  * so the every-tick admission stage is measured on its waiting path. Its
2888
2963
  * own reads are excluded from the measurement. */
2889
2964
  slotWaiting?: () => Promise<boolean>
2965
+ /** Proves an admitted node keeps holding its slot after each measured tick
2966
+ * with no further admission: `admissions()` counts its `slot.admitted`
2967
+ * facts, `held()` reports `nodeHoldsSlot`. Their own reads are excluded. */
2968
+ slotHeld?: { admissions(): Promise<number>; held(): Promise<boolean> }
2890
2969
  /** An optimization node with one in-flight attempt build (#1069): proves
2891
2970
  * its active-hours activity pass. Each change is appended on the attempt
2892
2971
  * build; `pad` appends unrelated events there. */
@@ -2950,6 +3029,7 @@ export async function nodePollingReadBudget(opts: {
2950
3029
  return selected
2951
3030
  }
2952
3031
  const costs: number[] = []
3032
+ const admitted = opts.slotHeld ? await opts.slotHeld.admissions() : 0
2953
3033
  let calls = 0
2954
3034
  const getReduced = store.getReducerValue.bind(store)
2955
3035
  store.getReducerValue = async (...args) => {
@@ -2967,6 +3047,10 @@ export async function nodePollingReadBudget(opts: {
2967
3047
  if (elapsed === 10_000) expect(rows).toBe(0)
2968
3048
  costs.push(rows, calls)
2969
3049
  if (opts.slotWaiting) expect(await opts.slotWaiting()).toBe(true)
3050
+ if (opts.slotHeld) {
3051
+ expect(await opts.slotHeld.held()).toBe(true)
3052
+ expect(await opts.slotHeld.admissions()).toBe(admitted)
3053
+ }
2970
3054
  history = 0
2971
3055
  }
2972
3056
  } finally {
@@ -3559,6 +3643,201 @@ export async function cliWatchDiscoveryReadBudget() {
3559
3643
  expect(costs[1]).toEqual(costs[0]!)
3560
3644
  }
3561
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
+
3562
3841
  /** Fresh operator backends must not turn canonical build history into ticket requests. */
3563
3842
  export async function operatorTicketAssociationBudget() {
3564
3843
  const { MemoryBuildStore } = await import('../store/memory')
@@ -4128,8 +4407,9 @@ export async function ticketRoleTickBudget(
4128
4407
  return baseline!
4129
4408
  }
4130
4409
 
4131
- /** Urgent intake order (AUT-1027) is an in-memory partition of the one ready
4132
- * 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),
4133
4413
  * a quiet intake tick makes the same source calls and the same store reads, at
4134
4414
  * 100 and 100,000 repository events, and an unchanged follow-up read costs zero
4135
4415
  * rows. Returns the per-method source calls of one tick. */
@@ -4145,12 +4425,19 @@ export async function urgentIntakeReadBudget() {
4145
4425
  const methods = ['listReady', 'get', 'dependencyStates', 'listAll'] as const
4146
4426
  const results = new Map<string, { calls: Record<string, number>[]; rows: number[] }>()
4147
4427
  const profileResults = new Map<string, { calls: Record<string, number>[]; rows: number[] }>()
4148
- for (const [urgent, profiles] of [
4149
- [false, false],
4150
- [true, false],
4151
- [false, true],
4152
- [true, true],
4153
- ] 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) {
4154
4441
  const config = parseConfig(profiles ? profiled : plain)
4155
4442
  for (const length of [100, 100_000]) {
4156
4443
  const source = new FakeTicketSource([], { createState: 'triage', doneState: 'done' })
@@ -4171,7 +4458,7 @@ export async function urgentIntakeReadBudget() {
4171
4458
  const ticket = await source.create({
4172
4459
  title,
4173
4460
  body: 'Budget',
4174
- ...(urgent && index === 2 ? { priority: 'urgent' as const } : {}),
4461
+ ...(levels[index] !== 'normal' ? { priority: levels[index] } : {}),
4175
4462
  ...(profiles
4176
4463
  ? { labels: index === 0 ? ['deep'] : index === 1 ? ['deep', 'cheap'] : [] }
4177
4464
  : {}),
@@ -4263,8 +4550,9 @@ export async function urgentIntakeReadBudget() {
4263
4550
  * on a full repository cost each idle tick zero historical rows, no append and
4264
4551
  * no ready listing inside the scan interval, at 100 and 100,000 events. Once
4265
4552
  * `free` opens one slot for the normal build, its first deferral forces one
4266
- * listing; while its launch keeps being refused under the same deferral key,
4267
- * idle ticks force no further listing and still read no history. */
4553
+ * listing and admits it with exactly one `slot.admitted` fact; while its
4554
+ * launch keeps being refused, idle ticks retry it holding its slot, append
4555
+ * nothing, force no further listing and read no history. */
4268
4556
  export async function slotAdmissionReadBudget(opts: {
4269
4557
  store: import('../store/memory').MemoryBuildStore
4270
4558
  /** The normal parked build; filler events extend its log. */
@@ -4290,7 +4578,15 @@ export async function slotAdmissionReadBudget(opts: {
4290
4578
  total += repo.events.length
4291
4579
  return total
4292
4580
  }
4293
- const idle = async (ticks: number) => {
4581
+ const admissions = () => {
4582
+ let total = 0
4583
+ for (const build of (
4584
+ Reflect.get(store, 'builds') as Map<string, { events: { type: string }[] }>
4585
+ ).values())
4586
+ total += build.events.filter((event) => event.type === 'slot.admitted').length
4587
+ return total
4588
+ }
4589
+ const idle = async (ticks: number, relaunches = false) => {
4294
4590
  const boundary = events.at(-1)!.seq
4295
4591
  const metrics = { historicalRows: 0, tailRows: 0 }
4296
4592
  const restore = instrumentBuildRows(store, slug, () => boundary, metrics)
@@ -4305,7 +4601,9 @@ export async function slotAdmissionReadBudget(opts: {
4305
4601
  }
4306
4602
  expect(metrics.historicalRows).toBe(0)
4307
4603
  expect(opts.listed() - before.listed).toBe(0)
4308
- expect(opts.launched() - before.launched).toBe(0)
4604
+ // An admitted build holds its slot, so its refused launch is retried
4605
+ // (here with no first-claim grace); a waiter is never launched.
4606
+ expect(opts.launched() - before.launched).toBe(relaunches ? ticks : 0)
4309
4607
  expect(appended() - before.appended).toBe(0)
4310
4608
  }
4311
4609
  let filler = 0
@@ -4330,10 +4628,81 @@ export async function slotAdmissionReadBudget(opts: {
4330
4628
  await opts.free()
4331
4629
  opts.advance()
4332
4630
  const listed = opts.listed()
4631
+ const admitted = admissions()
4333
4632
  await opts.tick()
4334
- // The first deferral forces one listing and admits the build after it.
4633
+ // The first deferral forces one listing and admits the build after it:
4634
+ // admission is one durable `slot.admitted` fact (SPEC §12 "What holds a
4635
+ // slot"), appended once and never per idle tick.
4335
4636
  expect(opts.listed() - listed).toBe(1)
4336
- await idle(3)
4637
+ expect(admissions() - admitted).toBe(1)
4638
+ // One tick advances the saved reduced values past that fact; the admitted
4639
+ // build then holds its slot and its refused launch is retried, with no
4640
+ // listing, append or history read.
4641
+ opts.advance()
4642
+ await opts.tick()
4643
+ await idle(3, true)
4644
+ expect(admissions() - admitted).toBe(1)
4645
+ }
4646
+
4647
+ /** A leaf whose question was answered while its runner still worked keeps
4648
+ * the slot it never gave up (SPEC §12 "What holds a slot", #1348): idle ticks
4649
+ * over it, at 100 and 100,000 events, read no historical event rows, append
4650
+ * nothing (no per-tick launch record), force no ready listing, launch nothing,
4651
+ * and leave it held. */
4652
+ export async function runnerRetainedSlotReadBudget(opts: {
4653
+ store: import('../store/memory').MemoryBuildStore
4654
+ /** The retained leaf; filler events extend its log. */
4655
+ slug: string
4656
+ tick: () => Promise<unknown>
4657
+ listed: () => number
4658
+ launched: () => number
4659
+ /** Advance the clock by a small fraction of the scan interval. */
4660
+ advance: () => void
4661
+ /** Advance the clock past the scan interval, so the next scan is due. */
4662
+ advanceDue: () => void
4663
+ held: () => Promise<boolean>
4664
+ }): Promise<void> {
4665
+ const { store, slug } = opts
4666
+ const events = buildEventRows(store, slug)
4667
+ const appended = () => {
4668
+ let total = 0
4669
+ for (const build of (
4670
+ Reflect.get(store, 'builds') as Map<string, { events: unknown[] }>
4671
+ ).values())
4672
+ total += build.events.length
4673
+ for (const repo of (Reflect.get(store, 'repos') as Map<string, { events: unknown[] }>).values())
4674
+ total += repo.events.length
4675
+ return total
4676
+ }
4677
+ for (const length of [100, 100_000]) {
4678
+ while (events.length < length)
4679
+ await store.append(slug, {
4680
+ actor: humanActor('budget'),
4681
+ type: 'build.auto-merge-cancelled',
4682
+ payload: {},
4683
+ })
4684
+ opts.advanceDue()
4685
+ await opts.tick()
4686
+ opts.advance()
4687
+ await opts.tick()
4688
+ const boundary = events.at(-1)!.seq
4689
+ const metrics = { historicalRows: 0, tailRows: 0 }
4690
+ const restore = instrumentBuildRows(store, slug, () => boundary, metrics)
4691
+ const before = { listed: opts.listed(), launched: opts.launched(), appended: appended() }
4692
+ try {
4693
+ for (let tick = 0; tick < 3; tick++) {
4694
+ opts.advance()
4695
+ await opts.tick()
4696
+ }
4697
+ } finally {
4698
+ restore()
4699
+ }
4700
+ expect(metrics.historicalRows).toBe(0)
4701
+ expect(opts.listed() - before.listed).toBe(0)
4702
+ expect(opts.launched() - before.launched).toBe(0)
4703
+ expect(appended() - before.appended).toBe(0)
4704
+ expect(await opts.held()).toBe(true)
4705
+ }
4337
4706
  }
4338
4707
 
4339
4708
  /** Open-PR backpressure (SPEC §12 Intake order) counts open root PRs over the
@@ -5450,9 +5819,10 @@ export async function hookReadBudget(): Promise<void> {
5450
5819
  requests: requests.vector(),
5451
5820
  }
5452
5821
  expect(delivered.slice(deliveredBefore)).toHaveLength(2)
5453
- // Each new row is read once per hook, plus once by the shared reduced
5454
- // value's incremental advance.
5455
- 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 })
5456
5826
  expect(listing(changed.requests)).toEqual([0, 0, 0])
5457
5827
  requests.restore()
5458
5828
 
@@ -7092,11 +7462,11 @@ export async function panelProgressReadBudget(): Promise<void> {
7092
7462
  const shared = { record, state, workspace: true }
7093
7463
  const before = requests.vector()
7094
7464
  for (let repeat = 0; repeat < 5; repeat++) {
7095
- expect(slotRequest({ ...shared, workspace: false }, now)).toBe('verification')
7465
+ expect(slotRequest(shared, now)).toBe('verification')
7096
7466
  expect(decideNextFromFacts(state, facts.log, config).kind).toBe('measure-progress')
7097
7467
  expect(strandedNodeWorkspace(shared, now)).toBe(false)
7098
7468
  state.currentPhase = { phase: 'propose', round: 100, seq: state.lastSeq }
7099
- expect(slotRequest({ ...shared, workspace: false }, now)).toBe('propose')
7469
+ expect(slotRequest(shared, now)).toBe('propose')
7100
7470
  expect(decideNextFromFacts(state, facts.log, config)).toMatchObject({
7101
7471
  kind: 'run-phase',
7102
7472
  phase: 'propose',
@@ -7389,6 +7759,8 @@ export async function ticketStartReadBudget(): Promise<{
7389
7759
  label: string,
7390
7760
  /** AB-0 waits on a blocker whose dependency read fails. */
7391
7761
  blocked = false,
7762
+ /** Further ready tickets, as `[id, level]`. */
7763
+ extra: readonly (readonly [string, import('../ports/types').TicketPriority])[] = [],
7392
7764
  ) => {
7393
7765
  let now = 1_800_000_000_000
7394
7766
  const clock = () => new Date(now)
@@ -7416,6 +7788,10 @@ export async function ticketStartReadBudget(): Promise<{
7416
7788
  { ...ticket('AB-W'), state: 'doing' },
7417
7789
  ticket('AB-S'),
7418
7790
  ...Array.from({ length: builds }, (_, i) => ticket(`AB-${i + 1}`)),
7791
+ ...extra.map(([id, level]) => ({
7792
+ ...ticket(id),
7793
+ ...(level === 'normal' ? {} : { priority: level }),
7794
+ })),
7419
7795
  ],
7420
7796
  { doneState: 'done' },
7421
7797
  )
@@ -7452,6 +7828,9 @@ export async function ticketStartReadBudget(): Promise<{
7452
7828
  },
7453
7829
  }) as unknown as Source
7454
7830
  // Unrelated active builds: legacy aliases and readable ids in mixed case.
7831
+ // Each runs under an attached runner's live lease, so it holds its slot
7832
+ // for the whole budget: a build blocked by a failed dispatch boundary
7833
+ // would hold none (SPEC §12 "What holds a slot").
7455
7834
  for (let i = 1; i <= builds; i++) {
7456
7835
  const ref = { source: 'hosted', id: i % 2 ? `ticket-${i}` : `ab-${i}` }
7457
7836
  await store.createBuild({
@@ -7465,6 +7844,12 @@ export async function ticketStartReadBudget(): Promise<{
7465
7844
  payload: { ticket: ref, repo, baseBranch: 'main' },
7466
7845
  },
7467
7846
  })
7847
+ await store.append(`active-${i}`, {
7848
+ actor: KERNEL,
7849
+ type: 'runner.attached',
7850
+ payload: { instance: `runner-active-${i}`, host: 'budget' },
7851
+ })
7852
+ await store.claimLease(`active-${i}`, `runner-active-${i}`, 365 * 24 * 3_600_000)
7468
7853
  }
7469
7854
  // Unrelated builds this runtime defers for a newer writer's decisive
7470
7855
  // fact, one per five active builds: they hold slots and their deferral
@@ -7622,10 +8007,9 @@ export async function ticketStartReadBudget(): Promise<{
7622
8007
  control.fresh()
7623
8008
  pending.fresh()
7624
8009
  }
7625
- // The unleased builds are relaunched until their launch budget blocks
7626
- // them. Capacity is measured from the facts the tick's own stages
7627
- // read, so even a fresh process's first waiting tick reads no build
7628
- // the control does not.
8010
+ // Capacity is measured from the facts the tick's own stages read, so
8011
+ // even a fresh process's first waiting tick reads no build the control
8012
+ // does not.
7629
8013
  for (let i = 0; i < (fresh ? 1 : 2); i++) {
7630
8014
  const base = await control.tick()
7631
8015
  const measured = await pending.tick()
@@ -7844,6 +8228,52 @@ export async function ticketStartReadBudget(): Promise<{
7844
8228
  }
7845
8229
  expect(tiers.get(5_000)).toEqual(tiers.get(100))
7846
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
+ }
7847
8277
  return baseline
7848
8278
  }
7849
8279
 
@@ -8179,13 +8609,17 @@ function memoryListingEntryCounter(store: import('../store/memory').MemoryBuildS
8179
8609
  * held-config capacity — receive the same record and digest entries at 1 and
8180
8610
  * 30 settled builds and at 100 and 100,000 events, each through a fresh
8181
8611
  * store handle (the stand-in for a fresh process), and read zero event rows
8182
- * while nothing changes (#1230). Returns the per-surface entry vectors. */
8183
- export async function openBuildListingReadBudget() {
8612
+ * while nothing changes (#1230). Every answer reports slot state (#1341).
8613
+ * With `commands`, `ab builds`, `ab build status` and `ab repository status`
8614
+ * JSON also report it with zero event rows; they read checkout files, so only
8615
+ * an integration test passes it. Returns the per-surface entry vectors. */
8616
+ export async function openBuildListingReadBudget(opts: { commands?: boolean } = {}) {
8184
8617
  const { MemoryBuildStore } = await import('../store/memory')
8185
8618
  const { listOperatorLandings } = await import('../operator/landings')
8186
8619
  const { getOperatorAttention } = await import('../operator/attention')
8187
- const { readRepositoryCapacity } = await import('../cli/repository-status')
8188
- const repo = 'open-listing-budget'
8620
+ const { readRepositoryCapacity, abRepositoryStatus } = await import('../cli/repository-status')
8621
+ const { abBuilds, abBuildStatus } = await import('../cli/status')
8622
+ const repo = '/open-listing-budget'
8189
8623
  const now = new Date(1000)
8190
8624
  const created = (slug: string) => ({
8191
8625
  actor: DISPATCHER,
@@ -8258,6 +8692,31 @@ export async function openBuildListingReadBudget() {
8258
8692
  })
8259
8693
  await store.createBuild({ slug: 'open-aborted', repo, created: created('open-aborted') })
8260
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
+ })
8261
8720
  for (let i = 0; i < settled; i++) {
8262
8721
  const slug = `settled-${i}`
8263
8722
  await store.createBuild({ slug, repo, created: created(slug) })
@@ -8277,9 +8736,59 @@ export async function openBuildListingReadBudget() {
8277
8736
  dashboard: (store: BuildStore) => getOperatorDashboard({ store, repo, clock: () => now }),
8278
8737
  status: (store: BuildStore) => getRepositoryStatus(store, repo, now),
8279
8738
  attention: (store: BuildStore) => getOperatorAttention({ store, repo, now }),
8739
+ get: (store: BuildStore) => getOperatorBuild({ store, repo, slug: 'open-consent', now }),
8280
8740
  history: (store: BuildStore) => listOperatorBuilds({ store, repo, scope: 'all', now }),
8281
8741
  }
8282
- let baseline: Record<string, { records: number; digests: number }> | undefined
8742
+ type Vector = { records: number; digests: number; calls: Record<string, number> }
8743
+ // The CLI status commands over the same store: each prints its JSON once.
8744
+ const exec = async (args: string[]) =>
8745
+ args[1] === 'remote'
8746
+ ? { stdout: '', stderr: 'no origin', exitCode: 2 }
8747
+ : { stdout: `${repo}/.git\n${repo}/.git\n${repo}\n`, stderr: '', exitCode: 0 }
8748
+ const cli = async (
8749
+ store: BuildStore,
8750
+ command: (opts: {
8751
+ targetRepo: string
8752
+ env: Record<string, string>
8753
+ exec: typeof exec
8754
+ storeRef: string
8755
+ openStore: () => BuildStore
8756
+ now: () => Date
8757
+ json: true
8758
+ stdout: (line: string) => void
8759
+ }) => Promise<void>,
8760
+ ) => {
8761
+ const lines: string[] = []
8762
+ // A handle whose close leaves the shared memory store open.
8763
+ const handle = new Proxy(store, {
8764
+ get(target, property) {
8765
+ if (property === 'close') return async () => {}
8766
+ const value = Reflect.get(target, property)
8767
+ return typeof value === 'function' ? value.bind(target) : value
8768
+ },
8769
+ })
8770
+ await command({
8771
+ targetRepo: repo,
8772
+ env: {},
8773
+ exec,
8774
+ // A named store reads no checkout configuration.
8775
+ storeRef: '/budget',
8776
+ openStore: () => handle,
8777
+ now: () => now,
8778
+ json: true,
8779
+ stdout: (line) => lines.push(line),
8780
+ })
8781
+ return JSON.parse(lines.join('\n'))
8782
+ }
8783
+ const commands = opts.commands
8784
+ ? {
8785
+ builds: (store: BuildStore) => cli(store, abBuilds),
8786
+ buildStatus: (store: BuildStore) =>
8787
+ cli(store, (command) => abBuildStatus({ ...command, slug: 'open-consent' })),
8788
+ repositoryStatus: (store: BuildStore) => cli(store, abRepositoryStatus),
8789
+ }
8790
+ : {}
8791
+ let baseline: Record<string, Vector> | undefined
8283
8792
  const history = new Map<number, number>()
8284
8793
  for (const settled of [1, 30])
8285
8794
  for (const padding of [100, 100_000]) {
@@ -8293,19 +8802,46 @@ export async function openBuildListingReadBudget() {
8293
8802
  const all = { ...surfaces, capacity, attentionAtHead }
8294
8803
  // Warm-up: every once-per-key reduction happens here. The seeded
8295
8804
  // surfaces answer real work, so the counted reads are meaningful.
8296
- for (const run of Object.values(all)) await run(store)
8805
+ for (const run of [...Object.values(all), ...Object.values(commands)]) await run(store)
8297
8806
  expect((await surfaces.landings(store)).map((entry) => entry.slug)).toEqual(['open-consent'])
8807
+ // Every answer reports slot state (#1341) from the facts it already read.
8808
+ const held = { state: 'held' } as const
8809
+ const none = { state: 'none' } as const
8810
+ // The consent leaf has not recorded `pipeline.settled`: it still holds.
8811
+ const slots = { 'open-queued': held, 'open-consent': held, 'open-aborted': none }
8812
+ for (const scope of ['active', 'queued'] as const)
8813
+ for (const row of await surfaces[scope](store))
8814
+ expect({ slug: row.slug, slot: row.slot }).toEqual({
8815
+ slug: row.slug,
8816
+ slot: slots[row.slug as keyof typeof slots],
8817
+ })
8818
+ const dashboardRows = (await surfaces.dashboard(store)).model.builds
8819
+ expect(Object.fromEntries(dashboardRows.map((row) => [row.slug, row.slot]))).toEqual(slots)
8820
+ // Repository status projects capacity as the dispatcher does, without
8821
+ // the aborted build in cleanup.
8822
+ const { 'open-aborted': _aborted, ...admitted } = slots
8823
+ expect((await surfaces.status(store)).capacity?.slots).toEqual(admitted)
8824
+ expect((await capacity(store))?.slots).toEqual(admitted)
8825
+ const got = await surfaces.get(store)
8826
+ expect([got.detail.slot, got.dashboardRow?.slot]).toEqual([held, held])
8298
8827
  expect(
8299
8828
  (await surfaces.dashboard(store)).model.builds.map((build) => build.slug).sort(),
8300
- ).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')
8301
8834
  expect((await surfaces.status(store)).capacity).toBeDefined()
8302
8835
  const digest = await surfaces.attention(store)
8303
8836
  expect(digest.merges.map((merge) => merge.slug)).toEqual(['open-consent'])
8304
- expect(digest.escalations).toEqual([])
8837
+ expect(digest.escalations.map(({ slug, status }) => ({ slug, status }))).toEqual([
8838
+ { slug: 'done-escalated', status: 'done' },
8839
+ ])
8305
8840
  expect(JSON.stringify(digest)).not.toMatch(/open-aborted|settled-/)
8306
8841
  const rows = memoryRepositoryReadCounter(store, repo)
8307
8842
  const entries = memoryListingEntryCounter(store)
8308
- const vectors: Record<string, { records: number; digests: number }> = {}
8843
+ const calls = memoryStoreRequestCounter(store)
8844
+ const vectors: Record<string, Vector> = {}
8309
8845
  try {
8310
8846
  for (const [name, run] of Object.entries(all)) {
8311
8847
  // A fresh handle shares no store-identity-keyed cache.
@@ -8317,6 +8853,7 @@ export async function openBuildListingReadBudget() {
8317
8853
  })
8318
8854
  rows.reset()
8319
8855
  entries.reset()
8856
+ calls.reset()
8320
8857
  await run(fresh)
8321
8858
  expect({ name, rows: rows.rows, buildRows: rows.buildRows }).toEqual({
8322
8859
  name,
@@ -8324,9 +8861,34 @@ export async function openBuildListingReadBudget() {
8324
8861
  buildRows: 0,
8325
8862
  })
8326
8863
  if (name === 'history') history.set(settled, entries.vector.records)
8327
- else vectors[name] = entries.vector
8864
+ else vectors[name] = { ...entries.vector, calls: calls.vector() }
8865
+ }
8866
+ // The CLI listing iterates every record (pre-existing), so it stays
8867
+ // out of the flat vectors; it still reads no event row.
8868
+ for (const [name, run] of Object.entries(commands)) {
8869
+ rows.reset()
8870
+ const output = await run(store)
8871
+ expect({ name, rows: rows.rows, buildRows: rows.buildRows }).toEqual({
8872
+ name,
8873
+ rows: 0,
8874
+ buildRows: 0,
8875
+ })
8876
+ const reported =
8877
+ name === 'builds'
8878
+ ? Object.fromEntries(
8879
+ (output as { slug: string; slot?: unknown }[]).map((row) => [row.slug, row.slot]),
8880
+ )
8881
+ : name === 'buildStatus'
8882
+ ? { 'open-consent': output.slot }
8883
+ : output.capacity.slots
8884
+ expect({ name, reported }).toEqual({
8885
+ name,
8886
+ // `ab builds` lists the active scope: the queued build is under --queued.
8887
+ reported: name === 'repositoryStatus' ? admitted : { 'open-consent': held },
8888
+ })
8328
8889
  }
8329
8890
  } finally {
8891
+ calls.restore()
8330
8892
  entries.restore()
8331
8893
  }
8332
8894
  if (baseline) expect(vectors).toEqual(baseline)