@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
@@ -169,6 +169,9 @@ export interface OpenSession {
169
169
  resumed?: boolean
170
170
  suspensionCause?: EventPayload<'session.suspended'>['cause']
171
171
  suspendedActiveMs?: number
172
+ /** The ended execution a dispatcher-settled suspension names; its
173
+ * continuation is a runner loss. */
174
+ suspendedExecution?: EventPayload<'session.suspended'>['execution']
172
175
  session: string
173
176
  role: string
174
177
  runner: string
@@ -1478,6 +1481,9 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
1478
1481
  nativeHandle: event.payload.handle ?? open.nativeHandle,
1479
1482
  suspensionCause: event.payload.cause,
1480
1483
  suspendedActiveMs: event.payload.activeMs,
1484
+ ...(event.payload.execution !== undefined
1485
+ ? { suspendedExecution: event.payload.execution }
1486
+ : {}),
1481
1487
  })
1482
1488
  openSessions.delete(open.session)
1483
1489
  }
@@ -89,10 +89,13 @@ export interface RepositoryReadAcc {
89
89
  scanSeq?: number
90
90
  scan?: Extract<RepositoryEvent, { type: 'dispatcher.ticket-scan-completed' }>['payload']
91
91
  /** The latest `dispatcher.work-deferred` hint: builds the next tick sweeps
92
- * first. */
92
+ * first, and carried ticket-preparation attempts it resumes first. */
93
93
  deferredWork?: {
94
94
  seq: number
95
95
  builds: Extract<RepositoryEvent, { type: 'dispatcher.work-deferred' }>['payload']['builds']
96
+ tickets?: NonNullable<
97
+ Extract<RepositoryEvent, { type: 'dispatcher.work-deferred' }>['payload']['tickets']
98
+ >
96
99
  }
97
100
  /** The latest `dispatcher.pass-cursors` hint: where each rotated loop of
98
101
  * the next bounded pass continues. */
@@ -259,7 +262,11 @@ export const repositoryReadFactsReducer = defineReducer({
259
262
  acc.scanSeq = event.seq
260
263
  }
261
264
  if (event.type === 'dispatcher.work-deferred')
262
- acc.deferredWork = { seq: event.seq, builds: event.payload.builds }
265
+ acc.deferredWork = {
266
+ seq: event.seq,
267
+ builds: event.payload.builds,
268
+ ...(event.payload.tickets !== undefined ? { tickets: event.payload.tickets } : {}),
269
+ }
263
270
  if (event.type === 'dispatcher.pass-cursors')
264
271
  acc.passCursors = { seq: event.seq, cursors: event.payload.cursors }
265
272
  if (event.type === 'dispatcher.run-started') acc.latestRun = event.payload.run
@@ -0,0 +1,82 @@
1
+ /** Which open sessions belong to the engine's next step, and how the
2
+ * dispatcher settles the sessions an ended execution left open. Pure: the
3
+ * runner and the dispatcher pass reduced state and the engine decision. */
4
+ import { verifyPhase } from '../ontology'
5
+ import type { Decision } from './engine'
6
+ import type { BuildState, OpenSession } from './reducer'
7
+
8
+ /** Whether `session` is the occurrence `decision` runs next, so a runner may
9
+ * continue it natively. */
10
+ export function recoveryMatches(decision: Decision, session: OpenSession): boolean {
11
+ if (decision.kind === 'run-verify-stage')
12
+ return decision.members.some((member) =>
13
+ recoveryMatches(member.kind === 'evaluate-verify' ? member.action : member, session),
14
+ )
15
+ return decision.kind === 'run-phase'
16
+ ? session.phase === decision.phase && session.round === decision.round
17
+ : decision.kind === 'run-agent-verify'
18
+ ? session.phase === verifyPhase(decision.step) && session.round === decision.attempt
19
+ : decision.kind === 'run-finalize-step'
20
+ ? session.phase === 'finalize' && session.role === decision.step
21
+ : false
22
+ }
23
+
24
+ /** Sessions open only inside executions, so once an execution has been
25
+ * recorded and none is open, every open session belongs to an ended one and
26
+ * no runner owns it. The dispatcher settles each without launching a runner:
27
+ *
28
+ * - `suspend`: an unfinished occurrence with a recorded native handle — the
29
+ * one the engine runs next, or one the caller found unfinished
30
+ * (`unfinished`) while a pause, escalation or other hold keeps the engine
31
+ * waiting. Suspending keeps it the native continuation candidate; the next
32
+ * runner resumes it as a runner loss.
33
+ * - `end`: everything else — a step that already has its outcome, a
34
+ * superseded round or attempt, or a session with no handle. These are ended
35
+ * `reclaimed`.
36
+ *
37
+ * A done or aborted build, or one with an abort pending, resumes nothing, so
38
+ * every session it left open is ended. A session whose phase has completed since it started is never
39
+ * suspended: the reducer ignores that suspension. Builds with no recorded
40
+ * execution keep the orphan-relaunch path, and already-suspended sessions are
41
+ * left alone. `decision` is absent only for a terminal build. */
42
+ export function endedExecutionSessionSettlement(
43
+ state: BuildState,
44
+ decision: Decision | undefined,
45
+ unfinished: ReadonlySet<string> = new Set(),
46
+ ): { suspend: OpenSession[]; end: OpenSession[] } {
47
+ const settlement = { suspend: [] as OpenSession[], end: [] as OpenSession[] }
48
+ if (state.openExecution !== undefined || state.executions.length === 0) return settlement
49
+ for (const session of state.sessions.open)
50
+ (resumable(state, session) &&
51
+ ((decision !== undefined && recoveryMatches(decision, session)) ||
52
+ unfinished.has(session.session))
53
+ ? settlement.suspend
54
+ : settlement.end
55
+ ).push(session)
56
+ return settlement
57
+ }
58
+
59
+ /** Open sessions of an ended execution whose resumability the engine
60
+ * decision does not settle: the caller checks each occurrence's durable
61
+ * terminal and passes the unfinished ones back as `unfinished`. */
62
+ export function settlementTerminalChecks(
63
+ state: BuildState,
64
+ decision: Decision | undefined,
65
+ ): OpenSession[] {
66
+ if (state.openExecution !== undefined || state.executions.length === 0) return []
67
+ return state.sessions.open.filter(
68
+ (session) =>
69
+ resumable(state, session) && (decision === undefined || !recoveryMatches(decision, session)),
70
+ )
71
+ }
72
+
73
+ function resumable(state: BuildState, session: OpenSession): boolean {
74
+ const completed = state.lastCompletedPhase
75
+ return (
76
+ state.status !== 'done' &&
77
+ state.status !== 'aborted' &&
78
+ !state.pendingCommands.some((command) => command.command === 'abort') &&
79
+ session.nativeHandle !== undefined &&
80
+ !(completed?.phase === session.phase && completed.seq > session.seq)
81
+ )
82
+ }
@@ -20,6 +20,16 @@ export interface TicketPreparation {
20
20
  missing?: string[]
21
21
  /** Its hand-back has been reported (`ticket.handed-back`). */
22
22
  reported?: boolean
23
+ /** The bounded invocation's work deadline (ISO) the latest `intended` was
24
+ * written under. An attempt past it with no recorded failure or bounce was
25
+ * interrupted by that deadline: it resumes and is never handed back. */
26
+ workDeadlineAt?: string
27
+ /** Admitted without a claim call (the preparation would not fit before the
28
+ * work deadline); cleared when a later `intended` records the claim start. */
29
+ claimDeferred?: true
30
+ /** The build level admission decided, recorded by a bounded pass. A
31
+ * carried attempt resumes with it. */
32
+ level?: 'urgent' | 'high' | 'normal' | 'low'
23
33
  }
24
34
  /** Completed attempts leave no historical entries in the canonical value. */
25
35
  export const ticketPreparationReducer = defineReducer<
@@ -61,6 +61,10 @@ import { systemClock, type BuildStore, type Clock } from '../store/types'
61
61
  import { BuildFeedUnsupportedError, BuildFeedValidationError } from '../store/build-feed'
62
62
  import { TicketOperationError } from '../ports/tickets/operations'
63
63
  import { TicketSearchCursorInvalid, TicketSearchUnsupported } from '../ports/tickets/search'
64
+ import {
65
+ TICKET_COMPLETION_SCAN_LIMIT,
66
+ TicketCompletionRangeTooBroad,
67
+ } from '../ports/tickets/completion'
64
68
  import { controlTicketStart } from './ticket-start'
65
69
  import {
66
70
  attachOperatorTicketAsset,
@@ -651,6 +655,10 @@ const harvestStatusInput = toolInput({ repo: repoField })
651
655
 
652
656
  const harvestControlInput = extendUnion(harvestControlRequestSchema, { repo: repoField })
653
657
 
658
+ /** The largest `tickets.list` page, and the page size used when paging or
659
+ * filter arguments arrive without `limit`. */
660
+ export const TICKETS_LIST_MAX_LIMIT = 200
661
+
654
662
  const ticketsListInput = toolInput({
655
663
  repo: repoField,
656
664
  state: z
@@ -658,27 +666,57 @@ const ticketsListInput = toolInput({
658
666
  .min(1)
659
667
  .optional()
660
668
  .describe(
661
- 'Provider state to list; defaults to the effective triage state from the repository’s effective config.',
669
+ 'Provider state to list; defaults to the effective triage state from the repository’s effective config, or to the effective done state when `since` or `until` is given.',
662
670
  ),
663
671
  labels: z
664
672
  .array(z.string().min(1))
665
673
  .optional()
666
674
  .describe('Narrow the list to tickets carrying every named label.'),
675
+ excludeLabels: z
676
+ .array(z.string().min(1))
677
+ .optional()
678
+ .describe('Omit tickets carrying any named label; `total` counts after the exclusion.'),
679
+ since: z
680
+ .string()
681
+ .datetime({ offset: true })
682
+ .optional()
683
+ .describe(
684
+ `Inclusive lower bound on completion time (\`resolvedAt\`), ISO-8601 with offset. Tickets without a completion time never match; defaults \`state\` to done. A hosted range over more than ${TICKET_COMPLETION_SCAN_LIMIT} tickets is refused.`,
685
+ ),
686
+ until: z
687
+ .string()
688
+ .datetime({ offset: true })
689
+ .optional()
690
+ .describe(
691
+ 'Exclusive upper bound on completion time (`resolvedAt`), ISO-8601 with offset; defaults `state` to done.',
692
+ ),
693
+ summary: z
694
+ .boolean()
695
+ .optional()
696
+ .describe('Omit ticket bodies and comments, keeping every other field.'),
667
697
  limit: z
668
698
  .number()
669
699
  .int()
670
700
  .min(0)
671
- .max(200)
701
+ .max(TICKETS_LIST_MAX_LIMIT)
672
702
  .optional()
673
- .describe('Return at most this many tickets; `total` still counts every match.'),
703
+ .describe(
704
+ `Return at most this many tickets; \`total\` still counts every match. Defaults to ${TICKETS_LIST_MAX_LIMIT} when \`offset\`, \`order\`, \`since\`, \`until\` or \`excludeLabels\` is given.`,
705
+ ),
674
706
  offset: z.number().int().min(0).optional().describe('Skip this many tickets first.'),
675
707
  order: z
676
- .enum(['oldest', 'newest'])
708
+ .enum(['oldest', 'newest', 'completed'])
677
709
  .optional()
678
710
  .describe(
679
- 'Priority order, urgent then high then normal then low tickets, each in the source order (the default), or newest filed first regardless of priority.',
711
+ 'Priority order, urgent then high then normal then low tickets, each in the source order (the default); newest filed first regardless of priority; or most recently completed first, then tickets without a completion time newest filed first.',
680
712
  ),
681
- })
713
+ }).refine(
714
+ (input) =>
715
+ input.since === undefined ||
716
+ input.until === undefined ||
717
+ Date.parse(input.since) < Date.parse(input.until),
718
+ { message: '`since` must be earlier than `until`', path: ['until'] },
719
+ )
682
720
 
683
721
  const ticketsSearchInput = toolInput({
684
722
  repo: repoField,
@@ -1365,19 +1403,30 @@ export const TOOLS: readonly ToolEntry[] = [
1365
1403
  'tickets.list',
1366
1404
  'List the repository’s ticket grooming queue from the configured ticket source.',
1367
1405
  ticketsListInput,
1368
- '{states, tickets, diagnostics, criteria, triageState, readyState, doneState, total}: the queue listing (one page when `limit` is set), the effective lifecycle names, the criteria actually applied, and the match count before paging.',
1406
+ `{states, tickets, diagnostics, criteria, triageState, readyState, doneState, total}: the queue listing (one page when \`limit\`, \`offset\`, \`order\`, \`since\`, \`until\` or \`excludeLabels\` is set), the effective lifecycle names, the criteria actually applied (state, labels, excludeLabels, since, until), and the match count before paging. Tickets carry \`resolvedAt\` (completion time) when the source knows it and \`targetTitle\` beside \`target\`; \`summary\` omits \`body\` and \`comments\`. Hosted completion queries (\`since\`/\`until\`, \`order: "completed"\`, \`excludeLabels\`) examine at most ${TICKET_COMPLETION_SCAN_LIMIT} tickets of the state and range; broader ones refuse with \`completion-range-too-broad\` — narrow \`since\`/\`until\`.`,
1369
1407
  async (raw, ctx) => {
1370
1408
  const input = raw as z.infer<typeof ticketsListInput>
1409
+ const paged =
1410
+ input.limit !== undefined ||
1411
+ input.offset !== undefined ||
1412
+ input.order !== undefined ||
1413
+ input.since !== undefined ||
1414
+ input.until !== undefined ||
1415
+ input.excludeLabels !== undefined
1371
1416
  return listOperatorTickets({
1372
1417
  store: ctx.store,
1373
1418
  repo: input.repo,
1374
1419
  backend: ticketsOf(ctx),
1375
1420
  ...(input.state !== undefined ? { state: input.state } : {}),
1376
1421
  ...(input.labels !== undefined ? { labels: input.labels } : {}),
1377
- ...(input.limit !== undefined
1422
+ ...(input.excludeLabels !== undefined ? { excludeLabels: input.excludeLabels } : {}),
1423
+ ...(input.since !== undefined ? { since: input.since } : {}),
1424
+ ...(input.until !== undefined ? { until: input.until } : {}),
1425
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
1426
+ ...(paged
1378
1427
  ? {
1379
1428
  page: {
1380
- limit: input.limit,
1429
+ limit: input.limit ?? TICKETS_LIST_MAX_LIMIT,
1381
1430
  ...(input.offset !== undefined ? { offset: input.offset } : {}),
1382
1431
  ...(input.order !== undefined ? { order: input.order } : {}),
1383
1432
  },
@@ -1857,6 +1906,12 @@ function mapDomainError(error: unknown): RegistryError {
1857
1906
  error: error.message,
1858
1907
  code: 'search-unsupported',
1859
1908
  })
1909
+ if (error instanceof TicketCompletionRangeTooBroad)
1910
+ return new RegistryError('domain', error.message, {
1911
+ kind: 'refusal',
1912
+ error: error.message,
1913
+ code: 'completion-range-too-broad',
1914
+ })
1860
1915
  if (error instanceof TicketSearchCursorInvalid)
1861
1916
  return new RegistryError('domain', error.message, {
1862
1917
  kind: 'refusal',
@@ -10,6 +10,11 @@ import { creationAssignees } from '../ports/tickets/assignees'
10
10
  import { creationLabels } from '../ports/tickets/labels'
11
11
  import type { IssueLink, TicketSearchPage } from '../ports/types'
12
12
  import { searchTickets } from '../ports/tickets/search'
13
+ import {
14
+ matchesPageCriteria,
15
+ orderCompleted,
16
+ usesCompletionCriteria,
17
+ } from '../ports/tickets/completion'
13
18
  import {
14
19
  projectTicketTree,
15
20
  compatibleTicketSource,
@@ -34,6 +39,7 @@ import type {
34
39
  TicketSource,
35
40
  TicketUpdate,
36
41
  TicketPage,
42
+ TicketPageCriteria,
37
43
  TicketPageListing,
38
44
  } from '../ports/types'
39
45
  import type { BuildStore } from '../store/types'
@@ -58,11 +64,19 @@ export interface OperatorTicketBackend {
58
64
  statesFor(context: OperatorTicketContext, source: TicketSource): string[] | Promise<string[]>
59
65
  }
60
66
 
61
- export interface OperatorTicketQueue {
67
+ export interface OperatorTicketQueue<T = Ticket> {
62
68
  states: string[]
63
- tickets: Ticket[]
69
+ /** Full tickets, or summaries without `body`/`comments` when `summary`. */
70
+ tickets: T[]
64
71
  diagnostics: string[]
65
- criteria: { state?: string; labels?: string[] }
72
+ /** The filters actually applied, including a defaulted state. */
73
+ criteria: {
74
+ state?: string
75
+ labels?: string[]
76
+ excludeLabels?: string[]
77
+ since?: string
78
+ until?: string
79
+ }
66
80
  /** Effective repository lifecycle names; clients must not invent provider states. */
67
81
  triageState: string
68
82
  readyState: string
@@ -72,7 +86,8 @@ export interface OperatorTicketQueue {
72
86
  }
73
87
 
74
88
  /** A window over a listing. `oldest` (default) is dispatch order: urgent first,
75
- * then the source's order; `newest` is newest filed first, regardless of urgency. */
89
+ * then the source's order; `newest` is newest filed first, regardless of urgency;
90
+ * `completed` is most recently completed first, then the rest newest filed first. */
76
91
  export type OperatorTicketPage = TicketPage
77
92
 
78
93
  export interface OperatorTicketBuild {
@@ -164,53 +179,152 @@ export async function searchOperatorTickets(opts: {
164
179
  return { ...page, tickets: page.tickets.map(namedPriority) }
165
180
  }
166
181
 
167
- export async function listOperatorTickets(opts: {
182
+ /** `tickets.list` with `summary`: a ticket without its body and comments. */
183
+ export type OperatorTicketSummary = Omit<Ticket, 'body' | 'comments'>
184
+
185
+ export interface OperatorTicketListOptions {
168
186
  store: BuildStore
169
187
  repo: string
170
188
  backend: OperatorTicketBackend
171
189
  state?: string
172
190
  labels?: string[]
191
+ /** Omit tickets carrying any of these labels. */
192
+ excludeLabels?: string[]
193
+ /** Half-open completion range over `resolvedAt`; either bound defaults the
194
+ * state to the effective done state. */
195
+ since?: string
196
+ until?: string
197
+ /** Omit every item's `body` and `comments`. */
198
+ summary?: boolean
173
199
  page?: OperatorTicketPage
174
- }): Promise<OperatorTicketQueue> {
200
+ }
201
+
202
+ export async function listOperatorTickets(
203
+ opts: OperatorTicketListOptions & { summary: true },
204
+ ): Promise<OperatorTicketQueue<OperatorTicketSummary>>
205
+ export async function listOperatorTickets(
206
+ opts: OperatorTicketListOptions & { summary?: false | undefined },
207
+ ): Promise<OperatorTicketQueue>
208
+ export async function listOperatorTickets(
209
+ opts: OperatorTicketListOptions,
210
+ ): Promise<OperatorTicketQueue<Ticket | OperatorTicketSummary>>
211
+ export async function listOperatorTickets(
212
+ opts: OperatorTicketListOptions,
213
+ ): Promise<OperatorTicketQueue<Ticket | OperatorTicketSummary>> {
175
214
  const { context, source } = await openOperatorTickets(opts)
176
215
  const lifecycle = ticketLifecycle(context.tickets)
177
216
  const triageState = lifecycle.triage
178
217
  const readyState = context.tickets.readyState
218
+ const ranged = opts.since !== undefined || opts.until !== undefined
179
219
  // The operator surface is a grooming queue. Unlike the CLI's ticket list,
180
220
  // labels narrow the default state instead of replacing its lifecycle gate.
181
- const criteria = {
182
- state: opts.state ?? triageState,
221
+ // A completion range only matches completed tickets, so it defaults to done.
222
+ const criteria: TicketPageCriteria = {
223
+ state: opts.state ?? (ranged ? lifecycle.done : triageState),
183
224
  ...(opts.labels !== undefined ? { labels: opts.labels } : {}),
225
+ // An empty exclusion is no criterion: omitting it keeps the request
226
+ // within what a service predating completion criteria accepts.
227
+ ...(opts.excludeLabels?.length ? { excludeLabels: opts.excludeLabels } : {}),
228
+ ...(opts.since !== undefined ? { since: new Date(opts.since).toISOString() } : {}),
229
+ ...(opts.until !== undefined ? { until: new Date(opts.until).toISOString() } : {}),
184
230
  }
185
- const nativePage = opts.page !== undefined && source.listPage !== undefined
231
+ const completion = usesCompletionCriteria(criteria, opts.page)
232
+ const nativePage =
233
+ opts.page !== undefined &&
234
+ source.listPage !== undefined &&
235
+ (!completion || source.completionPaging === true)
236
+ // A native refusal (TicketCompletionRangeTooBroad) propagates: falling back
237
+ // would perform the unbounded read the cap exists to prevent.
186
238
  const [listing, states] = await Promise.all([
187
- nativePage ? source.listPage!(criteria, opts.page!) : source.listReady(criteria),
239
+ nativePage
240
+ ? source.listPage!(criteria, opts.page!)
241
+ : source.listReady({
242
+ state: criteria.state,
243
+ ...(criteria.labels !== undefined ? { labels: criteria.labels } : {}),
244
+ }),
188
245
  opts.backend.statesFor(context, source),
189
246
  ])
190
- // Native pages arrive ordered; the fallback matches a native page's priority
191
- // order. listReady is in the source's filing order, so reversing it is newest
192
- // filed first.
193
- const ordered = nativePage
194
- ? listing.tickets
195
- : opts.page?.order === 'newest'
196
- ? [...listing.tickets].reverse()
197
- : byPriority(listing.tickets)
198
- const offset = opts.page?.offset ?? 0
247
+ let tickets: Ticket[]
248
+ let total: number
249
+ if (nativePage) {
250
+ // Native pages arrive filtered and ordered.
251
+ tickets = listing.tickets
252
+ total = (listing as TicketPageListing).total
253
+ } else {
254
+ // The fallback matches a native page: listReady is in the source's filing
255
+ // order, so reversing it is newest filed first.
256
+ const matching = completion
257
+ ? listing.tickets.filter((ticket) => matchesPageCriteria(ticket, criteria))
258
+ : listing.tickets
259
+ const ordered =
260
+ opts.page?.order === 'completed'
261
+ ? orderCompleted(matching)
262
+ : opts.page?.order === 'newest'
263
+ ? [...matching].reverse()
264
+ : byPriority(matching)
265
+ const offset = opts.page?.offset ?? 0
266
+ tickets = opts.page ? ordered.slice(offset, offset + opts.page.limit) : ordered
267
+ total = matching.length
268
+ }
269
+ const titled = await withTargetTitles(source, tickets, listing.tickets)
199
270
  return {
200
271
  states,
201
- tickets: (opts.page && !nativePage
202
- ? ordered.slice(offset, offset + opts.page.limit)
203
- : ordered
204
- ).map(namedPriority),
272
+ tickets: titled.map((ticket) => {
273
+ const named = namedPriority(ticket)
274
+ if (!opts.summary) return named
275
+ const { body: _body, comments: _comments, ...summary } = named
276
+ return summary
277
+ }),
205
278
  diagnostics: listing.diagnostics,
206
- criteria,
279
+ criteria: {
280
+ state: criteria.state,
281
+ ...(criteria.labels !== undefined ? { labels: criteria.labels } : {}),
282
+ ...(criteria.excludeLabels !== undefined ? { excludeLabels: criteria.excludeLabels } : {}),
283
+ ...(criteria.since !== undefined ? { since: criteria.since } : {}),
284
+ ...(criteria.until !== undefined ? { until: criteria.until } : {}),
285
+ },
207
286
  triageState,
208
287
  readyState,
209
288
  doneState: lifecycle.done,
210
- total: nativePage ? (listing as TicketPageListing).total : listing.tickets.length,
289
+ total,
211
290
  }
212
291
  }
213
292
 
293
+ /** Fill `targetTitle` for children whose source did not answer it: first
294
+ * from tickets already in hand, then one `get` per remaining distinct parent,
295
+ * bounded by the page. A failed or absent parent leaves the title absent. */
296
+ async function withTargetTitles(
297
+ source: TicketSource,
298
+ tickets: Ticket[],
299
+ inHand: readonly Ticket[],
300
+ ): Promise<Ticket[]> {
301
+ const missing = tickets.filter(
302
+ (ticket) => ticket.target !== undefined && ticket.targetTitle === undefined,
303
+ )
304
+ if (!missing.length) return tickets
305
+ const titles = new Map<string, string>()
306
+ for (const ticket of [...inHand, ...tickets])
307
+ titles.set(ticket.ref.id, ticket.ref.title ?? ticket.title)
308
+ const unknown = [...new Set(missing.map((ticket) => ticket.target!))].filter(
309
+ (id) => !titles.has(id),
310
+ )
311
+ await Promise.all(
312
+ unknown.map(async (id) => {
313
+ try {
314
+ const parent = await source.get(id)
315
+ if (parent) titles.set(id, parent.ref.title ?? parent.title)
316
+ } catch {
317
+ /* the title is optional; the listing stands without it */
318
+ }
319
+ }),
320
+ )
321
+ return tickets.map((ticket) => {
322
+ if (ticket.target === undefined || ticket.targetTitle !== undefined) return ticket
323
+ const title = titles.get(ticket.target)
324
+ return title === undefined ? ticket : { ...ticket, targetTitle: title }
325
+ })
326
+ }
327
+
214
328
  async function matchingBuild(
215
329
  store: BuildStore,
216
330
  repo: string,
@@ -179,6 +179,10 @@ export {
179
179
  PRIORITY_LABELS,
180
180
  } from '../ports/tickets/priority-labels'
181
181
  export { TicketSearchCursorInvalid, TicketSearchUnsupported } from '../ports/tickets/search'
182
+ export {
183
+ TICKET_COMPLETION_SCAN_LIMIT,
184
+ TicketCompletionRangeTooBroad,
185
+ } from '../ports/tickets/completion'
182
186
  export {
183
187
  TicketAssigneesUnsupported,
184
188
  refuseUnsupportedAssignees,
@@ -15,7 +15,7 @@ import type {
15
15
  } from '../ports/workspace/provider-capabilities'
16
16
 
17
17
  /** Version of the in-process plugin contract exposed by `@defrex/autobuild/plugin-sdk`. */
18
- export const PLUGIN_API_VERSION = '1.12.0' as const
18
+ export const PLUGIN_API_VERSION = '1.13.0' as const
19
19
 
20
20
  /** Context supplied when a registered adapter or contract fixture is selected. */
21
21
  export interface PluginFactoryContext<Config = Record<string, unknown>> {
@@ -0,0 +1,71 @@
1
+ // Completion filters for `listPage`: the shared matcher and order used by the
2
+ // operator's exhaustive fallback, and the typed refusal a native source raises
3
+ // when a completion query would examine more rows than its per-request cap.
4
+ // Dependency-light on purpose: it imports only port types.
5
+ import type { Ticket, TicketPage, TicketPageCriteria } from '../types'
6
+
7
+ /** Per-request ceiling on ticket rows a native completion query may examine. */
8
+ export const TICKET_COMPLETION_SCAN_LIMIT = 5_000
9
+
10
+ /** A native completion query would examine more than `limit` tickets of the
11
+ * requested state and range; nothing past the cap was read. */
12
+ export class TicketCompletionRangeTooBroad extends Error {
13
+ constructor(
14
+ readonly source: string,
15
+ readonly limit: number,
16
+ ) {
17
+ super(
18
+ `${source} ticket source refuses a completion query over more than ${limit} tickets; narrow since/until`,
19
+ )
20
+ this.name = 'TicketCompletionRangeTooBroad'
21
+ }
22
+ }
23
+
24
+ /** True when the request needs a source declaring `completionPaging`. */
25
+ export function usesCompletionCriteria(criteria: TicketPageCriteria, page?: TicketPage): boolean {
26
+ return (
27
+ (criteria.excludeLabels?.length ?? 0) > 0 ||
28
+ criteria.since !== undefined ||
29
+ criteria.until !== undefined ||
30
+ page?.order === 'completed'
31
+ )
32
+ }
33
+
34
+ /** The ticket's completion time, when it is resolved and the source knows it. */
35
+ export function completionTime(ticket: Ticket): string | undefined {
36
+ return ticket.resolved ? ticket.resolvedAt : undefined
37
+ }
38
+
39
+ /** `excludeLabels` (any match drops) and the half-open completion range. */
40
+ export function matchesPageCriteria(ticket: Ticket, criteria: TicketPageCriteria): boolean {
41
+ const excluded = criteria.excludeLabels ?? []
42
+ if (excluded.some((label) => ticket.labels.includes(label))) return false
43
+ if (criteria.since === undefined && criteria.until === undefined) return true
44
+ const at = completionTime(ticket)
45
+ if (at === undefined) return false
46
+ const time = Date.parse(at)
47
+ if (Number.isNaN(time)) return false
48
+ if (criteria.since !== undefined && time < Date.parse(criteria.since)) return false
49
+ if (criteria.until !== undefined && time >= Date.parse(criteria.until)) return false
50
+ return true
51
+ }
52
+
53
+ /** Tickets with a completion time first, most recent first, ties newest filed
54
+ * (latest in input order) first; the rest follow newest filed first. Input is
55
+ * in filing order. */
56
+ export function orderCompleted(tickets: readonly Ticket[]): Ticket[] {
57
+ const indexed = tickets.map((ticket, index) => {
58
+ const at = completionTime(ticket)
59
+ const time = at === undefined ? Number.NaN : Date.parse(at)
60
+ return { ticket, index, time }
61
+ })
62
+ return indexed
63
+ .sort((a, b) => {
64
+ const aHas = !Number.isNaN(a.time)
65
+ const bHas = !Number.isNaN(b.time)
66
+ if (aHas !== bHas) return aHas ? -1 : 1
67
+ if (aHas && a.time !== b.time) return b.time - a.time
68
+ return b.index - a.index
69
+ })
70
+ .map((entry) => entry.ticket)
71
+ }