@defrex/autobuild 1.17.0 → 1.18.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 (55) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +41 -2
  3. package/docs/architecture.md +27 -2
  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/config/schema.ts +2 -1
  17. package/packages/core/src/events/repository.ts +37 -1
  18. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/d41044cb2e54809c.json +194 -0
  19. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e0f89f52e48cbf62.json +197 -0
  20. package/packages/core/src/kernel/reducer-revisions.ts +5 -0
  21. package/packages/core/src/kernel/repository-read-facts.ts +9 -2
  22. package/packages/core/src/kernel/ticket-preparation.ts +10 -0
  23. package/packages/core/src/operator/registry.ts +64 -9
  24. package/packages/core/src/operator/tickets.ts +139 -25
  25. package/packages/core/src/plugin-sdk/index.ts +4 -0
  26. package/packages/core/src/plugins/manifest.ts +1 -1
  27. package/packages/core/src/ports/tickets/completion.ts +71 -0
  28. package/packages/core/src/ports/tickets/contract.ts +73 -0
  29. package/packages/core/src/ports/tickets/github-fake.ts +8 -0
  30. package/packages/core/src/ports/tickets/github-issues.ts +1 -0
  31. package/packages/core/src/ports/tickets/github.ts +18 -6
  32. package/packages/core/src/ports/tickets/hosted-index.ts +8 -0
  33. package/packages/core/src/ports/tickets/linear.ts +18 -2
  34. package/packages/core/src/ports/tickets/remote-protocol.ts +37 -8
  35. package/packages/core/src/ports/tickets/remote.ts +41 -3
  36. package/packages/core/src/ports/tickets/tree.ts +11 -1
  37. package/packages/core/src/ports/types.ts +32 -4
  38. package/packages/core/src/ports/workspace/vercel-sandbox.ts +78 -25
  39. package/packages/core/src/processes/dispatcher.ts +852 -276
  40. package/packages/core/src/processes/pass-stages.ts +32 -6
  41. package/packages/core/src/store/reducer-value-shapes.json +8309 -8240
  42. package/packages/core/src/store/remote/released-clients.json +11 -0
  43. package/packages/core/src/store/remote/released-reducer-values/1.18.0.json +36436 -0
  44. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  45. package/packages/core/src/testing/dispatch-read-budget.ts +143 -16
  46. package/packages/core/src/testing/index.ts +2 -0
  47. package/packages/core/src/testing/reduced-read-budget.ts +198 -2
  48. package/skills/guide/SKILL.md +21 -5
  49. package/skills/guide/references/operator-api.md +14 -1
  50. package/skills/guide/references/plugin-authoring.md +29 -1
  51. package/skills/guide/references/remote-ticket-protocol.md +34 -1
  52. package/skills/guide/references/restacking.md +5 -0
  53. package/skills/guide/references/setup.md +9 -3
  54. package/skills/operate/SKILL.md +18 -1
  55. package/templates/hosted-service/package.json +2 -2
@@ -8,14 +8,15 @@ 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.2.0.json'
13
+ import release11 from './1.3.0.json'
14
+ import release12 from './1.4.0.json'
15
+ import release13 from './1.5.0.json'
16
+ import release14 from './1.6.0.json'
17
+ import release15 from './1.7.0.json'
18
+ import release16 from './1.8.0.json'
19
+ import release17 from './1.9.0.json'
19
20
  import type { ReducerValueCatalog } from '../../reducer-value-validation'
20
21
  export interface ReleasedReducerValues extends ReducerValueCatalog {
21
22
  versions: Record<string, number>
@@ -30,12 +31,13 @@ export const RELEASED_REDUCER_VALUES: Readonly<Record<string, ReleasedReducerVal
30
31
  '1.15.0.json': release6,
31
32
  '1.16.0.json': release7,
32
33
  '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,
34
+ '1.18.0.json': release9,
35
+ '1.2.0.json': release10,
36
+ '1.3.0.json': release11,
37
+ '1.4.0.json': release12,
38
+ '1.5.0.json': release13,
39
+ '1.6.0.json': release14,
40
+ '1.7.0.json': release15,
41
+ '1.8.0.json': release16,
42
+ '1.9.0.json': release17,
41
43
  }
@@ -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
@@ -886,8 +886,11 @@ Every effective primary/alternate runtime needs a strict
886
886
  `runtimeProvisioning` entry with pinned `install` and exact-version `preflight`
887
887
  commands; runtime names remain open for plugins. Install/preflight runs before
888
888
  the marker in every fresh/replacement/readiness sandbox, and preflight reruns
889
- before every child. Failures name the runtime, role/alternate, and field and
890
- start no agent. Keep runtime installation out of `commands.setup`. Pi over
889
+ before every child. A relaunch whose preflight fails installs that runtime in
890
+ place and preflights again, so a `[roles]` change takes effect in existing
891
+ workspaces at their next launch; only a failure after that install fails the
892
+ launch. Failures name the runtime, role/alternate, and field (`install` or
893
+ `preflight`) with the command output and start no agent. Keep runtime installation out of `commands.setup`. Pi over
891
894
  `vercel-ai-gateway/...` uses `AI_GATEWAY_API_KEY`; never copy Pi state or Pi OAuth refresh tokens. Claude Code can select named [accounts](references/accounts.md): subscription tokens or region-bound Kimi Code keys stay on the dispatcher, with placeholders in the guest and exact-host/header egress transforms. Use the unmodified runtime, your own subscription and ordinary individual usage. Provision Claude/Kimi credentials manually; Autobuild never invokes `claude setup-token`. Codex can explicitly select a ChatGPT Plus/Pro account authorized with `bun ab accounts login NAME [--local|--project]`; exactly one dispatcher or hosted refreshing secret owns its renewal. The clone identity is upload-pack-only and
892
895
  scrubbed from Git config before an agent starts. Agents cannot push. Remote phase terminals deposit a durable
893
896
  publication request and park; that successful `ab done` is the one terminal and
@@ -1299,6 +1302,16 @@ the release, the entry keeps the cut execution's instance, and the next
1299
1302
  invocation fences or releases it before anything else. A carried build keeps
1300
1303
  its slot. Its entry retires without launching anything when the build is
1301
1304
  aborted, discarded, paused or no longer needs the start.
1305
+ Ticket preparations are carried too. Intake starts a preparation only with
1306
+ about 30 s left before the work deadline. Otherwise it records the admission
1307
+ without claiming, logs `ticket <id>: preparation carried by the invocation
1308
+ budget`, counts it as `preparationsCarried` and stops claiming. A preparation
1309
+ the deadline cuts before its build exists is carried the same way. The next
1310
+ invocation prepares the same attempt first, from where it stopped, without
1311
+ re-checking capacity. A carried ticket keeps its slot and is held from other
1312
+ claims until its preparation resolves, even across several invocations, and is
1313
+ never handed back to Ready for the interruption. It is released untouched if it left
1314
+ Ready or gained unresolved blockers before its claim.
1302
1315
  No stage consumes a bounded invocation: each starts items only within its share
1303
1316
  of the time left when it begins (half for deferred work, the janitor and the
1304
1317
  lease sweep, a quarter for the others; intake runs to the work deadline), and
@@ -2629,7 +2642,7 @@ subcommands accept `--json`, which emits one bare JSON value and no prose: a
2629
2642
  `Ticket[]` for `list`, and the complete resulting `Ticket` for `create`,
2630
2643
  `update`, `block`, `unblock`, `show`, or `move`.
2631
2644
 
2632
- Paged operator ticket listings may use the optional API 1.9 `TicketSource.listPage(criteria, page)` capability; without it, the operator reads the full listing and slices it. Native errors propagate. CLI ticket lists and dispatcher ready scans remain exhaustive through `listReady`/`listAll`. PostgreSQL pages natively, and the remote `HostedTicketSource` forwards pages to it through the service's `list-page` operation, falling back only against a service predating it; file, Linear and GitHub retain fallback. The POST list-ready protocol stays exhaustive. See the [custom source contract](references/plugin-authoring.md) for types and contract coverage.
2645
+ Paged operator ticket listings may use the optional API 1.9 `TicketSource.listPage(criteria, page)` capability; without it, the operator reads the full listing and slices it. Native errors propagate. CLI ticket lists and dispatcher ready scans remain exhaustive through `listReady`/`listAll`. PostgreSQL pages natively, and the remote `HostedTicketSource` forwards pages to it through the service's `list-page` operation, falling back only against a service predating it; file, Linear and GitHub retain fallback. The POST list-ready protocol stays exhaustive. Completion filters (`since`/`until` over `resolvedAt`, `excludeLabels`, order `completed`) reach `listPage` only on sources declaring the API 1.13 `completionPaging`; the hosted source answers them with at most two range scans, each bounded at 5,001 rows, and refuses ranges over 5,000 tickets with `completion-range-too-broad`, while other sources are filtered over the full listing. See the [custom source contract](references/plugin-authoring.md) for types and contract coverage.
2633
2646
 
2634
2647
  ### Ticket assets
2635
2648
 
@@ -3211,7 +3224,8 @@ an operator may move it as soon as the event arrives. Act on that event, not on
3211
3224
  `build.aborted` or the build leaving `ab builds`: cleanup is asynchronous. Every
3212
3225
  other non-completion hand-back reports the same event once after its move —
3213
3226
  spec-gate bounces (`spec-bounce`, with `missing`), preparation recovery
3214
- returning a confirmed claim to Ready (`preparation-failed`), closed-unmerged
3227
+ returning a confirmed claim to Ready (`preparation-failed`; never for a
3228
+ preparation the work deadline cut or deferred, which is carried), closed-unmerged
3215
3229
  PRs (`pr-closed`) and discards (`discard`). Missing
3216
3230
  Forge cleanup capabilities or provider outages leave cleanup pending with an
3217
3231
  actionable diagnostic for the next tick.
@@ -3615,7 +3629,9 @@ The default watch reports actionable conditions only:
3615
3629
  historical ones, and nothing clears or acknowledges it.
3616
3630
  - Repository `ticket.handed-back`: the dispatcher returned a claimed or ready
3617
3631
  ticket other than as completion, and the move is committed. `cause` is
3618
- `abort`, `spec-bounce`, `preparation-failed`, `pr-closed` or `discard`; the
3632
+ `abort`, `spec-bounce`, `preparation-failed`, `pr-closed` or `discard`
3633
+ (`preparation-failed` never for a preparation the work deadline cut or
3634
+ deferred; that one is carried); the
3619
3635
  payload carries the ticket, the build slug (or the preparation attempt), the
3620
3636
  destination `state` and `role`, `requested` when an abort to ready fell back,
3621
3637
  the spec-standard parts `missing`, and the operator's `reason`. Each hand-back
@@ -93,7 +93,7 @@ raw session-event append. External operator harnesses own agent execution.
93
93
  | `GET …/status` | Repository intake, pause, and default-auto-merge projection, plus `ticketStarts` (`{pending, recent}`, each entry with its `priority`) when single-ticket start requests are pending or recently settled. `capacity.slots`, when the held configuration is readable, maps each nonterminal build to its slot state; `capacity.occupied` counts its `held` entries. Its `operator` is `{presence: "unavailable", reason}`: this route does not load presence registrations, so it is not evidence that no operator is present. |
94
94
  | `GET …/harvest/status` | Harvest gate, runs, steps, recovery, and attention projection. |
95
95
  | `GET …/builds/{slug}/artifacts/{kind}?rev=N` | Raw bytes (`application/octet-stream`) plus content-disposition and `X-Autobuild-Artifact-*` metadata headers. Omit `rev` for latest. |
96
- | `GET …/tickets?state=S&label=L&limit=N&offset=K&order=O` | `{states,tickets,diagnostics,criteria,triageState,readyState,doneState,total}`. The three lifecycle names come from effective repository configuration (including provider fallback). With no `state`, `criteria.state` is `triageState`; repeated `label` parameters narrow that state with AND filters. An explicit `state` selects that exact backend workflow state. `limit` (0–200) returns one page, after skipping `offset`, in `order` `oldest` (the default: priority order, urgent, high, normal, then low tickets, each in the source order) or `newest` (newest filed first, regardless of priority; see paging below); `total` counts every match before paging. |
96
+ | `GET …/tickets?state=S&label=L&limit=N&offset=K&order=O` | `{states,tickets,diagnostics,criteria,triageState,readyState,doneState,total}`. The three lifecycle names come from effective repository configuration (including provider fallback). With no `state`, `criteria.state` is `triageState`; repeated `label` parameters narrow that state with AND filters. An explicit `state` selects that exact backend workflow state. `limit` (0–200) returns one page, after skipping `offset`, in `order` `oldest` (the default: priority order, urgent, high, normal, then low tickets, each in the source order) or `newest` (newest filed first, regardless of priority; see paging below); `total` counts every match before paging. Tickets carry `resolvedAt` and, beside `target`, `targetTitle` when known; see completion listings below. |
97
97
  | `GET …/tickets/states` | Full state metadata `{name,tickets,about?}[]`, including empty states (`tickets.states` in MCP). |
98
98
  | `GET …/tickets/{id}` | `{ticket,blockers,build,assets}`. Blockers include native `exists`/`resolved` status; `build` prefers an active matching repository build, otherwise the most recently updated one. `assets` lists the current ticket assets as `{kind,name,revision,size,layout,fileCount}`, as `ab ticket show --json` does. |
99
99
 
@@ -874,6 +874,19 @@ are successful cleanup; provider errors never count as completed deletion.
874
874
 
875
875
  Paged ticket listings use the source's optional native `listPage(criteria, page)` capability when present, otherwise read the full listing, order it, and slice it: by default priority order (urgent, high, normal, then low tickets, each in source order); for `newest`, the reversed listing. `newest` means newest filed first, regardless of priority, with a stable tie-break; it is not the reverse of priority order. A source that lists in filing order (file, GitHub, Linear) gets exactly that from the reversed listing. The remote `HostedTicketSource` pages natively through the service's `list-page` operation, and uses the fallback only against a service predating it. Native errors propagate. PostgreSQL counts matches without bodies and reads only the requested window. Zero limits and offsets past the end still report the full matching total. Unpaged listings remain exhaustive; the wire payload is the same for both paths.
876
876
 
877
+ Completion listings (`tickets.list` in MCP) answer "what shipped" digests:
878
+
879
+ | Input | Effect |
880
+ |---|---|
881
+ | `since`, `until` | ISO-8601 with offset; half-open `since <= resolvedAt < until`. Tickets without `resolvedAt` never match. Either one defaults `state` to the effective done state. `since` must precede `until`. |
882
+ | `order: "completed"` | Most recently completed first, ties newest filed first; tickets without a completion time follow, newest filed first. |
883
+ | `excludeLabels` | Drops any ticket carrying any named label; ANDed with `labels`, `state` and the range; `total` counts after it. |
884
+ | `summary: true` | Omits each ticket's `body` and `comments`; every other field, `revision` included, stays. |
885
+
886
+ - **Paging.** `order` and `offset` apply with or without `limit`. Any of `offset`, `order`, `since`, `until` or `excludeLabels` without `limit` pages at 200, the maximum; `total` still counts every match. A call with none of them stays exhaustive.
887
+ - **Fields.** `resolvedAt` is the ISO-8601 completion time, present only on resolved tickets whose source knows it (hosted, GitHub, Linear; never the file source). `targetTitle` is the target node's title, returned when resolvable: from the source's own read, a parent already in the listing, or one `get` per distinct remaining parent. A parent that is missing or whose read fails leaves `targetTitle` absent. `criteria` echoes the state, labels, `excludeLabels`, `since` and `until` applied.
888
+ - **Cost.** A source declaring completion paging (hosted) answers natively with at most two index range scans of the state and range, each stopping at 5,001 tickets: one counts the matches, a second reads the requested window. A zero `limit` or a refusal stops after the first. A range holding more than 5,000 tickets refuses with `code: "completion-range-too-broad"`; narrow `since`/`until`. `excludeLabels` or `order: "completed"` alone on a state holding more than 5,000 tickets refuses too. Other sources, and hosted services that predate completion listing, filter their full state listing and never refuse.
889
+
877
890
 
878
891
  ### Forge cooldown admission and explicit recovery
879
892
 
@@ -252,6 +252,7 @@ A plugin relying on a capability declares an `apiVersion` range containing its v
252
252
  - **1.10** Optional ticket-source ready-assignee capability (`readyAssignee`, with `prepareReadyAssignee`, `readyAssigneeRefusal` and `describeReadyAssignee`); sources without it refuse `[tickets].readyAssignee`. Also optional targeted ticket listing (`listTargeting`); older tree sources are observed through `listAll`.
253
253
  - **1.11** Optional ticket-source search (`search`); callers refuse sources without it and never fall back to a listing.
254
254
  - **1.12** Host-provided factory-context `fetch` and `invocationSignal` for bounded-invocation cancellation.
255
+ - **1.13** Optional ticket completion listing (`completionPaging`, with `TicketPageCriteria`, order `completed` and the `TicketCompletionRangeTooBroad` refusal), and the listing-time `Ticket.resolvedAt` and `Ticket.targetTitle`; callers filter the exhaustive listing for sources without it.
255
256
 
256
257
  ## 2. Create a repository-local module
257
258
 
@@ -651,7 +652,7 @@ for any other label.
651
652
  ## Optional ticket paging capability
652
653
 
653
654
  Native paging is an optional API 1.9 ticket-source capability:
654
- `listPage?(criteria: TicketCriteria, page: TicketPage): Promise<TicketPageListing>`.
655
+ `listPage?(criteria: TicketPageCriteria, page: TicketPage): Promise<TicketPageListing>`.
655
656
  The SDK exports these types; the result is `TicketListing & { total: number }`.
656
657
  Criteria retain state, labels (AND), and assignee semantics. The page has a
657
658
  nonnegative integer `limit`, optional nonnegative integer `offset` (default 0),
@@ -675,6 +676,33 @@ File, Linear and GitHub retain fallback; the remote `HostedTicketSource`
675
676
  forwards pages to the service's native paging (`list-page`), falling back only
676
677
  against a service predating it. The POST list-ready protocol stays exhaustive.
677
678
 
679
+ Completion listing is an optional API 1.13 extension of native paging.
680
+ `listPage` takes `TicketPageCriteria`: the criteria above plus
681
+ `excludeLabels` (drop any ticket carrying any named label), and `since`
682
+ (inclusive) and `until` (exclusive) bounds on `Ticket.resolvedAt`; tickets
683
+ without a completion time never match. `TicketPage.order` adds `completed`:
684
+ tickets with `resolvedAt` first, most recent first, ties newest filed first,
685
+ then the rest newest filed first. Declare `completionPaging: true` only when
686
+ `listPage` honours all of these; callers send them only to sources declaring it
687
+ and otherwise filter the exhaustive listing with the SDK's shared semantics. A
688
+ native source may refuse a range broader than its per-request cap with
689
+ `TicketCompletionRangeTooBroad` (the SDK exports it and
690
+ `TICKET_COMPLETION_SCAN_LIMIT`); callers surface it as the
691
+ `completion-range-too-broad` refusal and never fall back. The shared contract
692
+ suite checks declared completion paging.
693
+
694
+ Tickets may carry two listing-time facts outside `revision`: `resolvedAt`, the
695
+ ISO-8601 time the ticket entered its completed state (only when `resolved`),
696
+ and `targetTitle`, the target node's title (only beside `target`). Return them
697
+ when your read already has them. The hosted PostgreSQL source records
698
+ `resolvedAt` when a ticket enters the done state, uses the last update for done
699
+ tickets that predate it, and projects `targetTitle` in its listing statements.
700
+ GitHub reports `closed_at` for completed issues and the parent title it reads
701
+ for targeting; Linear reports `completedAt` (or `canceledAt`) and the parent's
702
+ title. The file source reports no `resolvedAt`; operator listings fill a
703
+ missing `targetTitle` from tickets already listed, then with one `get` per
704
+ remaining parent.
705
+
678
706
  ## Optional ticket search capability
679
707
 
680
708
  Text search is an optional API 1.11 ticket-source capability: