@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
@@ -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
+ }
@@ -72,6 +72,10 @@ export interface TicketSourceContractHarness {
72
72
  /** Set false when a forwarding source declares `countStates` but its
73
73
  * backend cannot answer it (the hosted client over a backend without counts). */
74
74
  stateCounts?: boolean
75
+ /** Set false when a forwarding source declares `completionPaging` but its
76
+ * backend cannot answer completion pages (the hosted client over a backend
77
+ * without them). */
78
+ completionPaging?: boolean
75
79
  /** Allocate a label name that does not yet exist in the source. Live
76
80
  * providers may use this seam to track provider-side labels for cleanup. */
77
81
  freshLabel?: (purpose: string) => Promise<string> | string
@@ -383,6 +387,75 @@ export function describeTicketSourceContract(
383
387
  })
384
388
  })
385
389
 
390
+ test('native completion pages exclude labels, bound and order by completion when declared', async () => {
391
+ await withTicketSource(factory, async (harness) => {
392
+ const source = harness.source
393
+ if (!source.listPage || !source.completionPaging || harness.completionPaging === false)
394
+ return
395
+ const label = await freshLabel(harness, 'completion')
396
+ const hidden = await freshLabel(harness, 'completion-hidden')
397
+ const node = source.integrationTree
398
+ ? await createTracked(
399
+ harness,
400
+ {
401
+ title: contractTicketTitle('completion-node'),
402
+ body: CONTRACT_TICKET_BODY,
403
+ kind: 'node',
404
+ },
405
+ { state: harness.states.ready },
406
+ )
407
+ : undefined
408
+ const since = new Date(Date.now() - 60_000).toISOString()
409
+ const completed: string[] = []
410
+ for (let i = 0; i < 3; i++) {
411
+ // Distinct completion times, so completed order is deterministic.
412
+ if (i > 0) await Bun.sleep(5)
413
+ const ticket = await createTracked(
414
+ harness,
415
+ {
416
+ title: contractTicketTitle('completion'),
417
+ body: CONTRACT_TICKET_BODY,
418
+ labels: i === 1 ? [label, hidden] : [label],
419
+ ...(node ? { target: node.ref.id } : {}),
420
+ },
421
+ { state: harness.states.ready },
422
+ )
423
+ await source.transition(ticket.ref.id, harness.states.completed)
424
+ completed.push(ticket.ref.id)
425
+ }
426
+ const done = { state: harness.states.completed, labels: [label] }
427
+ const page = await source.listPage({ ...done, since }, { limit: 10, order: 'completed' })
428
+ expect(page.tickets.map((ticket) => ticket.ref.id)).toEqual([...completed].reverse())
429
+ expect(page.total).toBe(3)
430
+ for (const ticket of page.tickets) {
431
+ expect(ticket.resolved).toBe(true)
432
+ expect(Date.parse(ticket.resolvedAt!)).toBeGreaterThanOrEqual(Date.parse(since))
433
+ if (node) expect(ticket.targetTitle).toBe(node.title)
434
+ }
435
+ const excluded = await source.listPage(
436
+ { ...done, since, excludeLabels: [hidden] },
437
+ { limit: 10, order: 'completed' },
438
+ )
439
+ expect(excluded.tickets.map((ticket) => ticket.ref.id)).toEqual([
440
+ completed[2]!,
441
+ completed[0]!,
442
+ ])
443
+ expect(excluded.total).toBe(2)
444
+ // `until` is exclusive: the middle completion bounds only the first.
445
+ const until = page.tickets[1]!.resolvedAt!
446
+ const bounded = await source.listPage({ ...done, since, until }, { limit: 10 })
447
+ expect(bounded.tickets.map((ticket) => ticket.ref.id)).toEqual([completed[0]!])
448
+ expect(bounded.total).toBe(1)
449
+ // Only completed tickets have a completion time.
450
+ const open = await source.listPage(
451
+ { state: harness.states.ready, labels: [label], since },
452
+ { limit: 10 },
453
+ )
454
+ expect(open.tickets).toEqual([])
455
+ expect(open.total).toBe(0)
456
+ })
457
+ })
458
+
386
459
  test('bounded state counts agree with listed states when declared', async () => {
387
460
  await withTicketSource(factory, async (harness) => {
388
461
  const source = harness.source
@@ -133,6 +133,13 @@ function etagOf(json: unknown, link: string | undefined): string {
133
133
  .digest('hex')}"`
134
134
  }
135
135
 
136
+ /** GitHub's `closed_at`: when the issue last closed, null while open. */
137
+ function closedAt(issue: FakeIssue): string | null {
138
+ if (issue.state !== 'closed') return null
139
+ const closed = issue.history.findLast((entry) => entry.state === 'closed')
140
+ return closed === undefined ? null : new Date(closed.at).toISOString()
141
+ }
142
+
136
143
  export class FakeGitHubIssues {
137
144
  readonly owner: string
138
145
  readonly name: string
@@ -1233,6 +1240,7 @@ export class FakeGitHubIssues {
1233
1240
  comments: issue.comments,
1234
1241
  created_at: issue.created_at,
1235
1242
  updated_at: issue.updated_at,
1243
+ closed_at: closedAt(issue),
1236
1244
  ...(issue.pull_request
1237
1245
  ? { pull_request: { url: `${API}/repos/${repo}/pulls/${issue.number}` } }
1238
1246
  : {}),
@@ -51,6 +51,7 @@ export const githubIssueSchema = z
51
51
  pull_request: z.unknown().optional(),
52
52
  repository_url: z.string().optional(),
53
53
  created_at: z.string().optional(),
54
+ closed_at: z.string().nullable().optional(),
54
55
  parent_issue_url: z.string().nullable().optional(),
55
56
  sub_issues_summary: z
56
57
  .object({ total: z.number().int().optional() })
@@ -982,8 +982,12 @@ export class GitHubTicketSource implements TicketSource {
982
982
  * parent's label is read from the parent itself, because relabelling it
983
983
  * leaves the child's own ETag unchanged.
984
984
  */
985
- private async targetOf(issue: GitHubIssue, opts: HydrateOptions): Promise<string | undefined> {
986
- if (opts.target !== undefined) return opts.target ?? undefined
985
+ private async targetOf(
986
+ issue: GitHubIssue,
987
+ opts: HydrateOptions,
988
+ ): Promise<{ id: string; title?: string } | undefined> {
989
+ // A precomputed target (a node's own sub-issue list) carries no title.
990
+ if (opts.target !== undefined) return opts.target === null ? undefined : { id: opts.target }
987
991
  if (opts.resolveTarget === false) return undefined
988
992
  const number = this.localParent(issue)
989
993
  if (number === undefined) return undefined
@@ -997,7 +1001,9 @@ export class GitHubTicketSource implements TicketSource {
997
1001
  }
998
1002
  parent = await read
999
1003
  }
1000
- return parent !== null && isNode(parent) ? String(number) : undefined
1004
+ return parent !== null && isNode(parent)
1005
+ ? { id: String(number), title: parent.title }
1006
+ : undefined
1001
1007
  }
1002
1008
 
1003
1009
  private async hydrate(issue: GitHubIssue, opts: HydrateOptions): Promise<Hydrated> {
@@ -1049,19 +1055,25 @@ export class GitHubTicketSource implements TicketSource {
1049
1055
  state: string | undefined,
1050
1056
  blockedBy: string[],
1051
1057
  issueLinks: IssueLink[],
1052
- target: string | undefined,
1058
+ target: { id: string; title?: string } | undefined,
1053
1059
  ): Ticket {
1054
1060
  const { body, marker } = splitCreationMarker(issue.body)
1061
+ const resolved = state !== undefined && isClosedCompleted(issue)
1055
1062
  const ticket: Ticket = {
1056
1063
  kind: isNode(issue) ? 'node' : 'work',
1057
- ...(target !== undefined ? { target } : {}),
1064
+ ...(target !== undefined ? { target: target.id } : {}),
1065
+ // Not part of the revision: ticketRevision picks its fields explicitly.
1066
+ ...(target?.title !== undefined ? { targetTitle: target.title } : {}),
1058
1067
  revision: '',
1059
1068
  ref: { source: this.name, id: String(issue.number), url: issue.html_url, title: issue.title },
1060
1069
  ...(marker !== undefined ? { creationKey: marker.key } : {}),
1061
1070
  title: issue.title,
1062
1071
  body,
1063
1072
  ...(state !== undefined ? { state } : {}),
1064
- resolved: state !== undefined && isClosedCompleted(issue),
1073
+ resolved,
1074
+ ...(resolved && issue.closed_at && !Number.isNaN(Date.parse(issue.closed_at))
1075
+ ? { resolvedAt: new Date(issue.closed_at).toISOString() }
1076
+ : {}),
1065
1077
  labels: ticketLabelsOf(issue),
1066
1078
  ...(blockedBy.length > 0 ? { blockedBy } : {}),
1067
1079
  issueLinks,
@@ -34,9 +34,17 @@ export {
34
34
  hostedTicketRequestSchemas,
35
35
  TICKET_REVISIONS_HEADER,
36
36
  TICKET_REVISIONS_CAPABILITY,
37
+ TICKET_COMPLETION_HEADER,
38
+ TICKET_COMPLETION_CAPABILITY,
37
39
  } from './remote-protocol'
38
40
  export type { HostedTicketContext, HostedTicketOperation } from './remote-protocol'
39
41
 
42
+ export {
43
+ TICKET_COMPLETION_SCAN_LIMIT,
44
+ TicketCompletionRangeTooBroad,
45
+ usesCompletionCriteria,
46
+ } from './completion'
47
+
40
48
  export {
41
49
  searchTerms,
42
50
  searchTickets,
@@ -112,10 +112,13 @@ interface Connection<T> {
112
112
  }
113
113
 
114
114
  interface GqlIssue {
115
+ completedAt?: string | null
116
+ canceledAt?: string | null
115
117
  team?: { key: string }
116
118
  parent?: {
117
119
  id: string
118
120
  identifier: string
121
+ title?: string
119
122
  team?: { key: string }
120
123
  labels: { nodes: Array<{ name: string }>; pageInfo?: PageInfo }
121
124
  } | null
@@ -223,8 +226,10 @@ interface LinearTeamInfo {
223
226
  * listings exhaust relations so they can safely report blocker completion. */
224
227
  export const LINEAR_RELATION_PAGE_SIZE = 250
225
228
 
229
+ // Every issue selection that builds a ticket carries the completion scalars
230
+ // and the parent's title, so `resolvedAt` and `targetTitle` cost no extra read.
226
231
  const METADATA_FIELDS =
227
- 'team { key } parent { id identifier team { key } labels(first: 50) { nodes { name } pageInfo { hasNextPage endCursor } } }'
232
+ 'completedAt canceledAt team { key } parent { id identifier title team { key } labels(first: 50) { nodes { name } pageInfo { hasNextPage endCursor } } }'
228
233
 
229
234
  const ISSUE_FIELDS =
230
235
  `${METADATA_FIELDS} id identifier title description url priority state { name type } labels(first: 50) { nodes { name } pageInfo { hasNextPage endCursor } } ` +
@@ -232,6 +237,8 @@ const ISSUE_FIELDS =
232
237
 
233
238
  // Linear computes complexity from requested bounds, not returned counts:
234
239
  // https://linear.app/developers/rate-limiting. Scalars cost .1, objects 1.
240
+ // The metadata's completedAt, canceledAt and parent title add .3 per issue
241
+ // (at most 25 * .3 = 7.5), which leaves every bound below.
235
242
  // Dependency: 25 * (1.2 + 1.1 + 100 * 2.2 + 1.2) + wrappers < 5,600.
236
243
  // Ready: 10 * (10 + 50 * 1.1 + 100 * 3.5 + 1.2) + wrappers < 4,200.
237
244
  // Continuations: <=25 * (2 + 100 * 2.2 + 1.2) < 5,600, or
@@ -1598,9 +1605,15 @@ export class LinearTicketSource implements TicketSource {
1598
1605
  ? issue.parent.identifier
1599
1606
  : undefined
1600
1607
  const priority = linearLevel(issue.priority)
1608
+ const resolved = RESOLVED_STATE_TYPES.has(issue.state?.type ?? '')
1609
+ const completedAt = resolved ? (issue.completedAt ?? issue.canceledAt) : undefined
1601
1610
  return {
1602
1611
  kind,
1603
1612
  ...(target !== undefined ? { target } : {}),
1613
+ // Neither listing-time fact is part of the revision.
1614
+ ...(target !== undefined && issue.parent?.title !== undefined
1615
+ ? { targetTitle: issue.parent.title }
1616
+ : {}),
1604
1617
  revision: ticketRevision({
1605
1618
  kind,
1606
1619
  target,
@@ -1621,7 +1634,10 @@ export class LinearTicketSource implements TicketSource {
1621
1634
  title: issue.title,
1622
1635
  body: issue.description ?? '',
1623
1636
  state: issue.state?.name,
1624
- resolved: RESOLVED_STATE_TYPES.has(issue.state?.type ?? ''),
1637
+ resolved,
1638
+ ...(completedAt && !Number.isNaN(Date.parse(completedAt))
1639
+ ? { resolvedAt: new Date(completedAt).toISOString() }
1640
+ : {}),
1625
1641
  labels: issue.labels.nodes.map((label) => label.name),
1626
1642
  ...(blockedBy.length > 0 ? { blockedBy } : {}),
1627
1643
  ...(priority ? { priority } : {}),
@@ -6,6 +6,7 @@ import { refineUniqueIssues } from './issue-links'
6
6
  import { holdsState } from './lifecycle'
7
7
  import { ticketPrioritySchema } from './priority'
8
8
  import { TICKET_SEARCH_MAX_LIMIT } from './search'
9
+ import { usesCompletionCriteria } from './completion'
9
10
 
10
11
  /** Explicit opt-in: released clients through 0.12 use strict decoders without revisions.
11
12
  * Source checkouts can share their release version, so version alone is insufficient. */
@@ -91,6 +92,18 @@ export const TICKET_PAGING_CAPABILITY = '1'
91
92
  export const TICKET_SEARCH_HEADER = 'x-autobuild-ticket-search'
92
93
  export const TICKET_SEARCH_CAPABILITY = '1'
93
94
 
95
+ /** Completion listing. A client sends it on every request; only then does a
96
+ * service answer tickets with `resolvedAt` and `targetTitle`, so released
97
+ * strict decoders never see them. Services that accept `list-page` completion
98
+ * criteria (`excludeLabels`, `since`, `until`, order `completed`) echo it on
99
+ * every ticket response, failures included, and a client sends those criteria
100
+ * only after a response carried it. A native completion query over more than
101
+ * its cap answers `409 {kind: 'conflict', code: 'completion-range-too-broad',
102
+ * error, limit}`; one the backing source cannot honour answers the existing
103
+ * `409` `paging-unsupported`. */
104
+ export const TICKET_COMPLETION_HEADER = 'x-autobuild-ticket-completion'
105
+ export const TICKET_COMPLETION_CAPABILITY = '1'
106
+
94
107
  /** The node id a client's `list-targeting` negotiation probe names. Hosted
95
108
  * readable ids are `<teamKey>-<n>` or legacy `ticket-<uuid>`, so it never
96
109
  * names a ticket and the probe is an indexed miss. */
@@ -127,6 +140,10 @@ export const ticketWireSchema = z.strictObject({
127
140
  blockedBy: z.array(z.string()).optional(),
128
141
  issueLinks: issueLinksWireSchema.optional(),
129
142
  priority: ticketPrioritySchema.optional(),
143
+ /** Only to clients sending `TICKET_COMPLETION_HEADER`. */
144
+ resolvedAt: z.string().datetime({ offset: true }).optional(),
145
+ /** Only to clients sending `TICKET_COMPLETION_HEADER`, beside `target`. */
146
+ targetTitle: z.string().optional(),
130
147
  })
131
148
  export const ticketListingWireSchema = z.strictObject({
132
149
  tickets: z.array(ticketWireSchema),
@@ -171,6 +188,12 @@ const criteriaSchema = z.strictObject({
171
188
  labels: z.array(z.string()).optional(),
172
189
  state: z.string().optional(),
173
190
  })
191
+ /** `list-page` criteria; released clients never send the completion keys. */
192
+ const pageCriteriaSchema = criteriaSchema.extend({
193
+ excludeLabels: z.array(z.string()).optional(),
194
+ since: z.string().datetime({ offset: true }).optional(),
195
+ until: z.string().datetime({ offset: true }).optional(),
196
+ })
174
197
  const idSchema = z.strictObject({ id: z.string().min(1) })
175
198
  const draftSchema = z.strictObject({
176
199
  kind: z.enum(['work', 'node']).optional(),
@@ -232,14 +255,20 @@ export const hostedTicketRequestSchemas = {
232
255
  'list-ready': envelope(criteriaSchema),
233
256
  'list-targeting': envelope(z.strictObject({ nodeId: z.string().min(1) })),
234
257
  'list-page': envelope(
235
- z.strictObject({
236
- criteria: criteriaSchema,
237
- page: z.strictObject({
238
- limit: z.number().int().nonnegative(),
239
- offset: z.number().int().nonnegative().optional(),
240
- order: z.enum(['oldest', 'newest']).optional(),
241
- }),
242
- }),
258
+ z
259
+ .strictObject({
260
+ criteria: pageCriteriaSchema,
261
+ page: z.strictObject({
262
+ limit: z.number().int().nonnegative(),
263
+ offset: z.number().int().nonnegative().optional(),
264
+ order: z.enum(['oldest', 'newest', 'completed']).optional(),
265
+ }),
266
+ })
267
+ .refine(
268
+ (value) =>
269
+ value.criteria.state !== undefined || !usesCompletionCriteria(value.criteria, value.page),
270
+ 'completion criteria require a state',
271
+ ),
243
272
  ),
244
273
  search: envelope(
245
274
  z.strictObject({