@defrex/autobuild 1.10.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +738 -68
  3. package/bin/ab-dispatch-generation.ts +3 -1
  4. package/docs/accounts.md +2 -1
  5. package/docs/answering-blocked-builds.md +20 -0
  6. package/docs/architecture.md +155 -25
  7. package/docs/build-store.md +10 -7
  8. package/docs/cli.md +33 -1
  9. package/docs/configuration-overview.md +4 -1
  10. package/docs/configuration.md +381 -29
  11. package/docs/dispatcher.md +63 -4
  12. package/docs/forges.md +7 -0
  13. package/docs/integration-tree.md +2 -2
  14. package/docs/operating.md +4 -2
  15. package/docs/operator-api.md +134 -6
  16. package/docs/operator-surfaces.md +85 -0
  17. package/docs/optimization-nodes.md +69 -11
  18. package/docs/plugin-authoring.md +37 -1
  19. package/docs/remote-store-protocol.md +94 -13
  20. package/docs/remote-ticket-protocol.md +40 -0
  21. package/docs/restacking.md +20 -4
  22. package/docs/setup.md +14 -2
  23. package/docs/ticket-dependencies.md +10 -3
  24. package/docs/ticket-sources.md +24 -2
  25. package/docs/tickets.md +7 -1
  26. package/docs/troubleshooting.md +8 -0
  27. package/docs/verification.md +4 -3
  28. package/docs/workspaces.md +3 -0
  29. package/package.json +9 -5
  30. package/packages/core/src/cli/accounts.ts +7 -2
  31. package/packages/core/src/cli/attention.ts +3 -1
  32. package/packages/core/src/cli/binary-direct.ts +2 -0
  33. package/packages/core/src/cli/binary-lifecycle.ts +2 -1
  34. package/packages/core/src/cli/build-control.ts +79 -1
  35. package/packages/core/src/cli/context.ts +4 -0
  36. package/packages/core/src/cli/dashboard/facts.ts +49 -53
  37. package/packages/core/src/cli/dashboard/header.ts +101 -0
  38. package/packages/core/src/cli/dashboard/model.ts +31 -39
  39. package/packages/core/src/cli/dashboard/objective-row.ts +46 -14
  40. package/packages/core/src/cli/dashboard/poll.ts +178 -76
  41. package/packages/core/src/cli/dashboard/render.ts +129 -230
  42. package/packages/core/src/cli/dashboard/row-text.ts +538 -0
  43. package/packages/core/src/cli/dashboard/timeline.ts +288 -0
  44. package/packages/core/src/cli/dashboard/vocabulary.ts +188 -0
  45. package/packages/core/src/cli/dispatch-args.ts +44 -1
  46. package/packages/core/src/cli/dispatch-frontend.ts +29 -38
  47. package/packages/core/src/cli/dispatch-launch-stop.ts +18 -0
  48. package/packages/core/src/cli/dispatch-launcher.ts +20 -7
  49. package/packages/core/src/cli/dispatch-web.ts +155 -0
  50. package/packages/core/src/cli/dispatch.ts +200 -34
  51. package/packages/core/src/cli/help.ts +87 -3
  52. package/packages/core/src/cli/init-validation.ts +3 -3
  53. package/packages/core/src/cli/main.ts +70 -6
  54. package/packages/core/src/cli/mcp.ts +35 -3
  55. package/packages/core/src/cli/objective.ts +1 -1
  56. package/packages/core/src/cli/operator-preference.ts +57 -0
  57. package/packages/core/src/cli/repo-lease.ts +2 -0
  58. package/packages/core/src/cli/repo-state.ts +56 -6
  59. package/packages/core/src/cli/repository-status.ts +97 -43
  60. package/packages/core/src/cli/status.ts +82 -1
  61. package/packages/core/src/cli/terminal-restore.ts +32 -7
  62. package/packages/core/src/cli/ticket.ts +98 -36
  63. package/packages/core/src/cli/wait.ts +14 -6
  64. package/packages/core/src/cli/watch.ts +20 -4
  65. package/packages/core/src/cli/web.ts +139 -0
  66. package/packages/core/src/config/live.ts +99 -14
  67. package/packages/core/src/config/load.ts +61 -20
  68. package/packages/core/src/config/local.ts +212 -0
  69. package/packages/core/src/config/pipeline-source.ts +2 -0
  70. package/packages/core/src/config/reference.ts +18 -0
  71. package/packages/core/src/config/schema.ts +45 -10
  72. package/packages/core/src/events/catalog.ts +4 -0
  73. package/packages/core/src/events/payloads.ts +97 -0
  74. package/packages/core/src/events/policy.ts +10 -0
  75. package/packages/core/src/events/repository.ts +46 -3
  76. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +316 -0
  77. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/017d8dd5bb6dd80b.json.gz +0 -0
  78. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/178e12f1759b7552.json.gz +0 -0
  79. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4932c70a2af97faf.json.gz +0 -0
  80. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/536085773daf6b58.json.gz +0 -0
  81. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6bd6275061aaffa5.json.gz +0 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/89625654b02e9ac1.json.gz +0 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a98af134be2da8a9.json.gz +0 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d5d5ccca80a893d8.json.gz +0 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f8155387eb5f375c.json.gz +0 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3c27f918b194e3b3.json +465 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/79f0e0f4ccd43ba2.json +455 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
  92. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
  93. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
  94. package/packages/core/src/kernel/build-roster.ts +230 -0
  95. package/packages/core/src/kernel/dispatch-capacity.ts +4 -2
  96. package/packages/core/src/kernel/engine.ts +43 -5
  97. package/packages/core/src/kernel/execution-intervals.ts +61 -0
  98. package/packages/core/src/kernel/generators/optimization-log.ts +101 -0
  99. package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
  100. package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
  101. package/packages/core/src/kernel/leaf-restack-state.ts +82 -3
  102. package/packages/core/src/kernel/log-index.ts +19 -0
  103. package/packages/core/src/kernel/optimization-admission.ts +244 -3
  104. package/packages/core/src/kernel/optimization.ts +183 -4
  105. package/packages/core/src/kernel/phase-failures.ts +121 -0
  106. package/packages/core/src/kernel/published-branch-head.ts +60 -0
  107. package/packages/core/src/kernel/reducer-registry.ts +27 -8
  108. package/packages/core/src/kernel/reducer-revisions.ts +25 -0
  109. package/packages/core/src/kernel/reducer.ts +63 -4
  110. package/packages/core/src/kernel/rollup.ts +61 -0
  111. package/packages/core/src/kernel/setup-streak.ts +38 -0
  112. package/packages/core/src/kernel/step-durations.ts +257 -0
  113. package/packages/core/src/kernel/target-observation.ts +6 -1
  114. package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
  115. package/packages/core/src/kernel/verify-diff-base.ts +5 -0
  116. package/packages/core/src/kernel/verify-stages.ts +13 -3
  117. package/packages/core/src/ontology.ts +5 -0
  118. package/packages/core/src/operator/agent-context-serve.ts +631 -0
  119. package/packages/core/src/operator/annotations.ts +75 -5
  120. package/packages/core/src/operator/attention.ts +470 -0
  121. package/packages/core/src/operator/canonical-skills.ts +35 -0
  122. package/packages/core/src/operator/cli-equivalents.ts +270 -0
  123. package/packages/core/src/operator/context-prompts.ts +61 -0
  124. package/packages/core/src/operator/index.ts +49 -1
  125. package/packages/core/src/operator/landings.ts +28 -19
  126. package/packages/core/src/operator/optimization.ts +7 -0
  127. package/packages/core/src/operator/protocol.ts +3 -0
  128. package/packages/core/src/operator/query.ts +122 -72
  129. package/packages/core/src/operator/read-view.ts +5 -2
  130. package/packages/core/src/operator/registry.ts +406 -46
  131. package/packages/core/src/operator/requests.ts +20 -18
  132. package/packages/core/src/operator/sandbox-host.ts +107 -11
  133. package/packages/core/src/operator/sandbox-resolver.ts +253 -0
  134. package/packages/core/src/operator/sandbox.ts +778 -82
  135. package/packages/core/src/operator/ticket-asset-list.ts +77 -0
  136. package/packages/core/src/operator/ticket-assets.ts +167 -0
  137. package/packages/core/src/operator/tickets.ts +33 -2
  138. package/packages/core/src/plugin-sdk/index.ts +22 -0
  139. package/packages/core/src/plugins/manifest.ts +1 -1
  140. package/packages/core/src/ports/forge/fake.ts +92 -1
  141. package/packages/core/src/ports/forge/git-blob.ts +15 -0
  142. package/packages/core/src/ports/forge/github.ts +82 -0
  143. package/packages/core/src/ports/forge/local-git.ts +61 -1
  144. package/packages/core/src/ports/forge-failure.ts +24 -0
  145. package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
  146. package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
  147. package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
  148. package/packages/core/src/ports/tickets/contract.ts +71 -0
  149. package/packages/core/src/ports/tickets/fake.ts +11 -0
  150. package/packages/core/src/ports/tickets/file.ts +18 -0
  151. package/packages/core/src/ports/tickets/github-fake.ts +136 -4
  152. package/packages/core/src/ports/tickets/github.ts +387 -30
  153. package/packages/core/src/ports/tickets/hosted-index.ts +10 -0
  154. package/packages/core/src/ports/tickets/linear.ts +130 -0
  155. package/packages/core/src/ports/tickets/priority.ts +9 -0
  156. package/packages/core/src/ports/tickets/remote-protocol.ts +34 -0
  157. package/packages/core/src/ports/tickets/remote.ts +70 -6
  158. package/packages/core/src/ports/tickets/search.ts +139 -0
  159. package/packages/core/src/ports/types.ts +104 -2
  160. package/packages/core/src/ports/workspace/builtin-capabilities.ts +9 -0
  161. package/packages/core/src/ports/workspace/create.ts +15 -1
  162. package/packages/core/src/ports/workspace/fake.ts +340 -12
  163. package/packages/core/src/ports/workspace/git-worktree.ts +833 -42
  164. package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
  165. package/packages/core/src/ports/workspace/process-group.ts +48 -0
  166. package/packages/core/src/ports/workspace/vercel-sandbox.ts +1260 -123
  167. package/packages/core/src/processes/agent-context-assemble.ts +576 -0
  168. package/packages/core/src/processes/agent-context.ts +469 -0
  169. package/packages/core/src/processes/build-runner.ts +387 -236
  170. package/packages/core/src/processes/dispatcher.ts +211 -55
  171. package/packages/core/src/processes/execution-no-progress.ts +4 -0
  172. package/packages/core/src/processes/optimization-activity.ts +120 -0
  173. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  174. package/packages/core/src/processes/repo-view.ts +78 -2
  175. package/packages/core/src/processes/sandbox-state.ts +53 -6
  176. package/packages/core/src/processes/tick-publication.ts +2 -0
  177. package/packages/core/src/processes/workspace-preparation.ts +76 -0
  178. package/packages/core/src/scenarios/harness.ts +0 -5
  179. package/packages/core/src/store/account-redaction.ts +1 -0
  180. package/packages/core/src/store/adapter.ts +52 -1
  181. package/packages/core/src/store/agent-context.ts +432 -0
  182. package/packages/core/src/store/build-feed.ts +291 -0
  183. package/packages/core/src/store/build-scope.ts +19 -1
  184. package/packages/core/src/store/contract.ts +911 -14
  185. package/packages/core/src/store/digest.ts +19 -6
  186. package/packages/core/src/store/histogram.ts +113 -0
  187. package/packages/core/src/store/local/schema.ts +62 -0
  188. package/packages/core/src/store/local/store.ts +628 -22
  189. package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
  190. package/packages/core/src/store/memory.ts +461 -69
  191. package/packages/core/src/store/open-builds.ts +19 -0
  192. package/packages/core/src/store/phase-session.ts +32 -4
  193. package/packages/core/src/store/reduced-reads.ts +14 -4
  194. package/packages/core/src/store/reducer-value-shapes.json +6987 -5749
  195. package/packages/core/src/store/reducer-values.ts +6 -1
  196. package/packages/core/src/store/remote/client.ts +208 -2
  197. package/packages/core/src/store/remote/compatibility.ts +1 -1
  198. package/packages/core/src/store/remote/index.ts +33 -0
  199. package/packages/core/src/store/remote/protocol.ts +69 -0
  200. package/packages/core/src/store/remote/released-clients.json +11 -0
  201. package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
  202. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  203. package/packages/core/src/store/retention.ts +23 -1
  204. package/packages/core/src/store/rollups.ts +337 -0
  205. package/packages/core/src/store/session-handle.ts +20 -2
  206. package/packages/core/src/store/snapshots.ts +10 -0
  207. package/packages/core/src/store/types.ts +108 -9
  208. package/packages/core/src/testing/dispatch-read-budget.ts +1092 -2
  209. package/packages/core/src/testing/git-config-isolation.ts +7 -5
  210. package/packages/core/src/testing/index.ts +27 -0
  211. package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
  212. package/packages/core/src/testing/reduced-read-budget.ts +1873 -98
  213. package/packages/core/src/web/analytics-source.ts +303 -0
  214. package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
  215. package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
  216. package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
  217. package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
  218. package/packages/core/src/web/assets/app.css +1 -0
  219. package/packages/core/src/web/assets/app.js +9 -0
  220. package/packages/core/src/web/assets/manifest.json +31 -0
  221. package/packages/core/src/web/assets/theme.js +1 -0
  222. package/packages/core/src/web/bounded.ts +31 -0
  223. package/packages/core/src/web/http.ts +315 -0
  224. package/packages/core/src/web/hub.ts +160 -0
  225. package/packages/core/src/web/options.ts +38 -0
  226. package/packages/core/src/web/overview-source.ts +322 -0
  227. package/packages/core/src/web/page.ts +56 -0
  228. package/packages/core/src/web/protocol.ts +151 -0
  229. package/packages/core/src/web/read-only.ts +23 -0
  230. package/packages/core/src/web/repository-source.ts +35 -0
  231. package/packages/core/src/web/server.ts +97 -0
  232. package/skills/code-review/SKILL.md +10 -2
  233. package/skills/guide/SKILL.md +366 -52
  234. package/skills/guide/references/accounts.md +2 -1
  235. package/skills/guide/references/integration-tree.md +2 -2
  236. package/skills/guide/references/operator-api.md +134 -6
  237. package/skills/guide/references/optimization-nodes.md +69 -11
  238. package/skills/guide/references/plugin-authoring.md +37 -1
  239. package/skills/guide/references/remote-store-protocol.md +94 -13
  240. package/skills/guide/references/remote-ticket-protocol.md +40 -0
  241. package/skills/guide/references/restacking.md +20 -4
  242. package/skills/guide/references/setup.md +14 -2
  243. package/skills/guide/references/ticket-dependencies.md +10 -3
  244. package/skills/implement/SKILL.md +23 -4
  245. package/skills/operate/SKILL.md +134 -32
  246. package/skills/plan/SKILL.md +10 -4
  247. package/skills/plan-review/SKILL.md +9 -2
  248. package/skills/spec/SKILL.md +34 -8
  249. package/skills/tickets/SKILL.md +51 -5
  250. package/templates/hosted-service/package.json +2 -2
@@ -1,5 +1,5 @@
1
1
  import { missingAccountCredentials, reconcileMissingAccounts } from '../accounts/availability'
2
- import { readRepositoryFacts } from '../store/reduced-reads'
2
+ import { readBuildFacts, readRepositoryFacts } from '../store/reduced-reads'
3
3
  import { READ_CATALOG_IDENTITY } from '../events/compatibility'
4
4
  import { dispatchFrontendReducer } from '../cli/dispatch-repository-feed'
5
5
  import { catalogSnapshotName, loadReducerSnapshot } from '../store/snapshots'
@@ -7,7 +7,25 @@ import { expect } from 'bun:test'
7
7
  import { DispatchFrontend } from '../cli/dispatch-frontend'
8
8
  import type { DispatchChildResult } from '../cli/dispatch-process'
9
9
  import { createTerminalModeController } from '../cli/terminal-restore'
10
- import { DISPATCHER, humanActor } from '../events/envelope'
10
+ import { DISPATCHER, humanActor, KERNEL } from '../events/envelope'
11
+ import { WebModelHub } from '../web/hub'
12
+ import { readOnlyStore } from '../web/read-only'
13
+ import { OverviewFrameSource } from '../web/overview-source'
14
+ import { projectRepositoryFrame } from '../web/repository-source'
15
+ import { finishedOutcomeText } from '../cli/dashboard/vocabulary'
16
+ import { measureStoreReads } from './reduced-read-budget'
17
+ import type { WebServerStarter } from '../web/server'
18
+ import type { WebFrame } from '../web/protocol'
19
+ import { startDispatchWeb, type DispatchWeb } from '../cli/dispatch-web'
20
+ import { abDispatch } from '../cli/dispatch'
21
+ import { FakeForge } from '../ports/forge/fake'
22
+ import { FakeWorkspaceProvider } from '../ports/workspace/fake'
23
+ import { ScriptedAgentRunner, defaultTurnResult } from '../ports/runner/fake'
24
+ import { randomUuids, sequentialIds } from '../ids'
25
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
26
+ import { tmpdir } from 'node:os'
27
+ import { join } from 'node:path'
28
+ import { FakeRefreshScheduler } from './refresh-scheduler'
11
29
  import type { BuildStore } from '../store/types'
12
30
  import type { RepositoryEvent } from '../events/repository'
13
31
  import type { DashboardModel } from '../cli/dashboard/model'
@@ -55,6 +73,8 @@ export async function dispatchReadBudget(
55
73
  ): Promise<void> {
56
74
  await warmRestoreReadBudget(store, backing, true, fillDiscarded)
57
75
  await viewerReadBudget(store, backing)
76
+ await webReadBudget(store, backing, fillDiscarded)
77
+ await webPresentationParity(store, backing)
58
78
  const repo = '/dashboard-read-budget'
59
79
  await backing.ensureRepo(repo)
60
80
  const metrics = {
@@ -465,6 +485,8 @@ export async function dispatchReadBudget(
465
485
  expect(metrics.rows).toBe(before.rows)
466
486
  expect(await store.getRepoHighWater(retentionRepo)).toBe(position)
467
487
  }
488
+ // Last: its 100,000 seeded builds would slow every section after it.
489
+ await webOverviewReadBudget(store, backing)
468
490
  }
469
491
 
470
492
  /** Viewer cold/idle reads must reuse canonical values even without a frontend checkpoint. */
@@ -699,6 +721,787 @@ async function viewerReadBudget(store: BuildStore, backing: BuildStore): Promise
699
721
  }
700
722
  }
701
723
 
724
+ /** Store methods that scan history: their cost grows with build count or log
725
+ * length. `ab web` never calls them. */
726
+ const HISTORY_READS = new Set([
727
+ 'listBuilds',
728
+ 'listBuildsForRepo',
729
+ 'listBuildsPage',
730
+ 'getEvents',
731
+ 'getRepoEvents',
732
+ 'getRepoBuildDigests',
733
+ ])
734
+
735
+ /** The four targeted reads one visible build costs `ab web`, as labelled by
736
+ * `countingStore` with `slugs`. */
737
+ const overviewBuildReads = (slug: string) => [
738
+ `getArtifact:${slug}`,
739
+ `getBuild:${slug}`,
740
+ `getReducerValue:build:${slug}`,
741
+ `listStreams:${slug}`,
742
+ ]
743
+
744
+ /** Count every store call by name; reduced-value reads also by scope kind,
745
+ * with `reducers` by reducer name too, and with `slugs` every build-scope
746
+ * call also by the build it names. */
747
+ function countingStore(store: BuildStore, opts: { reducers?: boolean; slugs?: boolean } = {}) {
748
+ const calls: string[] = []
749
+ const label = (name: string, args: unknown[]): string => {
750
+ const scope = args[0] as string | { kind?: string; slug?: string; build?: string }
751
+ if (name === 'getReducerValue') {
752
+ const kind = (scope as { kind?: string }).kind
753
+ const slug = opts.slugs && kind === 'build' ? `:${(scope as { slug: string }).slug}` : ''
754
+ const reducer = opts.reducers ? `:${(args[1] as { reducer?: string }).reducer}` : ''
755
+ return `getReducerValue:${kind}${reducer}${slug}`
756
+ }
757
+ if (!opts.slugs) return name
758
+ if (name === 'listStreams' && typeof scope === 'object' && scope.build !== undefined)
759
+ return `${name}:${scope.build}`
760
+ if (name === 'getBuild' || name === 'getArtifact' || name === 'getEvents')
761
+ return `${name}:${String(scope)}`
762
+ return name
763
+ }
764
+ const proxy = new Proxy(store, {
765
+ get(target, key, receiver) {
766
+ const value = Reflect.get(target, key, receiver)
767
+ if (typeof value !== 'function') return value
768
+ return (...args: unknown[]) => {
769
+ calls.push(label(String(key), args))
770
+ return Reflect.apply(value, target, args)
771
+ }
772
+ },
773
+ })
774
+ const histogram = () => {
775
+ const counts: Record<string, number> = {}
776
+ for (const name of [...calls].sort()) counts[name] = (counts[name] ?? 0) + 1
777
+ return counts
778
+ }
779
+ return { proxy, calls, histogram }
780
+ }
781
+
782
+ /**
783
+ * `ab web`'s shared refresh loop (RFC 0007 §9.3): with no browser connected
784
+ * it reads nothing; with one or ten connected, each tick reads one change
785
+ * position while nothing changes; the idle cost is the same at 100 and
786
+ * 100,000 repository events and at 2 and 200 builds; a change to one build
787
+ * reads that build only; and no tick ever scans history. The overview's
788
+ * 100,000-build axis is `webOverviewReadBudget`, which `dispatchReadBudget`
789
+ * runs last.
790
+ */
791
+ async function webReadBudget(
792
+ store: BuildStore,
793
+ backing: BuildStore,
794
+ fill?: (repo: string, count: number) => Promise<void>,
795
+ ): Promise<void> {
796
+ const slices = countJournalSlices(backing)
797
+ const originalEvents = backing.getRepoEvents.bind(backing)
798
+ const originalSeed = backing.getRepoStateEvents.bind(backing)
799
+ let rawCalls = 0
800
+ backing.getRepoEvents = async (...args) => {
801
+ rawCalls++
802
+ return originalEvents(...args)
803
+ }
804
+ backing.getRepoStateEvents = async (...args) => {
805
+ rawCalls++
806
+ return originalSeed(...args)
807
+ }
808
+ // Idle histograms per configuration; every journal length × build count cell must match.
809
+ const reference = new Map<boolean, Record<string, number>>()
810
+ const IDLE_MS = 25_000
811
+ try {
812
+ for (const length of [100, 100_000]) {
813
+ for (const configured of [false, true]) {
814
+ const repo = `/web-budget-${length}-${configured ? 'configured' : 'unconfigured'}`
815
+ await backing.ensureRepo(repo)
816
+ if (fill !== undefined) await fill(repo, length)
817
+ else
818
+ for (let i = 0; i < length; i++)
819
+ await backing.appendRepo(repo, {
820
+ actor: humanActor('budget'),
821
+ type: 'dispatcher.intake-set',
822
+ payload: { enabled: i % 2 === 0 },
823
+ })
824
+ if (configured) {
825
+ const config = await backing.putRepoArtifact(repo, {
826
+ kind: 'config',
827
+ content: JSON.stringify(OVERVIEW_BUDGET_CONFIG),
828
+ })
829
+ await backing.appendRepo(repo, {
830
+ actor: DISPATCHER,
831
+ type: 'dispatcher.run-started',
832
+ payload: {
833
+ run: 'web-budget',
834
+ pid: 1,
835
+ roleWarnings: ['role implement has no model'],
836
+ effectiveConfig: { kind: config.kind, rev: config.revision },
837
+ },
838
+ })
839
+ }
840
+ // The one canonical materialization is allowed once, never once per tab.
841
+ await readRepositoryFacts(store, repo)
842
+ let created = 0
843
+ for (const builds of [2, 200]) {
844
+ for (; created < builds; created++) {
845
+ const slug = `web-budget-${length}-${configured ? 'c' : 'u'}-${created}`
846
+ await backing.createBuild({ slug, repo })
847
+ await backing.append(slug, {
848
+ actor: KERNEL,
849
+ type: 'runner.attached',
850
+ payload: { instance: `runner-${created}`, host: 'budget', resumedFromSeq: 0 },
851
+ })
852
+ }
853
+ const frames: string[][] = []
854
+ for (const subscribers of [1, 10]) {
855
+ const counter = countingStore(store, { slugs: true })
856
+ const time = new FakeRefreshScheduler()
857
+ const hub = new WebModelHub({
858
+ source: new OverviewFrameSource(readOnlyStore(counter.proxy), repo),
859
+ networkReads: store.networkReads === true,
860
+ scheduler: time,
861
+ })
862
+ // 1. No subscriber: no read and no timer, however long it idles.
863
+ await time.advance(60_000)
864
+ expect(counter.calls).toEqual([])
865
+ expect(time.tasks.size).toBe(0)
866
+
867
+ const received = Array.from({ length: subscribers }, () => [] as string[])
868
+ const offs = received.map((list) => hub.subscribe((json) => list.push(json)))
869
+ await hub.join()
870
+ // 2. Idle ticks after the first read only the change position.
871
+ counter.calls.length = 0
872
+ slices?.reset()
873
+ rawCalls = 0
874
+ await time.advance(IDLE_MS)
875
+ await hub.join()
876
+ const idle = counter.histogram()
877
+ expect(Object.keys(idle)).toEqual(['getRepoChangePosition'])
878
+ expect(slices?.rows() ?? 0).toBe(0)
879
+ expect(rawCalls).toBe(0)
880
+ // 4/5. Flat in tab count, history and build count.
881
+ const expected = reference.get(configured)
882
+ if (expected === undefined) reference.set(configured, idle)
883
+ else expect(idle).toEqual(expected)
884
+
885
+ // 6. Build activity moves the position; the next tick reads at most
886
+ // one saved repository value, no journal rows and, with a config,
887
+ // that build's targeted reads only.
888
+ counter.calls.length = 0
889
+ slices?.reset()
890
+ const touched = `web-budget-${length}-${configured ? 'c' : 'u'}-0`
891
+ await backing.append(touched, {
892
+ actor: KERNEL,
893
+ type: 'runner.attached',
894
+ payload: { instance: 'runner-again', host: 'budget', resumedFromSeq: 0 },
895
+ })
896
+ await time.advance(5_000)
897
+ await hub.join()
898
+ const moved = counter.histogram()
899
+ expect(moved.getRepo ?? 0).toBeLessThanOrEqual(1)
900
+ expect(moved['getReducerValue:repo'] ?? 0).toBeLessThanOrEqual(1)
901
+ const {
902
+ getRepoChangePosition: _position,
903
+ getRepo: _repo,
904
+ 'getReducerValue:repo': _facts,
905
+ ...buildScope
906
+ } = moved
907
+ expect(buildScope).toEqual(
908
+ configured
909
+ ? Object.fromEntries(
910
+ ['listBuildsChangedSince', ...overviewBuildReads(touched)].map((name) => [
911
+ name,
912
+ 1,
913
+ ]),
914
+ )
915
+ : {},
916
+ )
917
+ expect(slices?.rows() ?? 0).toBe(0)
918
+ expect(rawCalls).toBe(0)
919
+ // One appended repository event costs one journal row.
920
+ counter.calls.length = 0
921
+ slices?.reset()
922
+ await backing.appendRepo(repo, {
923
+ actor: humanActor('budget'),
924
+ type: 'dispatcher.pause-set',
925
+ payload: { enabled: created % 2 === 0 },
926
+ })
927
+ await time.advance(5_000)
928
+ await hub.join()
929
+ if (slices !== undefined) expect(slices.rows()).toBe(1)
930
+ expect(rawCalls).toBe(0)
931
+ const changed = counter.histogram()
932
+ expect(changed.getRepo).toBe(1)
933
+ expect(changed['getReducerValue:repo']).toBe(1)
934
+
935
+ // 3. Never a history scan, and every read goes through the guard.
936
+ for (const name of counter.calls) expect(HISTORY_READS.has(name)).toBe(false)
937
+ // Every subscriber received the same frames.
938
+ for (const list of received) expect(list).toEqual(received[0]!)
939
+ frames.push(received[0]!)
940
+
941
+ // 7. After the last tab leaves, nothing more is read.
942
+ for (const off of offs) off()
943
+ expect(hub.subscribers).toBe(0)
944
+ counter.calls.length = 0
945
+ await time.advance(60_000)
946
+ expect(counter.calls).toEqual([])
947
+ expect(time.tasks.size).toBe(0)
948
+ hub.close()
949
+ }
950
+ expect(frames[0]!.length).toBeGreaterThan(0)
951
+ }
952
+ }
953
+ }
954
+ } finally {
955
+ slices?.restore()
956
+ backing.getRepoEvents = originalEvents
957
+ backing.getRepoStateEvents = originalSeed
958
+ }
959
+ }
960
+
961
+ /** A minimal effective config the dashboard can project rows against. */
962
+ const OVERVIEW_BUDGET_CONFIG = {
963
+ capacity: 4,
964
+ roles: { default: { runtime: 'claude' } },
965
+ tickets: { source: 'file', readyState: 'ready' },
966
+ }
967
+
968
+ /**
969
+ * `ab web`'s overview costs the same at 100 and 100,000 builds (5 live, the
970
+ * rest finished): a fresh process reads the `buildRoster` rollup and only the
971
+ * live builds; an idle poll reads the change position; a change to one build
972
+ * reads that build only, plus one roster read when the build starts or
973
+ * finishes, including one created and finished between two polls; and no
974
+ * read scans history. Row metrics need a memory backing, so other backings
975
+ * skip it.
976
+ */
977
+ async function webOverviewReadBudget(store: BuildStore, backing: BuildStore): Promise<void> {
978
+ const { MemoryBuildStore } = await import('../store/memory')
979
+ if (!(backing instanceof MemoryBuildStore)) return
980
+ type Phase = { calls: Record<string, number>; rows: number; repoRows: number }
981
+ const results: Record<number, Record<string, Phase>> = {}
982
+ // A later completion than every seeded one, so it sorts first.
983
+ const later = () => new Promise((resolve) => setTimeout(resolve, 2))
984
+ for (const n of [100, 100_000]) {
985
+ const repo = `/web-overview-budget-${n}`
986
+ // Slugs are store-wide; histograms drop this prefix so sizes compare.
987
+ const prefix = `overview-${n}-`
988
+ const live = (i: number) => `${prefix}live-${i}`
989
+ await backing.ensureRepo(repo)
990
+ const create = (slug: string) =>
991
+ backing.createBuild({
992
+ slug,
993
+ repo,
994
+ created: {
995
+ actor: DISPATCHER,
996
+ type: 'build.created',
997
+ payload: { ticket: { source: 'file', id: slug, title: slug }, repo, baseBranch: 'main' },
998
+ },
999
+ })
1000
+ const complete = (slug: string, outcome: 'merged' | 'abandoned' = 'merged') =>
1001
+ backing.append(slug, { actor: DISPATCHER, type: 'build.completed', payload: { outcome } })
1002
+ for (let i = 0; i < n - 5; i++) {
1003
+ const slug = `${prefix}done-${String(i).padStart(6, '0')}`
1004
+ await create(slug)
1005
+ // Every fourth build aborts, then finishes its cleanup.
1006
+ if (i % 4 === 3) {
1007
+ await backing.append(slug, { actor: KERNEL, type: 'build.aborted', payload: {} })
1008
+ await complete(slug, 'abandoned')
1009
+ } else await complete(slug)
1010
+ }
1011
+ for (let i = 0; i < 5; i++) await create(live(i))
1012
+ const config = await backing.putRepoArtifact(repo, {
1013
+ kind: 'config',
1014
+ content: JSON.stringify(OVERVIEW_BUDGET_CONFIG),
1015
+ })
1016
+ await backing.appendRepo(repo, {
1017
+ actor: DISPATCHER,
1018
+ type: 'dispatcher.run-started',
1019
+ payload: {
1020
+ run: 'web-overview-budget',
1021
+ pid: 1,
1022
+ roleWarnings: [],
1023
+ effectiveConfig: { kind: config.kind, rev: config.revision },
1024
+ },
1025
+ })
1026
+ // The canonical materializations happen once, before any measured read.
1027
+ await readRepositoryFacts(store, repo)
1028
+ await store.getReducerValue({ kind: 'rollup', repo }, { reducer: 'buildRoster' })
1029
+ for (let i = 0; i < 5; i++) await readBuildFacts(store, live(i))
1030
+
1031
+ const counter = countingStore(store, { slugs: true })
1032
+ // A fresh process: no state but the saved values.
1033
+ const source = new OverviewFrameSource(readOnlyStore(counter.proxy), repo)
1034
+ const phases: Record<string, Phase> = {}
1035
+ let frame!: Awaited<ReturnType<OverviewFrameSource['read']>>['frame']
1036
+ const measure = async (phase: string) => {
1037
+ counter.calls.length = 0
1038
+ const metrics = await measureStoreReads(backing, async () => {
1039
+ frame = (await source.read()).frame
1040
+ })
1041
+ for (const name of counter.calls) expect(HISTORY_READS.has(name)).toBe(false)
1042
+ const calls = Object.fromEntries(
1043
+ Object.entries(counter.histogram()).map(([name, count]) => [
1044
+ name.replaceAll(prefix, ''),
1045
+ count,
1046
+ ]),
1047
+ )
1048
+ phases[phase] = { calls, rows: metrics.rows, repoRows: metrics.repoRows }
1049
+ return phases[phase]!
1050
+ }
1051
+ const buildScope = (calls: Record<string, number>) =>
1052
+ Object.fromEntries(
1053
+ Object.entries(calls).filter(
1054
+ ([name]) =>
1055
+ name.includes(':') &&
1056
+ name !== 'getReducerValue:repo' &&
1057
+ name !== 'getReducerValue:rollup',
1058
+ ),
1059
+ )
1060
+ // Expected reads name builds without the prefix.
1061
+ const reads = (...slugs: string[]) =>
1062
+ Object.fromEntries(
1063
+ slugs
1064
+ .map((slug) => slug.replace(prefix, ''))
1065
+ .flatMap(overviewBuildReads)
1066
+ .map((name) => [name, 1]),
1067
+ )
1068
+ const named = (calls: Record<string, number>, slug: string) =>
1069
+ Object.keys(buildScope(calls)).every((name) => name.endsWith(`:${slug.replace(prefix, '')}`))
1070
+
1071
+ // (a) The first read: the roster plus the five live builds.
1072
+ const first = await measure('first')
1073
+ expect(first.calls['getReducerValue:rollup']).toBe(1)
1074
+ expect(buildScope(first.calls)).toEqual(reads(...[0, 1, 2, 3, 4].map(live)))
1075
+ expect(first.rows).toBe(0)
1076
+ expect(first.repoRows).toBe(0)
1077
+ expect(frame.overview!.active.length + frame.overview!.queued.length).toBe(5)
1078
+ expect(frame.overview!.finished).toHaveLength(10)
1079
+
1080
+ // (b) Idle: the change position only.
1081
+ expect(await measure('idle')).toEqual({
1082
+ calls: { getRepoChangePosition: 1 },
1083
+ rows: 0,
1084
+ repoRows: 0,
1085
+ })
1086
+
1087
+ // (c) One event on a live build: that build's reads and its one new row.
1088
+ await backing.append(live(0), {
1089
+ actor: KERNEL,
1090
+ type: 'runner.attached',
1091
+ payload: { instance: 'runner-0', host: 'budget', resumedFromSeq: 0 },
1092
+ })
1093
+ const event = await measure('event')
1094
+ expect(buildScope(event.calls)).toEqual(reads(live(0)))
1095
+ expect(event.calls['getReducerValue:rollup']).toBeUndefined()
1096
+ expect(event.rows).toBe(1)
1097
+
1098
+ // (d) A live build completes: its reads plus one roster read.
1099
+ await later()
1100
+ await complete(live(1))
1101
+ const completion = await measure('completion')
1102
+ expect(named(completion.calls, live(1))).toBe(true)
1103
+ expect(completion.calls['getReducerValue:rollup']).toBe(1)
1104
+ const shown = () =>
1105
+ [...frame.overview!.active, ...frame.overview!.queued].map((row) => row.slug)
1106
+ expect(shown()).not.toContain(live(1))
1107
+ expect(frame.overview!.finished[0]).toMatchObject({
1108
+ slug: live(1),
1109
+ word: finishedOutcomeText('merged').word,
1110
+ })
1111
+
1112
+ // (e) A new build: its reads plus one roster read.
1113
+ await create(`${prefix}new-0`)
1114
+ const created = await measure('created')
1115
+ expect(buildScope(created.calls)).toEqual(reads(`${prefix}new-0`))
1116
+ expect(created.calls['getReducerValue:rollup']).toBe(1)
1117
+ expect(shown()).toContain(`${prefix}new-0`)
1118
+
1119
+ // (f) A build created and completed between two reads.
1120
+ await later()
1121
+ const blinked = `${prefix}blink-0`
1122
+ await create(blinked)
1123
+ await complete(blinked)
1124
+ const blink = await measure('blink')
1125
+ expect(Object.keys(buildScope(blink.calls)).every((name) => name.endsWith(':blink-0'))).toBe(
1126
+ true,
1127
+ )
1128
+ expect(blink.calls['getReducerValue:rollup']).toBe(1)
1129
+ expect(frame.overview!.finished[0]).toMatchObject({
1130
+ slug: blinked,
1131
+ word: finishedOutcomeText('merged').word,
1132
+ })
1133
+ expect(shown()).not.toContain(blinked)
1134
+ expect(await measure('after')).toEqual({
1135
+ calls: { getRepoChangePosition: 1 },
1136
+ rows: 0,
1137
+ repoRows: 0,
1138
+ })
1139
+ results[n] = phases
1140
+ }
1141
+ expect(results[100_000]).toEqual(results[100]!)
1142
+ }
1143
+
1144
+ /** Subscribers to a push hub: one from the start, ten more joining mid-run. */
1145
+ class WebSubscribers {
1146
+ readonly early: string[] = []
1147
+ readonly late: string[][] = []
1148
+ /** Frames handed to the hub, including unchanged ones it does not fan out. */
1149
+ published = 0
1150
+ constructor(private readonly hub: DispatchWeb['hub']) {
1151
+ const publish = hub.publish.bind(hub)
1152
+ hub.publish = (frame) => {
1153
+ this.published++
1154
+ publish(frame)
1155
+ }
1156
+ hub.subscribe((json) => this.early.push(json))
1157
+ }
1158
+ join(): void {
1159
+ for (let i = 0; i < 10; i++) {
1160
+ const list: string[] = []
1161
+ this.late.push(list)
1162
+ this.hub.subscribe((json) => list.push(json))
1163
+ }
1164
+ }
1165
+ /** Every subscriber saw the same frames from when it joined, ending at the
1166
+ * repository frame (header and notice) for the repository's current facts. */
1167
+ async expectConsistent(store: BuildStore, repo: string): Promise<void> {
1168
+ expect(this.early.length).toBeGreaterThan(0)
1169
+ expect(this.late).toHaveLength(10)
1170
+ for (const list of this.late) {
1171
+ expect(list).toEqual(this.late[0]!)
1172
+ expect(list.length).toBeGreaterThan(0)
1173
+ expect(this.early.slice(this.early.length - list.length)).toEqual(list)
1174
+ }
1175
+ const facts = (await readRepositoryFacts(store, repo)).value
1176
+ // The change position is the browser's refetch signal, stamped on top.
1177
+ const { position: _position, ...last } = JSON.parse(this.early.at(-1)!) as WebFrame
1178
+ expect(last).toEqual(JSON.parse(JSON.stringify(projectRepositoryFrame(repo, facts).frame)))
1179
+ }
1180
+ }
1181
+
1182
+ interface ParityContext {
1183
+ /** The counted store the run must read through. */
1184
+ store: BuildStore
1185
+ repo: string
1186
+ /** Absent for the run without a web UI. Binds no socket. */
1187
+ start: WebServerStarter | undefined
1188
+ /** The web a frontend mode serves, as `abDispatch` would start it. */
1189
+ openWeb(): Promise<DispatchWeb | undefined>
1190
+ /** Ten more browser tabs connect. */
1191
+ join(): void
1192
+ }
1193
+
1194
+ /**
1195
+ * `ab dispatch --web` adds no store reads beyond its frames' change position
1196
+ * (RFC 0007 §4.4, §9.3). In each mode the same script runs twice on fresh,
1197
+ * identical repositories, once without the web UI and once with one
1198
+ * subscriber from the start and ten joining mid-run. The store-call
1199
+ * histograms and journal rows must be equal, except that the kernel path,
1200
+ * whose journal refresh samples no position, reads one
1201
+ * `getRepoChangePosition` per frame it publishes to a connected browser; the
1202
+ * frontends pass the position their refresh sampled. The frame the web
1203
+ * serves must be the repository frame for the repository's facts: `ab
1204
+ * dispatch --web` pushes the header and notice, not the overview.
1205
+ */
1206
+ async function webPresentationParity(store: BuildStore, backing: BuildStore): Promise<void> {
1207
+ const slices = countJournalSlices(backing)
1208
+ const parity = async (
1209
+ mode: string,
1210
+ prepare: (repo: string) => Promise<void>,
1211
+ run: (context: ParityContext) => Promise<void>,
1212
+ ) => {
1213
+ const results: { calls: Record<string, number>; rows: number }[] = []
1214
+ let frames = 0
1215
+ for (const withWeb of [false, true]) {
1216
+ const repo = `https://github.com/budget/web-parity-${mode}-${withWeb ? 'web' : 'plain'}`
1217
+ await backing.ensureRepo(repo)
1218
+ await prepare(repo)
1219
+ // The one canonical materialization precedes either run.
1220
+ await readRepositoryFacts(store, repo)
1221
+ const counter = countingStore(store, { reducers: true })
1222
+ let subscribers: WebSubscribers | undefined
1223
+ const start: WebServerStarter = async (opts) => {
1224
+ subscribers = new WebSubscribers(opts.hub)
1225
+ return { url: 'http://127.0.0.1:1/', port: 1, stop: async () => {} }
1226
+ }
1227
+ slices?.reset()
1228
+ await run({
1229
+ store: counter.proxy,
1230
+ repo,
1231
+ start: withWeb ? start : undefined,
1232
+ openWeb: async () =>
1233
+ withWeb
1234
+ ? startDispatchWeb({
1235
+ options: { port: 0, json: true },
1236
+ repo,
1237
+ env: {},
1238
+ stdout: () => {},
1239
+ stderr: () => {},
1240
+ start,
1241
+ })
1242
+ : undefined,
1243
+ join: () => subscribers?.join(),
1244
+ })
1245
+ const rows = slices?.rows() ?? 0
1246
+ if (withWeb) {
1247
+ await subscribers!.expectConsistent(store, repo)
1248
+ frames = subscribers!.published
1249
+ }
1250
+ const calls = counter.histogram()
1251
+ // The frontend's upgrade-release check runs on a wall-clock timer, not
1252
+ // per refresh, so a slow run may add one; it is not a presentation read.
1253
+ delete calls['getReducerValue:repo:dispatchUpgrade']
1254
+ results.push({ calls, rows })
1255
+ }
1256
+ if (mode === 'kernel') {
1257
+ const position = (result: { calls: Record<string, number> }) => {
1258
+ const count = result.calls.getRepoChangePosition ?? 0
1259
+ delete result.calls.getRepoChangePosition
1260
+ return count
1261
+ }
1262
+ const added = position(results[1]!) - position(results[0]!)
1263
+ // At most one per frame handed to the hub (it fans out only changed
1264
+ // frames, so delivered frames undercount); at least one, so the signal
1265
+ // is real.
1266
+ expect(added).toBeGreaterThan(0)
1267
+ expect(added).toBeLessThanOrEqual(frames)
1268
+ }
1269
+ expect({ mode, ...results[1] }).toEqual({ mode, ...results[0] })
1270
+ }
1271
+ const configured = async (repo: string) => {
1272
+ const config = await backing.putRepoArtifact(repo, {
1273
+ kind: 'config',
1274
+ content: JSON.stringify({
1275
+ capacity: 4,
1276
+ roles: { default: { runtime: 'claude' } },
1277
+ tickets: { source: 'file', readyState: 'ready' },
1278
+ }),
1279
+ })
1280
+ await backing.appendRepo(repo, {
1281
+ actor: DISPATCHER,
1282
+ type: 'dispatcher.run-started',
1283
+ payload: {
1284
+ run: 'elsewhere',
1285
+ pid: 1,
1286
+ roleWarnings: [],
1287
+ effectiveConfig: { kind: config.kind, rev: config.revision },
1288
+ },
1289
+ })
1290
+ }
1291
+ const activity = (repo: string, enabled: boolean) =>
1292
+ backing.appendRepo(repo, {
1293
+ actor: humanActor('budget'),
1294
+ type: 'dispatcher.pause-set',
1295
+ payload: { enabled },
1296
+ })
1297
+ const terminal = (interactive: boolean) => ({
1298
+ columns: 100,
1299
+ rows: 24,
1300
+ interactive,
1301
+ write: () => {},
1302
+ modes: createTerminalModeController(
1303
+ () => {},
1304
+ () => {},
1305
+ ),
1306
+ })
1307
+
1308
+ // TTY dispatch: the frontend's own refreshes feed the web.
1309
+ await parity(
1310
+ 'tty',
1311
+ async () => {},
1312
+ async ({ store, repo, openWeb, join }) => {
1313
+ const web = await openWeb()
1314
+ let now = 0
1315
+ let finish!: (result: DispatchChildResult) => void
1316
+ let started!: () => void
1317
+ const startup = new Promise<void>((resolve) => {
1318
+ started = resolve
1319
+ })
1320
+ const frontend = new DispatchFrontend({
1321
+ repo,
1322
+ storeRef: 'test',
1323
+ store,
1324
+ env: {},
1325
+ once: true,
1326
+ clock: () => new Date(now),
1327
+ input: { start: () => () => {} },
1328
+ terminal: terminal(true),
1329
+ ...(web ? { web: { dispatch: web } } : {}),
1330
+ launchChild: () => {
1331
+ const completed = new Promise<DispatchChildResult>((resolve) => {
1332
+ finish = resolve
1333
+ })
1334
+ void configured(repo).then(started)
1335
+ return { completed, stop: async () => {} }
1336
+ },
1337
+ })
1338
+ const running = frontend.run()
1339
+ await startup
1340
+ const refresh = () => (frontend as unknown as { renderOnce(): Promise<void> }).renderOnce()
1341
+ await refresh()
1342
+ await activity(repo, true)
1343
+ now += 6000
1344
+ await refresh()
1345
+ join()
1346
+ await activity(repo, false)
1347
+ now += 6000
1348
+ await refresh()
1349
+ now += 500
1350
+ await refresh()
1351
+ finish({ outcome: 'normal', exitCode: 0 })
1352
+ await running
1353
+ await web?.close()
1354
+ },
1355
+ )
1356
+
1357
+ // Viewers: the viewer loop feeds the web. Without a TTY, abDispatch
1358
+ // discards the text frames; the sink here only marks the first frame.
1359
+ for (const interactive of [true, false])
1360
+ await parity(
1361
+ interactive ? 'tty-viewer' : 'plain-viewer',
1362
+ configured,
1363
+ async ({ store, repo, openWeb, join }) => {
1364
+ const web = await openWeb()
1365
+ let now = 0
1366
+ const controller = new AbortController()
1367
+ let painted!: () => void
1368
+ const firstFrame = new Promise<void>((resolve) => {
1369
+ painted = resolve
1370
+ })
1371
+ let outputs = 0
1372
+ const frontend = new DispatchFrontend({
1373
+ viewer: {},
1374
+ repo,
1375
+ store,
1376
+ storeRef: 'memory',
1377
+ env: {},
1378
+ once: false,
1379
+ signal: controller.signal,
1380
+ refreshScheduler: { now: () => now, set: () => undefined, clear: () => {} },
1381
+ clock: () => new Date(now),
1382
+ ...(interactive
1383
+ ? {}
1384
+ : {
1385
+ plainOutput: () => {
1386
+ if (++outputs >= 2) painted()
1387
+ },
1388
+ }),
1389
+ ...(web ? { web: { dispatch: web } } : {}),
1390
+ terminal: {
1391
+ ...terminal(interactive),
1392
+ write: () => {
1393
+ if (interactive) painted()
1394
+ },
1395
+ },
1396
+ input: { start: () => () => {} },
1397
+ launchChild: () => {
1398
+ throw new Error('viewer child')
1399
+ },
1400
+ })
1401
+ const readFrame = () => (frontend as unknown as { readFrame(): Promise<void> }).readFrame()
1402
+ const running = frontend.run()
1403
+ await firstFrame
1404
+ await activity(repo, true)
1405
+ now += 500
1406
+ await readFrame()
1407
+ join()
1408
+ await activity(repo, false)
1409
+ now += 500
1410
+ await readFrame()
1411
+ now += 500
1412
+ await readFrame()
1413
+ controller.abort()
1414
+ await running
1415
+ await web?.close()
1416
+ },
1417
+ )
1418
+
1419
+ // Plain dispatch: the kernel's repository-view refreshes feed the web.
1420
+ const directory = await mkdtemp(join(tmpdir(), 'ab-web-parity-'))
1421
+ try {
1422
+ await writeFile(
1423
+ join(directory, 'autobuild.toml'),
1424
+ `[roles.default]
1425
+ runtime = "claude"
1426
+ [tickets]
1427
+ source = "file"
1428
+ readyState = "ready"
1429
+ [verify]
1430
+ steps = []
1431
+ [finalize]
1432
+ steps = []
1433
+ `,
1434
+ )
1435
+ await parity(
1436
+ 'kernel',
1437
+ async () => {},
1438
+ async ({ store, repo, start, join: joinTabs }) => {
1439
+ const stop = new AbortController()
1440
+ let ticks = 0
1441
+ const stdout: string[] = []
1442
+ await abDispatch({
1443
+ targetRepo: directory,
1444
+ repo,
1445
+ env: {},
1446
+ exec: async (args) =>
1447
+ args[1] === 'remote'
1448
+ ? { stdout: `${repo}.git\n`, stderr: '', exitCode: 0 }
1449
+ : {
1450
+ stdout: `${directory}/.git\n${directory}/.git\n${directory}\n`,
1451
+ stderr: '',
1452
+ exitCode: 0,
1453
+ },
1454
+ stdout: (line) => stdout.push(line),
1455
+ stderr: () => {},
1456
+ once: false,
1457
+ plain: true,
1458
+ signal: stop.signal,
1459
+ ...(start ? { web: { port: 0, json: true, start } } : {}),
1460
+ sleep: async () => {
1461
+ ticks++
1462
+ if (ticks === 1) joinTabs()
1463
+ if (ticks < 3) await activity(repo, ticks % 2 === 0)
1464
+ else stop.abort()
1465
+ },
1466
+ storeRef: '/budget',
1467
+ wire: () => ({
1468
+ store,
1469
+ storeRef: '/budget',
1470
+ tickets: new FakeTicketSource([]),
1471
+ forge: new FakeForge(),
1472
+ workspaces: new FakeWorkspaceProvider({ root: '/parity-workspaces', mode: 'logical' }),
1473
+ buildExecution: {
1474
+ start: () => {
1475
+ throw new Error('no builds in web parity')
1476
+ },
1477
+ },
1478
+ runtimes: {
1479
+ claude: {
1480
+ runner: new ScriptedAgentRunner({ script: () => defaultTurnResult() }),
1481
+ servesModels: [],
1482
+ },
1483
+ },
1484
+ ids: sequentialIds(),
1485
+ uuids: randomUuids(),
1486
+ clock: () => new Date(1000),
1487
+ }),
1488
+ })
1489
+ expect(ticks).toBe(3)
1490
+ // Under --web the URL line is the plain kernel's only stdout; without
1491
+ // it the line-oriented presentation still prints.
1492
+ if (start) {
1493
+ expect(stdout).toHaveLength(1)
1494
+ expect(JSON.parse(stdout[0] ?? '{}').url).toBe('http://127.0.0.1:1/')
1495
+ } else {
1496
+ expect(stdout.some((line) => line.includes('watching'))).toBe(true)
1497
+ }
1498
+ },
1499
+ )
1500
+ } finally {
1501
+ await rm(directory, { recursive: true, force: true })
1502
+ }
1503
+ }
1504
+
702
1505
  /** Script a minute at both launcher cadences using the real runtime reader and
703
1506
  * launcher cache. Each helper gets a fresh facade; private reads use that same
704
1507
  * instrumented receiver rather than escaping into an uncounted reducer. */
@@ -1180,6 +1983,293 @@ export async function ticketPageReadBudget(
1180
1983
  }
1181
1984
  }
1182
1985
 
1986
+ /** One ticket of a search-budget population: fixed-width id and title, a body
1987
+ * of at least 1 KiB, and strides that give each budget query more than two
1988
+ * pages of matches. The pattern repeats every 60 numbers, so the newest
1989
+ * matches of 100 and 100,000 tickets carry the same states and labels. */
1990
+ export interface TicketSearchRow {
1991
+ number: number
1992
+ id: string
1993
+ title: string
1994
+ body: string
1995
+ state: string
1996
+ labels: string[]
1997
+ }
1998
+
1999
+ const SEARCH_PAD = 'x'.repeat(1024)
2000
+ const SEARCH_BODY = `Body ${SEARCH_PAD}`
2001
+ const SEARCH_NEEDLE_BODY = `Body with a needle in it ${SEARCH_PAD}`
2002
+
2003
+ export function ticketSearchRows(population: number): TicketSearchRow[] {
2004
+ return Array.from({ length: population }, (_, i) => {
2005
+ const number = i + 1
2006
+ const n = String(number).padStart(6, '0')
2007
+ return {
2008
+ number,
2009
+ id: `ENG-${n}`,
2010
+ title: `${number % 5 === 0 ? 'Needle' : 'ticket'} ${n}`,
2011
+ body: number % 3 === 0 ? SEARCH_NEEDLE_BODY : SEARCH_BODY,
2012
+ state: number % 4 < 2 ? 'Ready' : 'Triage',
2013
+ labels: number % 2 === 0 ? ['dup'] : [],
2014
+ }
2015
+ })
2016
+ }
2017
+
2018
+ /** Same shape as `TicketPageFixture`: a fresh source over `tickets`;
2019
+ * `native` is a service answering `search`, `predating` one without it. */
2020
+ export type TicketSearchFixture = TicketPageFixture
2021
+
2022
+ /** A search page (per operator or agent request) through a hosted service
2023
+ * that searches costs exactly one `search` request and one bounded statement,
2024
+ * state-filtered pages and state refusals included, and ships no bodies, at
2025
+ * 100 and 100,000 tickets. Against a service predating search, the caller
2026
+ * refuses with `TicketSearchUnsupported` before any request: nothing is
2027
+ * listed. */
2028
+ export async function ticketSearchReadBudget(
2029
+ fixture: (
2030
+ population: number,
2031
+ mode: 'native' | 'predating',
2032
+ tickets: TicketSearchRow[],
2033
+ ) => Promise<TicketSearchFixture>,
2034
+ ): Promise<void> {
2035
+ const { searchTickets, searchTerms, matchesSearch, TicketSearchUnsupported } = await import(
2036
+ '../ports/tickets/search'
2037
+ )
2038
+ const populations = [100, 100_000] as const
2039
+ const limit = 5
2040
+ const queries = [
2041
+ { key: 'all' },
2042
+ { key: 'labels', labels: ['dup'] },
2043
+ { key: 'state', state: 'Ready' },
2044
+ { key: 'folded state', state: 'ready' },
2045
+ ] as const
2046
+ const bytes = new Map<string, number>()
2047
+ for (const population of populations) {
2048
+ const tickets = ticketSearchRows(population)
2049
+ const newestFirst = [...tickets].reverse()
2050
+ const terms = searchTerms('NEEDLE')
2051
+ const { source, reset, statements, requests } = await fixture(population, 'native', tickets)
2052
+ expect(source.search).toBeDefined()
2053
+ for (const query of queries) {
2054
+ const state = 'state' in query ? 'Ready' : undefined
2055
+ const labels = 'labels' in query ? query.labels : []
2056
+ const expected = newestFirst
2057
+ .filter(
2058
+ (ticket) =>
2059
+ (state === undefined || ticket.state === state) &&
2060
+ labels.every((label) => ticket.labels.includes(label)) &&
2061
+ matchesSearch(ticket, terms),
2062
+ )
2063
+ .slice(0, 2 * limit)
2064
+ .map((ticket) => ticket.id)
2065
+ let cursor: string | undefined
2066
+ const seen: string[] = []
2067
+ for (const pageNumber of [1, 2]) {
2068
+ reset()
2069
+ const page = await searchTickets(source, {
2070
+ text: 'NEEDLE',
2071
+ limit,
2072
+ ...('state' in query ? { state: query.state } : {}),
2073
+ ...('labels' in query ? { labels: [...query.labels] } : {}),
2074
+ ...(cursor !== undefined ? { cursor } : {}),
2075
+ })
2076
+ expect(requests().map((request) => request.operation)).toEqual(['search'])
2077
+ expect(statements()).toBe(1)
2078
+ expect(page.tickets).toHaveLength(limit)
2079
+ expect(page.cursor).toBeDefined()
2080
+ const size = requests().reduce((total, request) => total + request.bytes, 0)
2081
+ // A body is at least 1 KiB, so no page of five hits shipped one.
2082
+ expect(size).toBeLessThan(limit * 1024)
2083
+ bytes.set(`${population}:${query.key}:${pageNumber}`, size)
2084
+ seen.push(...page.tickets.map((hit) => hit.id))
2085
+ cursor = page.cursor
2086
+ }
2087
+ expect(seen).toEqual(expected)
2088
+ }
2089
+ reset()
2090
+ await expect(
2091
+ searchTickets(source, { text: 'NEEDLE', limit, state: 'nonexistent' }),
2092
+ ).rejects.toThrow(/unknown state "nonexistent"/)
2093
+ expect(requests().map((request) => request.operation)).toEqual(['search'])
2094
+ expect(statements()).toBe(1)
2095
+
2096
+ const predating = await fixture(population, 'predating', tickets)
2097
+ expect(predating.source.search).toBeUndefined()
2098
+ predating.reset()
2099
+ await expect(searchTickets(predating.source, { text: 'NEEDLE', limit })).rejects.toBeInstanceOf(
2100
+ TicketSearchUnsupported,
2101
+ )
2102
+ expect(predating.requests()).toEqual([])
2103
+ expect(predating.statements()).toBe(0)
2104
+ }
2105
+ // Only the cursor's digits grow with the population.
2106
+ const digits = String(populations[1]).length - String(populations[0]).length
2107
+ for (const query of queries)
2108
+ for (const pageNumber of [1, 2]) {
2109
+ const small = bytes.get(`${populations[0]}:${query.key}:${pageNumber}`)!
2110
+ const large = bytes.get(`${populations[1]}:${query.key}:${pageNumber}`)!
2111
+ expect(Math.abs(large - small)).toBeLessThanOrEqual(digits)
2112
+ }
2113
+ }
2114
+
2115
+ /** A provider-backed source over `tickets`, counting provider requests: each
2116
+ * entry is one request's sent and received byte sizes. */
2117
+ export interface TicketSearchRequestFixture {
2118
+ source: TicketSource
2119
+ reset(): void
2120
+ requests(): Array<{ request: number; response: number }>
2121
+ }
2122
+
2123
+ /** A search page through a provider-backed source (Linear, for one) costs
2124
+ * exactly one provider request, ships no bodies, returns the shared matcher's
2125
+ * newest-first matches, and costs the same bytes at 100 and 100,000 tickets. */
2126
+ export async function ticketSearchRequestBudget(
2127
+ fixture: (population: number, tickets: TicketSearchRow[]) => Promise<TicketSearchRequestFixture>,
2128
+ ): Promise<void> {
2129
+ const { searchTickets, searchTerms, matchesSearch } = await import('../ports/tickets/search')
2130
+ const populations = [100, 100_000] as const
2131
+ const limit = 5
2132
+ const queries = [
2133
+ { key: 'all' },
2134
+ { key: 'labels', labels: ['dup'] },
2135
+ { key: 'state', state: 'Ready' },
2136
+ ] as const
2137
+ const sizes = new Map<string, { request: number; response: number }>()
2138
+ for (const population of populations) {
2139
+ const tickets = ticketSearchRows(population)
2140
+ const newestFirst = [...tickets].reverse()
2141
+ const terms = searchTerms('NEEDLE')
2142
+ const { source, reset, requests } = await fixture(population, tickets)
2143
+ for (const query of queries) {
2144
+ const state = 'state' in query ? query.state : undefined
2145
+ const labels: readonly string[] = 'labels' in query ? query.labels : []
2146
+ const expected = newestFirst
2147
+ .filter(
2148
+ (ticket) =>
2149
+ (state === undefined || ticket.state === state) &&
2150
+ labels.every((label) => ticket.labels.includes(label)) &&
2151
+ matchesSearch(ticket, terms),
2152
+ )
2153
+ .slice(0, 2 * limit)
2154
+ .map((ticket) => ticket.id)
2155
+ let cursor: string | undefined
2156
+ const seen: string[] = []
2157
+ for (const pageNumber of [1, 2]) {
2158
+ reset()
2159
+ const page = await searchTickets(source, {
2160
+ text: 'NEEDLE',
2161
+ limit,
2162
+ ...(state !== undefined ? { state } : {}),
2163
+ ...(labels.length > 0 ? { labels: [...labels] } : {}),
2164
+ ...(cursor !== undefined ? { cursor } : {}),
2165
+ })
2166
+ const sent = requests()
2167
+ expect(sent).toHaveLength(1)
2168
+ expect(page.tickets).toHaveLength(limit)
2169
+ expect(page.cursor).toBeDefined()
2170
+ // A body is at least 1 KiB, so no page of five hits shipped one.
2171
+ expect(sent[0]!.response).toBeLessThan(limit * 1024)
2172
+ sizes.set(`${population}:${query.key}:${pageNumber}`, sent[0]!)
2173
+ seen.push(...page.tickets.map((hit) => hit.id))
2174
+ cursor = page.cursor
2175
+ }
2176
+ expect(seen).toEqual(expected)
2177
+ }
2178
+ }
2179
+ // Only a cursor's digits may grow with the population; cursors may be
2180
+ // encoded, so allow the encoded width of those digits.
2181
+ const digits = 2 * (String(populations[1]).length - String(populations[0]).length)
2182
+ for (const query of queries)
2183
+ for (const pageNumber of [1, 2]) {
2184
+ const small = sizes.get(`${populations[0]}:${query.key}:${pageNumber}`)!
2185
+ const large = sizes.get(`${populations[1]}:${query.key}:${pageNumber}`)!
2186
+ expect(Math.abs(large.request - small.request)).toBeLessThanOrEqual(digits)
2187
+ expect(Math.abs(large.response - small.response)).toBeLessThanOrEqual(digits)
2188
+ }
2189
+ }
2190
+
2191
+ /** A fresh provider-backed source over `tickets` whose provider requests are
2192
+ * recorded by operation; `idOf` maps a row to the id the source gave it. */
2193
+ export interface GitHubTicketSearchRequestFixture {
2194
+ source: TicketSource
2195
+ reset(): void
2196
+ requests(): { operation: string }[]
2197
+ idOf(row: TicketSearchRow): string
2198
+ }
2199
+
2200
+ /** A search page through a provider-backed source (GitHub issue search)
2201
+ * costs exactly one provider `search` request, filtered or not, with the
2202
+ * same request sequence at 100 and 100,000 tickets, newest filed first; a
2203
+ * cursor the source did not issue is refused before any request. */
2204
+ export async function githubTicketSearchRequestBudget(
2205
+ fixture: (
2206
+ population: number,
2207
+ tickets: TicketSearchRow[],
2208
+ ) => Promise<GitHubTicketSearchRequestFixture>,
2209
+ ): Promise<void> {
2210
+ const { searchTickets, searchTerms, matchesSearch, TicketSearchCursorInvalid } = await import(
2211
+ '../ports/tickets/search'
2212
+ )
2213
+ const { holdsState } = await import('../ports/tickets/lifecycle')
2214
+ const limit = 5
2215
+ const queries = [
2216
+ { key: 'all' },
2217
+ { key: 'labels', labels: ['dup'] },
2218
+ { key: 'state', state: 'Ready' },
2219
+ { key: 'folded state', state: 'ready' },
2220
+ { key: 'triage', state: 'Triage' },
2221
+ ] as const
2222
+ const sequences: string[][] = []
2223
+ for (const population of [100, 100_000]) {
2224
+ const tickets = ticketSearchRows(population)
2225
+ const newestFirst = [...tickets].reverse()
2226
+ const terms = searchTerms('NEEDLE')
2227
+ const { source, reset, requests, idOf } = await fixture(population, tickets)
2228
+ expect(source.search).toBeDefined()
2229
+ const sequence: string[] = []
2230
+ for (const query of queries) {
2231
+ const state = 'state' in query ? query.state : undefined
2232
+ const labels: readonly string[] = 'labels' in query ? query.labels : []
2233
+ const expected = newestFirst
2234
+ .filter(
2235
+ (ticket) =>
2236
+ (state === undefined || holdsState(ticket.state, state)) &&
2237
+ labels.every((label) => ticket.labels.includes(label)) &&
2238
+ matchesSearch(ticket, terms),
2239
+ )
2240
+ .slice(0, 2 * limit)
2241
+ .map(idOf)
2242
+ let cursor: string | undefined
2243
+ const seen: string[] = []
2244
+ for (const _page of [1, 2]) {
2245
+ reset()
2246
+ const page = await searchTickets(source, {
2247
+ text: 'NEEDLE',
2248
+ limit,
2249
+ ...(state !== undefined ? { state } : {}),
2250
+ ...(labels.length > 0 ? { labels: [...labels] } : {}),
2251
+ ...(cursor !== undefined ? { cursor } : {}),
2252
+ })
2253
+ const operations = requests().map((request) => request.operation)
2254
+ expect(operations).toEqual(['search'])
2255
+ sequence.push(...operations)
2256
+ expect(page.tickets).toHaveLength(limit)
2257
+ expect(page.cursor).toBeDefined()
2258
+ seen.push(...page.tickets.map((hit) => hit.id))
2259
+ cursor = page.cursor
2260
+ }
2261
+ expect(seen).toEqual(expected)
2262
+ }
2263
+ reset()
2264
+ await expect(
2265
+ searchTickets(source, { text: 'NEEDLE', limit, cursor: 'not-a-cursor' }),
2266
+ ).rejects.toBeInstanceOf(TicketSearchCursorInvalid)
2267
+ expect(requests()).toEqual([])
2268
+ sequences.push(sequence)
2269
+ }
2270
+ expect(sequences[1]).toEqual(sequences[0]!)
2271
+ }
2272
+
1183
2273
  /** Builds one dispatcher pass's observation inputs for a node build over a
1184
2274
  * fresh memory store, reporting which listing path the source decided on
1185
2275
  * before the pass; `observe` then observes the node with those inputs. */