@defrex/autobuild 1.17.0 → 1.19.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 (65) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +85 -11
  3. package/docs/architecture.md +57 -11
  4. package/docs/configuration.md +11 -3
  5. package/docs/dispatcher-hosting.md +5 -3
  6. package/docs/operator-api.md +14 -1
  7. package/docs/plugin-authoring.md +29 -1
  8. package/docs/remote-ticket-protocol.md +34 -1
  9. package/docs/restacking.md +5 -0
  10. package/docs/setup.md +9 -3
  11. package/docs/ticket-sources.md +28 -1
  12. package/docs/troubleshooting.md +15 -0
  13. package/docs/workspaces.md +1 -1
  14. package/package.json +4 -4
  15. package/packages/core/src/cli/dashboard/refresh.ts +8 -0
  16. package/packages/core/src/cli/dispatch.ts +2 -0
  17. package/packages/core/src/config/schema.ts +2 -1
  18. package/packages/core/src/events/catalog-identity.ts +3 -1
  19. package/packages/core/src/events/payloads.ts +7 -1
  20. package/packages/core/src/events/repository.ts +37 -1
  21. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/d41044cb2e54809c.json +194 -0
  22. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e012e9e8f3e82935.json +424 -0
  23. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e0f89f52e48cbf62.json +197 -0
  24. package/packages/core/src/kernel/janitor-failure.ts +1 -0
  25. package/packages/core/src/kernel/reducer-revisions.ts +9 -0
  26. package/packages/core/src/kernel/reducer.ts +6 -0
  27. package/packages/core/src/kernel/repository-read-facts.ts +9 -2
  28. package/packages/core/src/kernel/session-settlement.ts +82 -0
  29. package/packages/core/src/kernel/ticket-preparation.ts +10 -0
  30. package/packages/core/src/operator/registry.ts +64 -9
  31. package/packages/core/src/operator/tickets.ts +139 -25
  32. package/packages/core/src/plugin-sdk/index.ts +4 -0
  33. package/packages/core/src/plugins/manifest.ts +1 -1
  34. package/packages/core/src/ports/tickets/completion.ts +71 -0
  35. package/packages/core/src/ports/tickets/contract.ts +73 -0
  36. package/packages/core/src/ports/tickets/github-fake.ts +8 -0
  37. package/packages/core/src/ports/tickets/github-issues.ts +1 -0
  38. package/packages/core/src/ports/tickets/github.ts +18 -6
  39. package/packages/core/src/ports/tickets/hosted-index.ts +8 -0
  40. package/packages/core/src/ports/tickets/linear.ts +18 -2
  41. package/packages/core/src/ports/tickets/remote-protocol.ts +37 -8
  42. package/packages/core/src/ports/tickets/remote.ts +41 -3
  43. package/packages/core/src/ports/tickets/tree.ts +11 -1
  44. package/packages/core/src/ports/types.ts +32 -4
  45. package/packages/core/src/ports/workspace/vercel-sandbox.ts +78 -25
  46. package/packages/core/src/processes/build-runner.ts +100 -29
  47. package/packages/core/src/processes/dispatcher.ts +1016 -279
  48. package/packages/core/src/processes/execution-settlement.ts +30 -0
  49. package/packages/core/src/processes/pass-stages.ts +32 -6
  50. package/packages/core/src/store/reducer-value-shapes.json +8440 -8346
  51. package/packages/core/src/store/remote/released-clients.json +22 -0
  52. package/packages/core/src/store/remote/released-reducer-values/1.18.0.json +36436 -0
  53. package/packages/core/src/store/remote/released-reducer-values/1.19.0.json +36461 -0
  54. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  55. package/packages/core/src/testing/dispatch-read-budget.ts +143 -16
  56. package/packages/core/src/testing/index.ts +2 -0
  57. package/packages/core/src/testing/reduced-read-budget.ts +234 -2
  58. package/skills/guide/SKILL.md +45 -15
  59. package/skills/guide/references/operator-api.md +14 -1
  60. package/skills/guide/references/plugin-authoring.md +29 -1
  61. package/skills/guide/references/remote-ticket-protocol.md +34 -1
  62. package/skills/guide/references/restacking.md +5 -0
  63. package/skills/guide/references/setup.md +9 -3
  64. package/skills/operate/SKILL.md +18 -1
  65. package/templates/hosted-service/package.json +2 -2
@@ -8,14 +8,16 @@ import release5 from './1.14.0.json'
8
8
  import release6 from './1.15.0.json'
9
9
  import release7 from './1.16.0.json'
10
10
  import release8 from './1.17.0.json'
11
- import release9 from './1.2.0.json'
12
- import release10 from './1.3.0.json'
13
- import release11 from './1.4.0.json'
14
- import release12 from './1.5.0.json'
15
- import release13 from './1.6.0.json'
16
- import release14 from './1.7.0.json'
17
- import release15 from './1.8.0.json'
18
- import release16 from './1.9.0.json'
11
+ import release9 from './1.18.0.json'
12
+ import release10 from './1.19.0.json'
13
+ import release11 from './1.2.0.json'
14
+ import release12 from './1.3.0.json'
15
+ import release13 from './1.4.0.json'
16
+ import release14 from './1.5.0.json'
17
+ import release15 from './1.6.0.json'
18
+ import release16 from './1.7.0.json'
19
+ import release17 from './1.8.0.json'
20
+ import release18 from './1.9.0.json'
19
21
  import type { ReducerValueCatalog } from '../../reducer-value-validation'
20
22
  export interface ReleasedReducerValues extends ReducerValueCatalog {
21
23
  versions: Record<string, number>
@@ -30,12 +32,14 @@ export const RELEASED_REDUCER_VALUES: Readonly<Record<string, ReleasedReducerVal
30
32
  '1.15.0.json': release6,
31
33
  '1.16.0.json': release7,
32
34
  '1.17.0.json': release8,
33
- '1.2.0.json': release9,
34
- '1.3.0.json': release10,
35
- '1.4.0.json': release11,
36
- '1.5.0.json': release12,
37
- '1.6.0.json': release13,
38
- '1.7.0.json': release14,
39
- '1.8.0.json': release15,
40
- '1.9.0.json': release16,
35
+ '1.18.0.json': release9,
36
+ '1.19.0.json': release10,
37
+ '1.2.0.json': release11,
38
+ '1.3.0.json': release12,
39
+ '1.4.0.json': release13,
40
+ '1.5.0.json': release14,
41
+ '1.6.0.json': release15,
42
+ '1.7.0.json': release16,
43
+ '1.8.0.json': release17,
44
+ '1.9.0.json': release18,
41
45
  }
@@ -2144,35 +2144,74 @@ export async function ticketTargetingReadBudget(
2144
2144
  expect(costs[1]).toEqual(costs[0]!)
2145
2145
  }
2146
2146
 
2147
- /** One fixture per population and listing path: a fresh source over
2148
- * `population` tickets, all in `Ready`, none urgent. `native` is a service
2149
- * answering `list-page`; `fallback` is one predating it. `requests` are the
2150
- * ticket-service operations the source issued since `reset`, with their
2151
- * response sizes; window rows must not vary in size with the population. */
2147
+ /** One fixture per population and listing path. `native` is a service
2148
+ * answering `list-page` with completion criteria; `fallback` is one predating
2149
+ * `list-page`. For population `P` the backing store holds:
2150
+ *
2151
+ * - `P` `Ready` tickets, none urgent, filed one second apart;
2152
+ * - `P` older `Done` tickets completed in 2025, one second apart, every third
2153
+ * labelled `internal`;
2154
+ * - one node `ENG-900000` in `Doing`, titled `TICKET_PAGE_NODE_TITLE`;
2155
+ * - `TICKET_PAGE_RECENT_DONE` (9) recent `Done` tickets completed on
2156
+ * 2026-06-01, one second apart, every third labelled `internal`, all
2157
+ * targeting the node.
2158
+ *
2159
+ * Ids, titles and timestamps are fixed width, so a window's bytes do not
2160
+ * vary with the population. `requests` are the ticket-service operations the
2161
+ * source issued since `reset`, with their response sizes; `rowsExamined` is
2162
+ * the ticket rows the backing store examined since `reset`, across every
2163
+ * statement. */
2152
2164
  export interface TicketPageFixture {
2153
2165
  source: TicketSource
2154
2166
  reset(): void
2155
2167
  statements(): number
2156
2168
  requests(): { operation: string; bytes: number }[]
2169
+ rowsExamined(): number
2157
2170
  }
2158
2171
 
2172
+ /** The node title every `TicketPageFixture` population carries. */
2173
+ export const TICKET_PAGE_NODE_TITLE = 'node 900000'
2174
+ /** Recent done tickets in every `TicketPageFixture` population. */
2175
+ export const TICKET_PAGE_RECENT_DONE = 9
2176
+
2159
2177
  /** A paged operator listing (per operator request and per dashboard page view)
2160
2178
  * through a hosted service that pages natively costs one `list-page` request
2161
2179
  * whose statements are the same, and whose bytes differ only by the width of
2162
2180
  * the total's digits, at 10 and 10,000 tickets. Against a service predating it,
2163
- * the same listing reads every ticket through one `list-ready`. */
2181
+ * the same listing reads every ticket through one `list-ready`.
2182
+ *
2183
+ * A completion digest (per operator or agent request: `since`/`until`,
2184
+ * `excludeLabels`, order `completed`, `summary`) examines the same ticket
2185
+ * rows at 10 and 10,000, across every statement of the request, the
2186
+ * `states` prerequisite included, and reads no event. A range broader than
2187
+ * `TICKET_COMPLETION_SCAN_LIMIT` refuses after examining at most the cap
2188
+ * plus one rows, before any window statement. */
2164
2189
  export async function ticketPageReadBudget(
2165
2190
  fixture: (population: number, mode: 'native' | 'fallback') => Promise<TicketPageFixture>,
2166
2191
  ): Promise<void> {
2167
2192
  const { MemoryBuildStore } = await import('../store/memory')
2168
2193
  const { listOperatorTickets } = await import('../operator/tickets')
2169
2194
  const { ticketsSchema } = await import('../config/schema')
2170
- const tickets = ticketsSchema.parse({ source: 'hosted', teamKey: 'ENG', readyState: 'Ready' })
2195
+ const { TICKET_COMPLETION_SCAN_LIMIT, TicketCompletionRangeTooBroad } = await import(
2196
+ '../ports/tickets/completion'
2197
+ )
2198
+ const tickets = ticketsSchema.parse({
2199
+ source: 'hosted',
2200
+ teamKey: 'ENG',
2201
+ readyState: 'Ready',
2202
+ doneState: 'Done',
2203
+ })
2204
+ const contextFor = async () => ({ repo: 'repo', tickets, teamKey: 'ENG' })
2171
2205
  const populations = [10, 10_000] as const
2206
+ const recent = TICKET_PAGE_RECENT_DONE
2172
2207
  const costs = new Map<string, { statements: number; bytes: number; ids: string[] }>()
2208
+ const digests = new Map<
2209
+ string,
2210
+ { statements: number; bytes: number; stateBytes: number; rows: number; ids: string[] }
2211
+ >()
2173
2212
  for (const mode of ['native', 'fallback'] as const)
2174
2213
  for (const population of populations) {
2175
- const { source, reset, statements, requests } = await fixture(population, mode)
2214
+ const { source, reset, statements, requests, rowsExamined } = await fixture(population, mode)
2176
2215
  if (mode === 'native') expect(source.listPage).toBeDefined()
2177
2216
  else expect(source.listPage).toBeUndefined()
2178
2217
  for (const order of ['oldest', 'newest'] as const) {
@@ -2182,11 +2221,7 @@ export async function ticketPageReadBudget(
2182
2221
  repo: 'repo',
2183
2222
  state: 'Ready',
2184
2223
  page: { limit: 3, offset: 2, order },
2185
- backend: {
2186
- contextFor: async () => ({ repo: 'repo', tickets, teamKey: 'ENG' }),
2187
- sourceFor: () => source,
2188
- statesFor: () => ['Ready'],
2189
- },
2224
+ backend: { contextFor, sourceFor: () => source, statesFor: () => ['Ready'] },
2190
2225
  })
2191
2226
  expect(queue.tickets).toHaveLength(3)
2192
2227
  expect(queue.total).toBe(population)
@@ -2199,6 +2234,80 @@ export async function ticketPageReadBudget(
2199
2234
  ids: queue.tickets.map((ticket) => ticket.ref.id),
2200
2235
  })
2201
2236
  }
2237
+ // The completion digest, with the operator's `states` prerequisite
2238
+ // served by the source as production serves it.
2239
+ const backend = {
2240
+ contextFor,
2241
+ sourceFor: () => source,
2242
+ statesFor: async () =>
2243
+ source.listStates ? (await source.listStates()).map((state) => state.name) : ['Ready'],
2244
+ }
2245
+ for (const window of [
2246
+ { since: '2026-06-01T00:00:00Z', until: '2026-06-02T00:00:00Z' },
2247
+ { since: '2026-01-01T00:00:00Z' },
2248
+ ]) {
2249
+ reset()
2250
+ const counting = countingStore(new MemoryBuildStore())
2251
+ const queue = await listOperatorTickets({
2252
+ store: counting.proxy,
2253
+ repo: 'repo',
2254
+ state: 'Done',
2255
+ ...window,
2256
+ excludeLabels: ['internal'],
2257
+ summary: true,
2258
+ page: { limit: 3, order: 'completed' },
2259
+ backend,
2260
+ })
2261
+ expect(counting.calls).toEqual([])
2262
+ expect(
2263
+ requests()
2264
+ .map((request) => request.operation)
2265
+ .sort(),
2266
+ ).toEqual([mode === 'native' ? 'list-page' : 'list-ready', 'states'])
2267
+ expect(queue.total).toBe(recent - Math.ceil(recent / 3))
2268
+ expect(queue.tickets).toHaveLength(3)
2269
+ const times = queue.tickets.map((ticket) => Date.parse(ticket.resolvedAt!))
2270
+ for (let i = 1; i < times.length; i++) expect(times[i]!).toBeLessThan(times[i - 1]!)
2271
+ for (const ticket of queue.tickets) {
2272
+ expect('body' in ticket).toBe(false)
2273
+ expect(ticket.labels).not.toContain('internal')
2274
+ expect(ticket.targetTitle).toBe(TICKET_PAGE_NODE_TITLE)
2275
+ }
2276
+ const bytesOf = (states: boolean) =>
2277
+ requests()
2278
+ .filter((request) => (request.operation === 'states') === states)
2279
+ .reduce((total, request) => total + request.bytes, 0)
2280
+ digests.set(`${mode}:${population}:${window.until ?? 'open'}`, {
2281
+ statements: statements(),
2282
+ bytes: bytesOf(false),
2283
+ stateBytes: bytesOf(true),
2284
+ rows: rowsExamined(),
2285
+ ids: queue.tickets.map((ticket) => ticket.ref.id),
2286
+ })
2287
+ }
2288
+ if (mode !== 'native') continue
2289
+ // A range holding more rows than the cap: refused after the capped count
2290
+ // scan. A window statement would examine another capped scan, so an exact
2291
+ // row count of cap + 1 also proves no window ran.
2292
+ reset()
2293
+ const broad = listOperatorTickets({
2294
+ store: new MemoryBuildStore(),
2295
+ repo: 'repo',
2296
+ state: 'Done',
2297
+ since: '2025-01-01T00:00:00Z',
2298
+ page: { limit: 3, order: 'completed' },
2299
+ backend,
2300
+ })
2301
+ if (population + recent > TICKET_COMPLETION_SCAN_LIMIT) {
2302
+ const refusal = await broad.catch((error: unknown) => error)
2303
+ expect(refusal).toBeInstanceOf(TicketCompletionRangeTooBroad)
2304
+ expect((refusal as InstanceType<typeof TicketCompletionRangeTooBroad>).limit).toBe(
2305
+ TICKET_COMPLETION_SCAN_LIMIT,
2306
+ )
2307
+ expect(rowsExamined()).toBe(TICKET_COMPLETION_SCAN_LIMIT + 1)
2308
+ } else {
2309
+ expect((await broad).total).toBe(population + recent)
2310
+ }
2202
2311
  }
2203
2312
  const digits = String(populations[1]).length - String(populations[0]).length
2204
2313
  for (const order of ['oldest', 'newest'] as const) {
@@ -2212,6 +2321,23 @@ export async function ticketPageReadBudget(
2212
2321
  expect(fallback.ids).toEqual(large.ids)
2213
2322
  expect(fallback.bytes).toBeGreaterThan(large.bytes * 100)
2214
2323
  }
2324
+ for (const until of ['2026-06-02T00:00:00Z', 'open']) {
2325
+ const small = digests.get(`native:${populations[0]}:${until}`)!
2326
+ const large = digests.get(`native:${populations[1]}:${until}`)!
2327
+ expect(large.statements).toBe(small.statements)
2328
+ // The page's total is the same at both sizes; the `states` answer differs
2329
+ // only by the digits of its per-state counts.
2330
+ expect(large.bytes).toBe(small.bytes)
2331
+ expect(large.stateBytes - small.stateBytes).toBeLessThanOrEqual(digits * 5)
2332
+ // The capped count scan and the window each examine the range only:
2333
+ // unrelated older done and ready rows never enter any statement.
2334
+ expect(small.rows).toBe(2 * recent)
2335
+ expect(large.rows).toBe(2 * recent)
2336
+ const fallback = digests.get(`fallback:${populations[1]}:${until}`)!
2337
+ expect(fallback.ids).toEqual(large.ids)
2338
+ expect(fallback.rows).toBeGreaterThanOrEqual(large.rows * 100)
2339
+ expect(fallback.bytes).toBeGreaterThan(large.bytes * 100)
2340
+ }
2215
2341
  }
2216
2342
 
2217
2343
  /** One ticket of a search-budget population: fixed-width id and title, a body
@@ -2246,9 +2372,10 @@ export function ticketSearchRows(population: number): TicketSearchRow[] {
2246
2372
  })
2247
2373
  }
2248
2374
 
2249
- /** Same shape as `TicketPageFixture`: a fresh source over `tickets`;
2250
- * `native` is a service answering `search`, `predating` one without it. */
2251
- export type TicketSearchFixture = TicketPageFixture
2375
+ /** Same shape as `TicketPageFixture` without row accounting: a fresh source
2376
+ * over `tickets`; `native` is a service answering `search`, `predating` one
2377
+ * without it. */
2378
+ export type TicketSearchFixture = Omit<TicketPageFixture, 'rowsExamined'>
2252
2379
 
2253
2380
  /** A search page (per operator or agent request) through a hosted service
2254
2381
  * that searches costs exactly one `search` request and one bounded statement,
@@ -74,6 +74,8 @@ export {
74
74
  targetedCompletenessParity,
75
75
  ticketListReadBudget,
76
76
  ticketPageReadBudget,
77
+ TICKET_PAGE_NODE_TITLE,
78
+ TICKET_PAGE_RECENT_DONE,
77
79
  ticketPriorityLabelReadBudget,
78
80
  ticketSearchReadBudget,
79
81
  ticketSearchRequestBudget,
@@ -1,4 +1,4 @@
1
- import type { TicketPriority } from '../ports/types'
1
+ import type { Ticket, TicketPriority } from '../ports/types'
2
2
  import { upgradeGenerationWrites } from './upgrade-generations'
3
3
  import { restoreReplay } from '../kernel/replay-retention'
4
4
  import { reducerValueForClient } from '../store/remote/compatibility'
@@ -16,6 +16,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'
16
16
  import { tmpdir } from 'node:os'
17
17
  import { join } from 'node:path'
18
18
  import { DashboardBuildPollCache } from '../cli/dashboard/poll'
19
+ import { inPresentationRead } from '../cli/dashboard/refresh'
19
20
  import { abDispatch } from '../cli/dispatch'
20
21
  import { createInvocationBudget } from '../processes/invocation-budget'
21
22
  import { createTerminalModeController } from '../cli/terminal-restore'
@@ -1199,8 +1200,11 @@ steps = []
1199
1200
  }
1200
1201
  return target.appendRepo(...args)
1201
1202
  }
1203
+ // The interactive dashboard polls on its own timer, so under load its
1204
+ // reads can land inside a tick window; only the kernel's count.
1202
1205
  if (key === 'getRepoBuildDigests')
1203
1206
  return (...args: Parameters<BuildStore['getRepoBuildDigests']>) => {
1207
+ if (inPresentationRead()) return target.getRepoBuildDigests(...args)
1204
1208
  acquisitions.digests++
1205
1209
  if (budget !== undefined && acquisitions.digests === 1) {
1206
1210
  // The work deadline passes while this read is on the wire; the
@@ -1213,7 +1217,8 @@ steps = []
1213
1217
  if (key === 'getReducerValue')
1214
1218
  return (...args: Parameters<BuildStore['getReducerValue']>) => {
1215
1219
  expect(['dispatcherRunFacts', 'openTick']).not.toContain(args[1].reducer)
1216
- if (args[1].reducer === 'repositoryReadFacts') acquisitions.facts++
1220
+ if (args[1].reducer === 'repositoryReadFacts' && !inPresentationRead())
1221
+ acquisitions.facts++
1217
1222
  return target.getReducerValue(...args)
1218
1223
  }
1219
1224
  const value = Reflect.get(target, key, target)
@@ -2779,9 +2784,200 @@ export async function deferredWorkReadBudget(): Promise<void> {
2779
2784
  Object.entries(starts).map(([kind, runs]) => [kind, runs[0]]),
2780
2785
  ),
2781
2786
  queuedCallsPerTick: { withHint: queuedWithHint, withoutHint: queuedWithoutHint },
2787
+ carriedPreparationCalls: await carriedPreparationReadBudget(),
2782
2788
  })
2783
2789
  }
2784
2790
 
2791
+ /** #1431: carried ticket-preparation attempts. The early stage resumes each
2792
+ * from its durable boundaries: one `tickets.get`, no ready listing, no
2793
+ * capacity measurement and no read of any build but the one it creates,
2794
+ * whatever the fleet of compatible, slot-holding builds, the repository log
2795
+ * length or the ready queue. A deferred, never-claimed admission and a
2796
+ * claimed attempt the deadline cut cost the same at every size. */
2797
+ async function carriedPreparationReadBudget(): Promise<Record<string, unknown>> {
2798
+ const { MemoryBuildStore } = await import('../store/memory')
2799
+ const repo = '/repos/carried-preparation'
2800
+ const sha = 'a'.repeat(40)
2801
+ const config = parseConfig('[tickets]\nsource = "file"\nreadyState = "Ready"\n')
2802
+ const body = [
2803
+ 'Login attempts are currently unlimited; throttle repeated failures.',
2804
+ '',
2805
+ '## Acceptance criteria',
2806
+ '',
2807
+ '- a sixth failed login within five minutes returns 429',
2808
+ '',
2809
+ '## Out of scope',
2810
+ '',
2811
+ '- captcha',
2812
+ '',
2813
+ ].join('\n')
2814
+ const readyTicket = (id: string): Ticket => ({
2815
+ revision: 'fixture',
2816
+ ref: { source: 'fake', id, title: id },
2817
+ title: id,
2818
+ body,
2819
+ state: 'Ready',
2820
+ resolved: false,
2821
+ labels: [],
2822
+ })
2823
+ async function world(length: number, fleet: number, ready: number, kind: 'deferred' | 'cut') {
2824
+ let now = Date.parse('2026-12-01T00:00:00.000Z')
2825
+ const clock = () => new Date(now)
2826
+ const store = new MemoryBuildStore({ clock })
2827
+ await store.ensureRepo(repo)
2828
+ // Compatible, nonterminal builds holding slots under a live runner.
2829
+ for (let i = 1; i <= fleet; i++) {
2830
+ const slug = `fleet-${i}`
2831
+ const ticket = { source: 'fake', id: `T-${slug}` }
2832
+ await store.createBuild({
2833
+ slug,
2834
+ repo,
2835
+ ticket,
2836
+ branch: slug,
2837
+ created: {
2838
+ actor: DISPATCHER,
2839
+ type: 'build.created',
2840
+ payload: { ticket, repo, baseBranch: 'main' },
2841
+ },
2842
+ })
2843
+ await store.append(slug, {
2844
+ actor: DISPATCHER,
2845
+ type: 'spec.imported',
2846
+ payload: { artifact: { kind: 'spec', rev: 0 }, ticket },
2847
+ })
2848
+ await store.append(slug, { actor: DISPATCHER, type: 'slot.admitted', payload: {} })
2849
+ await store.append(slug, {
2850
+ actor: KERNEL,
2851
+ type: 'runner.attached',
2852
+ payload: { instance: `${slug}-runner`, host: 'remote' },
2853
+ })
2854
+ await store.append(slug, { actor: KERNEL, type: 'plan.started', payload: { round: 1 } })
2855
+ await store.claimLease(slug, `${slug}-runner`, 86_400_000)
2856
+ }
2857
+ await seedRepoFiller(store, repo, length)
2858
+ const tickets = new FakeTicketSource([])
2859
+ for (let i = 1; i <= ready; i++) tickets.add(readyTicket(`T-ready-${i}`))
2860
+ const carried = readyTicket('T-carried')
2861
+ tickets.add(carried)
2862
+ const ref = { source: 'fake', id: 'T-carried' }
2863
+ await store.appendRepo(repo, {
2864
+ actor: DISPATCHER,
2865
+ type: 'ticket-preparation.intended',
2866
+ payload: {
2867
+ attempt: 'prep_carried',
2868
+ ticket: ref,
2869
+ readyState: 'Ready',
2870
+ claimedState: 'Doing',
2871
+ workDeadlineAt: new Date(now - 60_000).toISOString(),
2872
+ ...(kind === 'deferred' ? { claimDeferred: true as const } : {}),
2873
+ },
2874
+ })
2875
+ if (kind === 'cut') {
2876
+ await tickets.claim('T-carried')
2877
+ await store.appendRepo(repo, {
2878
+ actor: DISPATCHER,
2879
+ type: 'ticket-preparation.claimed',
2880
+ payload: { attempt: 'prep_carried', ticket: ref },
2881
+ })
2882
+ }
2883
+ await store.appendRepo(repo, {
2884
+ actor: DISPATCHER,
2885
+ type: 'dispatcher.work-deferred',
2886
+ payload: { builds: [], tickets: [{ ticket: ref, attempt: 'prep_carried' }] },
2887
+ })
2888
+ const sourceCalls: Record<string, number> = {}
2889
+ for (const method of ['get', 'listReady', 'claim'] as const) {
2890
+ const original = tickets[method].bind(tickets) as (...args: unknown[]) => Promise<unknown>
2891
+ Reflect.set(tickets, method, (...args: unknown[]) => {
2892
+ sourceCalls[method] = (sourceCalls[method] ?? 0) + 1
2893
+ return original(...args)
2894
+ })
2895
+ }
2896
+ // One canonical reduction per key happens before anything is measured.
2897
+ await readRepositoryFacts(store, repo)
2898
+ await readBuildDigests(store, repo)
2899
+ for (let i = 1; i <= fleet; i++) await readBuildFacts(store, `fleet-${i}`)
2900
+ // The forge guard's health value, which the slug probe reads.
2901
+ await store.getReducerValue({ kind: 'repo', repo }, { reducer: 'forgeHealthValue' })
2902
+ now += 60_000
2903
+ const dispatcher = new Dispatcher({
2904
+ store,
2905
+ tickets,
2906
+ workspaces: {
2907
+ name: 'remote-test',
2908
+ preservation: async () => ({ outcome: 'preserved', heads: [] }),
2909
+ recovery: {
2910
+ fence: async () => ({ outcome: 'confirmed' }),
2911
+ reap: async () => ({
2912
+ outcome: 'confirmed',
2913
+ snapshots: { outcome: 'confirmed', deleted: 0 },
2914
+ }),
2915
+ },
2916
+ provision: async (input) => ({
2917
+ provider: 'remote-test',
2918
+ ref: `${input.branch}-g${input.generation ?? 0}`,
2919
+ path: '/remote/workspace',
2920
+ branch: input.branch,
2921
+ base: { source: 'existing' as const, sha },
2922
+ }),
2923
+ release: async () => {},
2924
+ },
2925
+ forge: (() => {
2926
+ const forge = new FakeForge()
2927
+ forge.seedBranch('main', sha)
2928
+ return forge
2929
+ })(),
2930
+ config,
2931
+ repo,
2932
+ exec: async () => ({ stdout: `${sha}\trefs/heads/main\n`, stderr: '', exitCode: 0 }),
2933
+ launchRunner: async () => 'scheduled' as const,
2934
+ ids: sequentialIds(),
2935
+ clock,
2936
+ })
2937
+ const stage = Reflect.get(dispatcher, 'serviceDeferredWork') as (
2938
+ ...args: unknown[]
2939
+ ) => Promise<void>
2940
+ let early: StoreReadMetrics | undefined
2941
+ let earlySource: Record<string, number> = {}
2942
+ Reflect.set(dispatcher, 'serviceDeferredWork', async (...args: unknown[]) => {
2943
+ const before = { ...sourceCalls }
2944
+ early = await measureStoreReads(store, () => stage.apply(dispatcher, args))
2945
+ earlySource = Object.fromEntries(
2946
+ Object.entries(sourceCalls)
2947
+ .map(([method, n]) => [method, n - (before[method] ?? 0)] as const)
2948
+ .filter(([, n]) => n > 0),
2949
+ )
2950
+ })
2951
+ await dispatcher.tick({ acceptNewWork: true })
2952
+ await dispatcher.drainProvisioning()
2953
+ const owned = (await store.getRepoEvents(repo)).findLast(
2954
+ (event) => event.type === 'ticket-preparation.resolved',
2955
+ )
2956
+ expect(owned?.payload).toMatchObject({ attempt: 'prep_carried', outcome: 'owned' })
2957
+ const fresh = (await store.listBuilds()).filter((record) => !record.slug.startsWith('fleet-'))
2958
+ expect(fresh.map((record) => record.ticket?.id)).toEqual(['T-carried'])
2959
+ return { early: early!, source: earlySource, created: fresh[0]!.slug, length }
2960
+ }
2961
+ const costs: Record<string, unknown> = {}
2962
+ for (const kind of ['deferred', 'cut'] as const) {
2963
+ const runs: unknown[] = []
2964
+ for (const [length, fleet, ready] of [
2965
+ [100, 20, 5],
2966
+ [100_000, 200, 500],
2967
+ ] as const) {
2968
+ const { early, source, created } = await world(length, fleet, ready, kind)
2969
+ // Only the attempt's own new build; never the fleet.
2970
+ expect(Object.keys(early.slugs)).toEqual([created])
2971
+ // One ticket read, and a claim only for the never-claimed admission.
2972
+ expect(source).toEqual(kind === 'deferred' ? { get: 1, claim: 1 } : { get: 1 })
2973
+ runs.push({ calls: early.calls, slugs: Object.values(early.slugs), repoRows: early.repoRows })
2974
+ }
2975
+ expect(runs[1]).toEqual(runs[0])
2976
+ costs[kind] = runs[0]
2977
+ }
2978
+ return costs
2979
+ }
2980
+
2785
2981
  /** #1409: carrying the rotated loops' positions between bounded passes, and
2786
2982
  * checking mixed-version deferral only on the build acted on. Positions come
2787
2983
  * from the repository facts the tick's refresh already reduced, so carrying
@@ -5792,8 +5988,40 @@ export async function headPathsLandingReadBudget(opts: {
5792
5988
  * after the first warm-up: exactly one `pr.checks-failed` is recorded and
5793
5989
  * an unchanged red head then costs the poll no extra store request. */
5794
5990
  failingChecks?: { set: (checks: import('../ports/types').HeadChecks) => void }
5991
+ /** Seeds an ended execution: `quiet` closed every session, `session` left
5992
+ * a finished verify session open. Warm-up settles that session in place
5993
+ * exactly once; afterwards both cost the poll the same. */
5994
+ endedExecution?: 'quiet' | 'session'
5795
5995
  }) {
5796
5996
  const { store, repo, slug } = opts
5997
+ if (opts.endedExecution) {
5998
+ const execution = { provider: 'fake', workspaceRef: 'budget', instance: 'budget-runner' }
5999
+ await store.append(slug, { actor: DISPATCHER, type: 'execution.started', payload: execution })
6000
+ if (opts.endedExecution === 'session')
6001
+ await store.append(slug, {
6002
+ actor: KERNEL,
6003
+ type: 'session.started',
6004
+ payload: {
6005
+ session: 'budget-verify',
6006
+ role: 'verify-e2e',
6007
+ runner: 'scripted',
6008
+ phase: 'verify:e2e',
6009
+ round: 1,
6010
+ },
6011
+ })
6012
+ await store.append(slug, {
6013
+ actor: DISPATCHER,
6014
+ type: 'execution.ended',
6015
+ payload: { instance: 'budget-runner', workspaceRef: 'budget', outcome: 'completed' },
6016
+ })
6017
+ }
6018
+ const settledSessions = async () =>
6019
+ (await store.getEvents(slug)).filter(
6020
+ (event) =>
6021
+ event.type === 'session.ended' &&
6022
+ 'outcome' in event.payload &&
6023
+ event.payload.session === 'budget-verify',
6024
+ ).length
5797
6025
  const ciFailures = async () =>
5798
6026
  (await store.getEvents(slug)).filter((event) => event.type === 'pr.checks-failed').length
5799
6027
  /** The commands that derive a head's path facts. */
@@ -5834,6 +6062,10 @@ export async function headPathsLandingReadBudget(opts: {
5834
6062
  }
5835
6063
  expect(await ciFailures()).toBe(1)
5836
6064
  }
6065
+ if (opts.endedExecution) {
6066
+ expect(await settledSessions()).toBe(opts.endedExecution === 'session' ? 1 : 0)
6067
+ expect((await readBuildFacts(store, slug)).value.state.sessions.open).toEqual([])
6068
+ }
5837
6069
  if (opts.warm) {
5838
6070
  const landing = (await store.getEvents(slug)).filter(
5839
6071
  (event) => event.type === 'landing.decided' || event.type === 'landing.deferred',