@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
@@ -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({
@@ -6,15 +6,20 @@ import { TicketIssueLinksUnsupported } from './issue-links'
6
6
  import { TicketPriorityUnsupported } from './priority'
7
7
  import { ticketLifecycle } from './lifecycle'
8
8
  import { TicketSearchCursorInvalid, TicketSearchUnsupported } from './search'
9
+ import {
10
+ TICKET_COMPLETION_SCAN_LIMIT,
11
+ TicketCompletionRangeTooBroad,
12
+ usesCompletionCriteria,
13
+ } from './completion'
9
14
  import type { TicketsConfig } from '../../config/schema'
10
15
  import type {
11
16
  DependencyState,
12
17
  Ticket,
13
18
  TicketCreateOptions,
14
19
  TicketDraft,
15
- TicketCriteria,
16
20
  TicketListing,
17
21
  TicketPage,
22
+ TicketPageCriteria,
18
23
  TicketPageListing,
19
24
  TicketPriority,
20
25
  TicketSearchPage,
@@ -62,6 +67,8 @@ import {
62
67
  TICKET_TARGETING_PROBE_NODE,
63
68
  TICKET_PAGING_HEADER,
64
69
  TICKET_PAGING_CAPABILITY,
70
+ TICKET_COMPLETION_HEADER,
71
+ TICKET_COMPLETION_CAPABILITY,
65
72
  TICKET_SEARCH_HEADER,
66
73
  TICKET_SEARCH_CAPABILITY,
67
74
  dependencyStatesWireSchema,
@@ -174,9 +181,11 @@ export class HostedTicketSource implements TicketSource {
174
181
  private readonly targeted = (nodeId: string) => this.targetedListing(nodeId)
175
182
  /** Unknown until a response settles it; see `noteCapabilities`. */
176
183
  private pagingSupport: boolean | undefined
177
- private readonly paged = (criteria: TicketCriteria, page: TicketPage) =>
184
+ private readonly paged = (criteria: TicketPageCriteria, page: TicketPage) =>
178
185
  this.pagedListing(criteria, page)
179
186
  /** Unknown until a response settles it; see `noteCapabilities`. */
187
+ private completionSupport: boolean | undefined
188
+ /** Unknown until a response settles it; see `noteCapabilities`. */
180
189
  private searchSupport: boolean | undefined
181
190
  private readonly searched = (query: TicketSearchQuery) => this.searchPage(query)
182
191
 
@@ -237,6 +246,12 @@ export class HostedTicketSource implements TicketSource {
237
246
  return this.pagingSupport === true ? this.paged : undefined
238
247
  }
239
248
 
249
+ /** True only once the service has advertised both `list-page` and its
250
+ * completion criteria; until then the operator filters `list-ready`. */
251
+ get completionPaging(): boolean {
252
+ return this.pagingSupport === true && this.completionSupport === true
253
+ }
254
+
240
255
  /** Present only once the service has positively advertised `search`; while
241
256
  * support is unknown or refused, callers refuse with `TicketSearchUnsupported`
242
257
  * before any request. There is never a listing fallback. */
@@ -274,6 +289,9 @@ export class HostedTicketSource implements TicketSource {
274
289
  if (response.headers.get(TICKET_SEARCH_HEADER) === TICKET_SEARCH_CAPABILITY)
275
290
  this.searchSupport = true
276
291
  else if (response.ok) this.searchSupport = false
292
+ if (response.headers.get(TICKET_COMPLETION_HEADER) === TICKET_COMPLETION_CAPABILITY)
293
+ this.completionSupport = true
294
+ else if (response.ok) this.completionSupport = false
277
295
  }
278
296
 
279
297
  private async send(
@@ -308,6 +326,7 @@ export class HostedTicketSource implements TicketSource {
308
326
  [TICKET_PAGING_HEADER]: TICKET_PAGING_CAPABILITY,
309
327
  [TICKET_SEARCH_HEADER]: TICKET_SEARCH_CAPABILITY,
310
328
  ...storeCallerHeaders(),
329
+ [TICKET_COMPLETION_HEADER]: TICKET_COMPLETION_CAPABILITY,
311
330
  [AUTOBUILD_VERSION_HEADER]: AUTOBUILD_VERSION,
312
331
  [REMOTE_STORE_PROTOCOL_VERSION_HEADER]: REMOTE_STORE_PROTOCOL_VERSION,
313
332
  },
@@ -412,6 +431,11 @@ export class HostedTicketSource implements TicketSource {
412
431
  ? body.error
413
432
  : 'ticket service cannot page this ticket source',
414
433
  )
434
+ if (body.code === 'completion-range-too-broad')
435
+ throw new TicketCompletionRangeTooBroad(
436
+ this.name,
437
+ typeof body.limit === 'number' ? body.limit : TICKET_COMPLETION_SCAN_LIMIT,
438
+ )
415
439
  if (body.code === 'search-unsupported') throw new TicketSearchUnsupported(this.name)
416
440
  if (body.code === 'search-cursor-invalid')
417
441
  throw new TicketSearchCursorInvalid(this.name, String(body.cursor ?? ''))
@@ -448,6 +472,7 @@ export class HostedTicketSource implements TicketSource {
448
472
  error instanceof TicketIssueLinksUnsupported ||
449
473
  error instanceof TicketPriorityUnsupported ||
450
474
  error instanceof HostedTicketPagingError ||
475
+ error instanceof TicketCompletionRangeTooBroad ||
451
476
  error instanceof TicketSearchUnsupported ||
452
477
  error instanceof TicketSearchCursorInvalid
453
478
  )
@@ -491,12 +516,19 @@ export class HostedTicketSource implements TicketSource {
491
516
  /** The service's native window: its order and total are canonical, so an
492
517
  * answer that contradicts the request fails rather than being repaired. */
493
518
  private async pagedListing(
494
- criteria: TicketCriteria,
519
+ criteria: TicketPageCriteria,
495
520
  page: TicketPage,
496
521
  ): Promise<TicketPageListing> {
497
522
  if (criteria.assignee !== undefined) {
498
523
  throw new Error('the hosted ticket source does not support an assignee gate')
499
524
  }
525
+ // A strict service predating completion criteria would refuse them, so
526
+ // they are sent only after a response echoed the completion capability.
527
+ if (usesCompletionCriteria(criteria, page) && this.completionSupport !== true)
528
+ throw new HostedTicketPagingError(
529
+ 'service-predates',
530
+ 'ticket service predates completion listing (since, until, excludeLabels, order completed); upgrade the service',
531
+ )
500
532
  const offset = page.offset ?? 0
501
533
  const listing = await this.request(
502
534
  'list-page',
@@ -504,6 +536,12 @@ export class HostedTicketSource implements TicketSource {
504
536
  criteria: {
505
537
  ...(criteria.labels !== undefined ? { labels: criteria.labels } : {}),
506
538
  ...(criteria.state !== undefined ? { state: criteria.state } : {}),
539
+ // Sent only when it excludes something, which the guard above
540
+ // has already negotiated; an empty list would trip an older
541
+ // service's strict request schema for no effect.
542
+ ...(criteria.excludeLabels?.length ? { excludeLabels: criteria.excludeLabels } : {}),
543
+ ...(criteria.since !== undefined ? { since: criteria.since } : {}),
544
+ ...(criteria.until !== undefined ? { until: criteria.until } : {}),
507
545
  },
508
546
  page: {
509
547
  limit: page.limit,
@@ -15,11 +15,21 @@ export function normalizeTicket(
15
15
  priority = true,
16
16
  assignees = true,
17
17
  ): Ticket {
18
- const { target, issueLinks: links, priority: level, assignees: assigned, ...rest } = ticket
18
+ const {
19
+ target,
20
+ targetTitle,
21
+ resolvedAt,
22
+ issueLinks: links,
23
+ priority: level,
24
+ assignees: assigned,
25
+ ...rest
26
+ } = ticket
19
27
  return {
20
28
  ...rest,
21
29
  kind: supported ? (ticket.kind ?? 'work') : 'work',
22
30
  ...(supported && target !== undefined ? { target } : {}),
31
+ ...(supported && target !== undefined && targetTitle !== undefined ? { targetTitle } : {}),
32
+ ...(ticket.resolved && resolvedAt !== undefined ? { resolvedAt } : {}),
23
33
  ...(issueLinks && links !== undefined ? { issueLinks: links } : {}),
24
34
  // Normal is the absence of the field, so strict wire schemas never see it.
25
35
  ...(priority && ticketPriority({ priority: level }) !== 'normal' ? { priority: level } : {}),
@@ -69,6 +69,9 @@ export interface Ticket {
69
69
  kind?: TicketKind
70
70
  /** Canonical source-local node ticket id; absent means the baseBranch root. */
71
71
  target?: string
72
+ /** The target node's title when the source answered it in the same read. A
73
+ * listing-time fact, not part of `revision`; present only alongside `target`. */
74
+ targetTitle?: string
72
75
  /** Opaque source version of title, body, labels, state and blockers. */
73
76
  revision: string
74
77
  /** Complete history oldest first when exposed by this read. Absent means
@@ -85,6 +88,10 @@ export interface Ticket {
85
88
  state?: string
86
89
  /** Native completion fact, identical to DependencyState.resolved. */
87
90
  resolved: boolean
91
+ /** ISO-8601 time the ticket entered its completed state, when the source
92
+ * knows it. A listing-time fact, not part of `revision`; present only when
93
+ * `resolved`. */
94
+ resolvedAt?: string
88
95
  labels: string[]
89
96
  /** Listing-time source fact that all declared blockers are resolved. Only
90
97
  * true permits skipping dependency reads; consumers fall back when absent. */
@@ -129,11 +136,25 @@ export interface TicketCriteria {
129
136
  assignee?: string
130
137
  }
131
138
 
139
+ /** `listPage` criteria: the dispatch criteria plus completion filters, which
140
+ * a source honours only when it declares `completionPaging`. */
141
+ export interface TicketPageCriteria extends TicketCriteria {
142
+ /** Omit every ticket carrying any of these labels. */
143
+ excludeLabels?: string[]
144
+ /** Completion range, half-open: `since <= resolvedAt < until`, both
145
+ * ISO-8601. A ticket without `resolvedAt` never matches. Completion criteria
146
+ * require `state`. A native source may refuse a range too broad for its
147
+ * per-request cap with `TicketCompletionRangeTooBroad`. */
148
+ since?: string
149
+ until?: string
150
+ }
151
+
132
152
  export interface TicketPage {
133
153
  limit: number
134
154
  offset?: number
135
- /** Dispatch order or newest filed first; see `TicketSource.listPage`. */
136
- order?: 'oldest' | 'newest'
155
+ /** Dispatch order, newest filed first, or most recently completed first;
156
+ * see `TicketSource.listPage`. */
157
+ order?: 'oldest' | 'newest' | 'completed'
137
158
  }
138
159
 
139
160
  export interface TicketPageListing extends TicketListing {
@@ -444,8 +465,15 @@ export interface TicketSource {
444
465
  * Arguments are nonnegative integers; zero limit returns no tickets with the
445
466
  * full matching total. Diagnostics
446
467
  * and failures match listReady; a failure must not trigger a full-read fallback.
447
- * listReady and listAll remain exhaustive. */
448
- listPage?(criteria: TicketCriteria, page: TicketPage): Promise<TicketPageListing>
468
+ * listReady and listAll remain exhaustive. `completed` (only sent to
469
+ * sources declaring `completionPaging`) puts tickets with `resolvedAt`
470
+ * first, most recent first, ties newest filed first; the rest follow newest
471
+ * filed first. */
472
+ listPage?(criteria: TicketPageCriteria, page: TicketPage): Promise<TicketPageListing>
473
+ /** Opt in only when `listPage` honours `excludeLabels`, `since`, `until`
474
+ * and order `completed`. Callers send them only to sources declaring it;
475
+ * the rest are filtered over the exhaustive `listReady` listing. */
476
+ readonly completionPaging?: boolean
449
477
  /** Optional text search over every lifecycle state (or `query.state`).
450
478
  * A ticket matches when every whitespace-separated term of `query.text`
451
479
  * occurs, case-insensitively, in its title or body (each term may hit either