@defrex/autobuild 1.12.0 → 1.14.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 (167) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +465 -163
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +28 -4
  5. package/docs/architecture.md +136 -53
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +120 -17
  8. package/docs/dispatcher.md +19 -8
  9. package/docs/integration-overview.md +1 -1
  10. package/docs/integration-tree.md +12 -9
  11. package/docs/merge-policy.md +7 -2
  12. package/docs/operating.md +13 -3
  13. package/docs/operator-api.md +46 -23
  14. package/docs/operator-surfaces.md +7 -6
  15. package/docs/optimization-nodes.md +7 -6
  16. package/docs/plugin-authoring.md +46 -18
  17. package/docs/remote-store-protocol.md +52 -13
  18. package/docs/remote-ticket-protocol.md +85 -38
  19. package/docs/restacking.md +48 -3
  20. package/docs/setup.md +2 -1
  21. package/docs/ticket-migration.md +2 -2
  22. package/docs/ticket-sources.md +23 -8
  23. package/docs/tickets.md +4 -4
  24. package/docs/troubleshooting.md +32 -2
  25. package/docs/verification.md +3 -1
  26. package/package.json +3 -3
  27. package/packages/core/src/cli/build-control.ts +72 -6
  28. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  29. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  30. package/packages/core/src/cli/dashboard/model.ts +14 -8
  31. package/packages/core/src/cli/dashboard/poll.ts +218 -10
  32. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  33. package/packages/core/src/cli/dashboard/row-text.ts +2 -1
  34. package/packages/core/src/cli/dashboard/vocabulary.ts +5 -1
  35. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  36. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  37. package/packages/core/src/cli/dispatch.ts +547 -145
  38. package/packages/core/src/cli/help.ts +38 -24
  39. package/packages/core/src/cli/main.ts +7 -5
  40. package/packages/core/src/cli/publication-settlement.ts +4 -0
  41. package/packages/core/src/cli/remote-poll.ts +22 -5
  42. package/packages/core/src/cli/repository-status.ts +19 -9
  43. package/packages/core/src/cli/status.ts +23 -11
  44. package/packages/core/src/cli/store-opening.ts +12 -0
  45. package/packages/core/src/cli/ticket-start.ts +3 -3
  46. package/packages/core/src/cli/ticket.ts +12 -11
  47. package/packages/core/src/cli/wait.ts +8 -28
  48. package/packages/core/src/cli/watch.ts +113 -50
  49. package/packages/core/src/config/reference-metadata.ts +7 -1
  50. package/packages/core/src/config/reference.ts +5 -2
  51. package/packages/core/src/config/schema.ts +51 -16
  52. package/packages/core/src/events/payloads.ts +74 -14
  53. package/packages/core/src/events/policy.ts +1 -0
  54. package/packages/core/src/events/repository.ts +33 -3
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +31 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/be211f0e31a65006.json.gz +0 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/312cc4090820a612.json +1078 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  61. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  62. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  63. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a2780567b4989fb6.json +105 -0
  64. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  65. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  66. package/packages/core/src/kernel/dispatch-capacity.ts +243 -107
  67. package/packages/core/src/kernel/done-escalations.ts +273 -0
  68. package/packages/core/src/kernel/engine.ts +28 -9
  69. package/packages/core/src/kernel/integration-landing.ts +24 -4
  70. package/packages/core/src/kernel/integration-stack.ts +39 -0
  71. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  72. package/packages/core/src/kernel/log-index-value.ts +3 -0
  73. package/packages/core/src/kernel/log-index.ts +41 -2
  74. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  75. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  76. package/packages/core/src/kernel/reducer-revisions.ts +19 -0
  77. package/packages/core/src/kernel/reducer.ts +42 -8
  78. package/packages/core/src/kernel/repository-attention.ts +14 -5
  79. package/packages/core/src/kernel/repository-read-facts.ts +9 -0
  80. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  81. package/packages/core/src/kernel/verify-stages.ts +46 -7
  82. package/packages/core/src/operator/attention.ts +28 -3
  83. package/packages/core/src/operator/done-escalations.ts +38 -0
  84. package/packages/core/src/operator/presentation.ts +1 -1
  85. package/packages/core/src/operator/protocol.ts +8 -5
  86. package/packages/core/src/operator/query.ts +33 -19
  87. package/packages/core/src/operator/registry.ts +17 -13
  88. package/packages/core/src/operator/ticket-start.ts +8 -7
  89. package/packages/core/src/operator/tickets.ts +28 -9
  90. package/packages/core/src/plugin-sdk/index.ts +10 -0
  91. package/packages/core/src/plugins/manifest.ts +14 -1
  92. package/packages/core/src/ports/forge/create.ts +8 -0
  93. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  94. package/packages/core/src/ports/forge/github.ts +3 -0
  95. package/packages/core/src/ports/tickets/contract.ts +147 -76
  96. package/packages/core/src/ports/tickets/create.ts +47 -7
  97. package/packages/core/src/ports/tickets/fake.ts +8 -4
  98. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  99. package/packages/core/src/ports/tickets/file.ts +7 -3
  100. package/packages/core/src/ports/tickets/github.ts +1 -0
  101. package/packages/core/src/ports/tickets/grants.ts +11 -3
  102. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  103. package/packages/core/src/ports/tickets/linear.ts +28 -9
  104. package/packages/core/src/ports/tickets/migration.ts +4 -4
  105. package/packages/core/src/ports/tickets/operations.ts +4 -2
  106. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  107. package/packages/core/src/ports/tickets/priority.ts +127 -21
  108. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  109. package/packages/core/src/ports/tickets/remote.ts +104 -11
  110. package/packages/core/src/ports/tickets/revision.ts +5 -3
  111. package/packages/core/src/ports/tickets/search.ts +9 -0
  112. package/packages/core/src/ports/tickets/tree.ts +8 -6
  113. package/packages/core/src/ports/types.ts +30 -15
  114. package/packages/core/src/ports/workspace/build-execution.ts +13 -1
  115. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  116. package/packages/core/src/ports/workspace/create.ts +16 -3
  117. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  118. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  119. package/packages/core/src/ports/workspace/vercel-sandbox.ts +596 -144
  120. package/packages/core/src/processes/build-execution-state.ts +4 -0
  121. package/packages/core/src/processes/build-runner.ts +14 -1
  122. package/packages/core/src/processes/dispatcher.ts +841 -230
  123. package/packages/core/src/processes/execution-settlement.ts +25 -3
  124. package/packages/core/src/processes/harvest-runner.ts +12 -7
  125. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  126. package/packages/core/src/processes/invocation-budget.ts +176 -0
  127. package/packages/core/src/processes/publication-loss.ts +38 -3
  128. package/packages/core/src/processes/tick-publication.ts +1 -0
  129. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  130. package/packages/core/src/store/contract.ts +88 -3
  131. package/packages/core/src/store/event-reads.ts +30 -1
  132. package/packages/core/src/store/reduced-reads.ts +23 -0
  133. package/packages/core/src/store/reducer-value-shapes.json +6759 -6490
  134. package/packages/core/src/store/reducer-value-validation.ts +188 -33
  135. package/packages/core/src/store/remote/client.ts +169 -29
  136. package/packages/core/src/store/remote/compatibility.ts +113 -56
  137. package/packages/core/src/store/remote/credentials.ts +4 -1
  138. package/packages/core/src/store/remote/protocol.ts +3 -0
  139. package/packages/core/src/store/remote/released-clients.json +22 -0
  140. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  141. package/packages/core/src/store/remote/released-reducer-values/1.14.0.json +36076 -0
  142. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  143. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  144. package/packages/core/src/store/remote/retry.ts +406 -0
  145. package/packages/core/src/store/repo-state-events.ts +1 -0
  146. package/packages/core/src/testing/dispatch-read-budget.ts +155 -11
  147. package/packages/core/src/testing/index.ts +2 -0
  148. package/packages/core/src/testing/invocation-budget.ts +42 -0
  149. package/packages/core/src/testing/reduced-read-budget.ts +589 -19
  150. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  151. package/packages/core/src/web/overview-source.ts +19 -6
  152. package/skills/guide/SKILL.md +147 -67
  153. package/skills/guide/references/integration-tree.md +12 -9
  154. package/skills/guide/references/merge-policy.md +7 -2
  155. package/skills/guide/references/operator-api.md +46 -23
  156. package/skills/guide/references/optimization-nodes.md +7 -6
  157. package/skills/guide/references/plugin-authoring.md +46 -18
  158. package/skills/guide/references/remote-store-protocol.md +52 -13
  159. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  160. package/skills/guide/references/restacking.md +48 -3
  161. package/skills/guide/references/setup.md +2 -1
  162. package/skills/guide/references/ticket-migration.md +2 -2
  163. package/skills/operate/SKILL.md +136 -55
  164. package/skills/plan/SKILL.md +4 -3
  165. package/skills/spec/SKILL.md +9 -5
  166. package/skills/tickets/SKILL.md +25 -17
  167. package/templates/hosted-service/package.json +2 -2
@@ -1,6 +1,6 @@
1
1
  import { createTicket, updateTicket, moveTicket, changeBlockers } from './operations'
2
2
  import { normalizeIssueLinks, TicketIssueLinksUnsupported } from './issue-links'
3
- import { TicketPriorityUnsupported, urgentFirst } from './priority'
3
+ import { byPriority } from './priority'
4
4
  import { TicketAssigneesUnsupported } from './assignees'
5
5
  import { compatibleTicketSource } from './tree'
6
6
  import { TicketRevisionConflict } from './revision'
@@ -33,7 +33,7 @@ export async function assertTicketPage(
33
33
  page.order === 'newest'
34
34
  ? [...filed].reverse().map((id) => full.tickets.find((ticket) => ticket.ref.id === id)!)
35
35
  : source.priority
36
- ? urgentFirst(full.tickets)
36
+ ? byPriority(full.tickets)
37
37
  : full.tickets
38
38
  const offset = page.offset ?? 0
39
39
  expect(actual).toEqual({
@@ -313,32 +313,32 @@ export function describeTicketSourceContract(
313
313
  })
314
314
  })
315
315
 
316
- test('native pages order urgent dispatch first and newest filed first when declared', async () => {
316
+ test('native pages order by priority level and newest filed first when declared', async () => {
317
317
  await withTicketSource(factory, async (harness) => {
318
318
  const source = harness.source
319
319
  if (!source.listPage || !source.priority) return
320
- const label = await freshLabel(harness, 'page-urgent')
321
- // n1, u2, n3, u4, n5 in filing order; u2 and u4 are urgent.
320
+ const label = await freshLabel(harness, 'page-priority')
321
+ // Filing order: low, normal, urgent, high, normal, urgent.
322
+ const levels = ['low', 'normal', 'urgent', 'high', 'normal', 'urgent'] as const
322
323
  const filed: string[] = []
323
- for (let i = 1; i <= 5; i++) {
324
+ for (const [i, level] of levels.entries()) {
324
325
  const interval = harness.filingIntervalMs ?? 5
325
- if (i > 1 && interval > 0) await Bun.sleep(interval)
326
- const urgent = i % 2 === 0
326
+ if (i > 0 && interval > 0) await Bun.sleep(interval)
327
327
  const ticket = await createTracked(
328
328
  harness,
329
329
  {
330
- title: contractTicketTitle('page-urgent'),
330
+ title: contractTicketTitle('page-priority'),
331
331
  body: CONTRACT_TICKET_BODY,
332
332
  labels: [label],
333
- ...(urgent ? { priority: 'urgent' as const } : {}),
333
+ ...(level !== 'normal' ? { priority: level } : {}),
334
334
  },
335
335
  { state: harness.states.ready },
336
336
  )
337
337
  filed.push(ticket.ref.id)
338
338
  }
339
- const [n1, u2, n3, u4, n5] = filed as [string, string, string, string, string]
340
- const dispatch = [u2, u4, n1, n3, n5]
341
- const newest = [n5, u4, n3, u2, n1]
339
+ const [l1, n2, u3, h4, n5, u6] = filed as [string, string, string, string, string, string]
340
+ const dispatch = [u3, u6, h4, n2, n5, l1]
341
+ const newest = [u6, n5, h4, u3, n2, l1]
342
342
  // The fixture separates newest filed first from reversed dispatch order.
343
343
  expect(newest).not.toEqual([...dispatch].reverse())
344
344
  for (const criteria of [
@@ -664,97 +664,65 @@ export function describeTicketSourceContract(
664
664
  })
665
665
  })
666
666
 
667
- test('urgent priority persists when declared and is refused otherwise', async () => {
667
+ test('every priority level persists natively or through labels', async () => {
668
668
  await withTicketSource(factory, async (harness) => {
669
669
  const source = harness.source
670
670
  const ready = harness.states.ready
671
+ // Both branches: an omitted priority files the ticket at normal.
672
+ const plain = await createTracked(
673
+ harness,
674
+ { title: contractTicketTitle('normal'), body: CONTRACT_TICKET_BODY },
675
+ { state: ready },
676
+ )
677
+ expect('priority' in plain).toBe(false)
671
678
  if (!source.priority) {
672
- const title = contractTicketTitle('refused priority')
673
- const refusedCreate = await createTicket(source, {
674
- title,
675
- body: CONTRACT_TICKET_BODY,
676
- state: ready,
677
- priority: 'urgent',
678
- }).catch((error: unknown) => error)
679
- expect(refusedCreate).toBeInstanceOf(TicketPriorityUnsupported)
680
- expect((refusedCreate as TicketPriorityUnsupported).source).toBe(source.name)
681
- expect(
682
- (await source.listReady({ state: ready })).tickets.some((t) => t.title === title),
683
- ).toBe(false)
684
- const created = await createTracked(
685
- harness,
686
- { title: contractTicketTitle('normal'), body: CONTRACT_TICKET_BODY },
687
- { state: ready },
688
- )
689
- const refusedUpdate = await updateTicket(source, created.ref.id, {
690
- priority: 'urgent',
691
- }).catch((error: unknown) => error)
692
- expect(refusedUpdate).toBeInstanceOf(TicketPriorityUnsupported)
693
- expect((refusedUpdate as TicketPriorityUnsupported).source).toBe(source.name)
694
- if (source.mutateIfRevision) {
695
- const refusedGuarded = await updateTicket(
696
- source,
697
- created.ref.id,
698
- { priority: 'urgent' },
699
- false,
700
- created.revision,
701
- ).catch((error: unknown) => error)
702
- expect(refusedGuarded).toBeInstanceOf(TicketPriorityUnsupported)
703
- }
704
- const unchanged = await source.get(created.ref.id)
705
- expect(unchanged?.revision).toBe(created.revision)
706
- expect(unchanged?.title).toBe(created.title)
707
- // Normal is the value an unsupported source already holds: a no-op.
708
- await compatibleTicketSource(source).update(created.ref.id, { priority: 'normal' })
709
- expect((await source.get(created.ref.id))?.revision).toBe(created.revision)
679
+ await assertPriorityLabels(harness)
710
680
  return
711
681
  }
712
682
  const created = await createTracked(
713
683
  harness,
714
- {
715
- title: contractTicketTitle('urgent'),
716
- body: CONTRACT_TICKET_BODY,
717
- priority: 'urgent',
718
- },
684
+ { title: contractTicketTitle('high'), body: CONTRACT_TICKET_BODY, priority: 'high' },
719
685
  { state: ready },
720
686
  )
721
687
  const id = created.ref.id
722
- expect(created.priority).toBe('urgent')
723
- expect((await source.get(id))?.priority).toBe('urgent')
688
+ expect(created.priority).toBe('high')
689
+ expect((await source.get(id))?.priority).toBe('high')
724
690
  expect(
725
691
  (await source.listReady({ state: ready })).tickets.find((t) => t.ref.id === id)?.priority,
726
- ).toBe('urgent')
692
+ ).toBe('high')
727
693
  if (source.listAll)
728
694
  expect((await source.listAll()).tickets.find((t) => t.ref.id === id)?.priority).toBe(
729
- 'urgent',
695
+ 'high',
730
696
  )
731
-
732
- await source.update(id, { priority: 'normal' })
733
- const normal = await source.get(id)
734
- expect(normal && 'priority' in normal).toBe(false)
735
- expect(normal?.revision).not.toBe(created.revision)
736
-
737
- await source.update(id, { priority: 'urgent' })
738
- const urgent = await source.get(id)
739
- expect(urgent?.priority).toBe('urgent')
740
697
  // Revisions may be content hashes or counters: only change is required.
741
- expect(urgent?.revision).not.toBe(normal?.revision)
742
-
698
+ const revisions = [created.revision]
699
+ for (const level of ['low', 'urgent', 'normal'] as const) {
700
+ await source.update(id, { priority: level })
701
+ const read = (await source.get(id))!
702
+ if (level === 'normal') expect('priority' in read).toBe(false)
703
+ else expect(read.priority).toBe(level)
704
+ expect(revisions).not.toContain(read.revision)
705
+ revisions.push(read.revision)
706
+ }
707
+ await source.update(id, { priority: 'urgent' })
708
+ await source.update(id, { title: contractTicketTitle('retitled') })
709
+ const kept = (await source.get(id))!
710
+ expect(kept.priority).toBe('urgent')
743
711
  if (source.mutateIfRevision) {
744
712
  await expect(
745
- source.mutateIfRevision(id, normal!.revision, {
713
+ source.mutateIfRevision(id, created.revision, {
746
714
  kind: 'update',
747
- patch: { priority: 'normal' },
715
+ patch: { priority: 'low' },
748
716
  }),
749
717
  ).rejects.toBeInstanceOf(TicketRevisionConflict)
750
718
  expect((await source.get(id))?.priority).toBe('urgent')
751
- await source.mutateIfRevision(id, urgent!.revision, {
719
+ await source.mutateIfRevision(id, kept.revision, {
752
720
  kind: 'update',
753
721
  patch: { priority: 'normal' },
754
722
  })
755
723
  const cleared = await source.get(id)
756
724
  expect(cleared && 'priority' in cleared).toBe(false)
757
- expect(cleared?.revision).not.toBe(urgent!.revision)
725
+ expect(cleared?.revision).not.toBe(kept.revision)
758
726
  }
759
727
  })
760
728
  })
@@ -1303,3 +1271,106 @@ export function describeTicketSourceContract(
1303
1271
  })
1304
1272
  })
1305
1273
  }
1274
+
1275
+ /** The label fallback the compatibility facade gives a source without
1276
+ * native priority: exactly one `priority:<level>` label, the highest winning
1277
+ * when several are present, hidden from `labels`, untouched by a labels
1278
+ * replacement, and never touching another label. */
1279
+ async function assertPriorityLabels(harness: TicketSourceContractHarness): Promise<void> {
1280
+ const source = harness.source
1281
+ const facade = compatibleTicketSource(source)
1282
+ expect(facade.priority).toBe(true)
1283
+ const label = await freshLabel(harness, 'priority-labels')
1284
+ const isPriority = (name: string) => name.toLowerCase().startsWith('priority:')
1285
+ const rawPriority = async (id: string) =>
1286
+ (await source.get(id))!.labels.filter(isPriority).map((name) => name.toLowerCase())
1287
+ const viaFacade = { ...harness, source: facade }
1288
+ const created = await createTracked(
1289
+ viaFacade,
1290
+ {
1291
+ title: contractTicketTitle('labelled'),
1292
+ body: CONTRACT_TICKET_BODY,
1293
+ labels: [label],
1294
+ priority: 'high',
1295
+ },
1296
+ { state: harness.states.ready },
1297
+ )
1298
+ const id = created.ref.id
1299
+ expect(created.priority).toBe('high')
1300
+ expect(created.labels).toEqual([label])
1301
+ expect(await rawPriority(id)).toEqual(['priority:high'])
1302
+ const seen = [(await source.get(id))!.revision]
1303
+ // A second priority label added by hand: the highest level wins.
1304
+ const raw = (await source.get(id))!
1305
+ await source.update(id, { labels: [...raw.labels, 'priority:low'] })
1306
+ expect((await facade.get(id))?.priority).toBe('high')
1307
+ seen.push((await source.get(id))!.revision)
1308
+ // The next priority write leaves exactly one and every other label intact.
1309
+ await facade.update(id, { priority: 'low' })
1310
+ expect(await rawPriority(id)).toEqual(['priority:low'])
1311
+ const low = (await facade.get(id))!
1312
+ expect(low).toMatchObject({ priority: 'low', labels: [label] })
1313
+ expect(seen).not.toContain(low.revision)
1314
+ seen.push(low.revision)
1315
+ // A labels replacement neither adds nor removes priority labels.
1316
+ const other = await freshLabel(harness, 'priority-other')
1317
+ await facade.update(id, { labels: [other] })
1318
+ expect(await rawPriority(id)).toEqual(['priority:low'])
1319
+ expect((await facade.get(id))?.labels).toEqual([other])
1320
+ expect(
1321
+ (await facade.listReady({ state: harness.states.ready })).tickets.find((t) => t.ref.id === id)
1322
+ ?.priority,
1323
+ ).toBe('low')
1324
+ await facade.update(id, { priority: 'normal' })
1325
+ expect(await rawPriority(id)).toEqual([])
1326
+ const normal = (await facade.get(id))!
1327
+ expect('priority' in normal).toBe(false)
1328
+ expect(normal.labels).toEqual([other])
1329
+ // Labels and criteria naming a priority label are refused before any write.
1330
+ await expect(facade.update(id, { labels: ['priority:high'] })).rejects.toThrow(
1331
+ 'stores ticket priority',
1332
+ )
1333
+ await expect(facade.listReady({ labels: ['priority:high'] })).rejects.toThrow(
1334
+ 'stores ticket priority',
1335
+ )
1336
+ expect((await source.get(id))?.revision).toBe(normal.revision)
1337
+ if (source.mutateIfRevision) {
1338
+ await expect(
1339
+ facade.mutateIfRevision!(id, low.revision, { kind: 'update', patch: { priority: 'high' } }),
1340
+ ).rejects.toBeInstanceOf(TicketRevisionConflict)
1341
+ expect(await rawPriority(id)).toEqual([])
1342
+ await facade.mutateIfRevision!(id, normal.revision, {
1343
+ kind: 'update',
1344
+ patch: { priority: 'urgent' },
1345
+ })
1346
+ expect((await facade.get(id))?.priority).toBe('urgent')
1347
+ }
1348
+ if (source.integrationTree) {
1349
+ const node = await createTracked(
1350
+ viaFacade,
1351
+ { title: contractTicketTitle('labelled node'), body: CONTRACT_TICKET_BODY, kind: 'node' },
1352
+ { state: harness.states.ready },
1353
+ )
1354
+ await facade.update(node.ref.id, { priority: 'high' })
1355
+ expect(await facade.get(node.ref.id)).toMatchObject({ kind: 'node', priority: 'high' })
1356
+ // A kind change written beside a priority keeps every other label; only a
1357
+ // source recording kind as a label (`kindLabel`) moves that label with it.
1358
+ const kindLabel = source.kindLabel
1359
+ const work = await createTracked(
1360
+ viaFacade,
1361
+ { title: contractTicketTitle('labelled work'), body: CONTRACT_TICKET_BODY, labels: [label] },
1362
+ { state: harness.states.ready },
1363
+ )
1364
+ await facade.update(work.ref.id, { kind: 'node', priority: 'low' })
1365
+ const promoted = (await facade.get(work.ref.id))!
1366
+ expect(promoted).toMatchObject({ kind: 'node', priority: 'low' })
1367
+ expect([...promoted.labels].sort()).toEqual(
1368
+ (kindLabel === undefined ? [label] : [label, kindLabel]).sort(),
1369
+ )
1370
+ await facade.update(work.ref.id, { kind: 'work', priority: 'normal' })
1371
+ const demoted = (await facade.get(work.ref.id))!
1372
+ expect(demoted.kind).toBe('work')
1373
+ expect('priority' in demoted).toBe(false)
1374
+ expect(demoted.labels).toEqual([label])
1375
+ }
1376
+ }
@@ -1,4 +1,5 @@
1
1
  import { compatibleTicketSource } from './tree'
2
+ import { isPriorityLabel } from './priority-labels'
2
3
  import { configuredStore } from '../../cli/configured-store'
3
4
  import { projectToken } from '../../cli/project-credentials'
4
5
  import { resolveRepoOrigin } from '../../cli/repo-state'
@@ -15,7 +16,7 @@ import { createPluginRegistry, type PluginRegistry } from '../../plugins/registr
15
16
  import type { PluginFactoryContext } from '../../plugins/manifest'
16
17
  import type { TicketSource } from '../types'
17
18
  import { DEFAULT_TICKETS_DIR, FileTicketSource } from './file'
18
- import { LinearTicketSource } from './linear'
19
+ import { LinearTicketSource, type LinearFetch } from './linear'
19
20
  import { GitHubTicketSource } from './github'
20
21
  import { FileGitHubValidatorStore } from './github-validators'
21
22
  import {
@@ -61,6 +62,16 @@ async function rawTicketSource(
61
62
  /** Process label: the github source's default transport refuses requests
62
63
  * without a credential. Absent, `AB_GITHUB_REQUIRE_CREDENTIAL` decides. */
63
64
  requireCredential?: string
65
+ /** Host fetch for the builtin network sources (hosted, GitHub, Linear)
66
+ * and the plugin factory context; absent ⇒ global `fetch`. A bounded
67
+ * dispatcher invocation passes one that cancels at its deadline. */
68
+ fetchFn?: typeof fetch
69
+ /** Plugin factory context `invocationSignal`; absent ⇒ `() => undefined`. */
70
+ invocationSignal?: () => AbortSignal | undefined
71
+ /** The dispatcher's seam: a hosted source's policy synchronization and
72
+ * targeting negotiation are handed over to run at its first tick boundary
73
+ * instead of during construction. Absent, construction performs them. */
74
+ deferPreparation?: (prepare: () => Promise<void>) => void
64
75
  } = {},
65
76
  ): Promise<TicketSource> {
66
77
  const exec = options.exec ?? spawnExec
@@ -114,14 +125,16 @@ async function rawTicketSource(
114
125
  teamKey: config.teamKey,
115
126
  ...(config.claimedState !== undefined ? { claimedState: config.claimedState } : {}),
116
127
  ...(config.createState !== undefined ? { createState: config.createState } : {}),
128
+ ...(options.fetchFn !== undefined ? { fetchFn: options.fetchFn } : {}),
117
129
  })
118
130
  // Delegated sessions may read policy, but never redefine project authority.
119
- if (!ticketSession && !env.AB_HARVEST && !env.AB_PHASE) {
120
- await source.synchronizePolicy(hostedTicketPolicy(config))
121
- }
122
- // The source leaves with a settled targeting decision, so no observation
123
- // pass ever runs on undecided support; the policy sync usually settled it.
124
- await source.negotiateTargeting()
131
+ const policy =
132
+ !ticketSession && !env.AB_HARVEST && !env.AB_PHASE ? hostedTicketPolicy(config) : undefined
133
+ // The source is used with a settled targeting decision, so no observation
134
+ // pass ever runs on undecided support; the policy sync usually settles it.
135
+ if (options.deferPreparation !== undefined)
136
+ options.deferPreparation(() => source.prepareForDispatch(policy))
137
+ else await source.prepareForDispatch(policy)
125
138
  return source
126
139
  }
127
140
 
@@ -141,9 +154,15 @@ async function rawTicketSource(
141
154
  '[tickets].source = "linear" requires teamKey — the Linear team key (e.g. "ENG")',
142
155
  )
143
156
  }
157
+ const fetchFn = options.fetchFn
144
158
  return new LinearTicketSource({
145
159
  apiKey,
146
160
  teamKey: config.teamKey,
161
+ ...(fetchFn !== undefined
162
+ ? {
163
+ fetchFn: (url, init) => fetchFn(url, init) as unknown as ReturnType<LinearFetch>,
164
+ }
165
+ : {}),
147
166
  ...(config.claimedState !== undefined ? { claimedState: config.claimedState } : {}),
148
167
  ...(config.createState !== undefined ? { createState: config.createState } : {}),
149
168
  })
@@ -167,6 +186,7 @@ async function rawTicketSource(
167
186
  createGitHubFetchTransport({
168
187
  token: githubTokenSource(env),
169
188
  requireCredential: githubCredentialRequirement(env, options.requireCredential),
189
+ ...(options.fetchFn !== undefined ? { fetchFn: options.fetchFn } : {}),
170
190
  }),
171
191
  repository: coordinates,
172
192
  lifecycle: ticketLifecycle(config),
@@ -228,6 +248,8 @@ async function rawTicketSource(
228
248
  config: config as unknown as Record<string, unknown>,
229
249
  env,
230
250
  repoRoot: resolve(targetRepo),
251
+ fetch: options.fetchFn ?? globalThis.fetch,
252
+ invocationSignal: options.invocationSignal ?? (() => undefined),
231
253
  }
232
254
  try {
233
255
  return await registration.factory(context)
@@ -251,9 +273,27 @@ export async function createTicketSource(
251
273
  const plugin = owner?.kind === 'plugin' ? owner.name : undefined
252
274
  assertReadyAssigneeSupported(config, source, plugin)
253
275
  assertCreateAssigneeSupported(config, source, plugin)
276
+ if (!source.priority) assertNoPriorityLabels(config, source.name)
254
277
  return compatibleTicketSource(source)
255
278
  }
256
279
 
280
+ /** A source without native priority stores levels as `priority:<level>`
281
+ * labels, so they can neither gate readiness nor be applied by default. */
282
+ function assertNoPriorityLabels(
283
+ config: { readyLabels?: string[]; createLabels?: string[] },
284
+ source: string,
285
+ ): void {
286
+ for (const [key, labels] of [
287
+ ['readyLabels', config.readyLabels],
288
+ ['createLabels', config.createLabels],
289
+ ] as const)
290
+ for (const label of labels ?? [])
291
+ if (isPriorityLabel(label))
292
+ throw new Error(
293
+ `[tickets].${key} entry "${label}" is how the ${source} ticket source stores ticket priority; set priority with --priority instead`,
294
+ )
295
+ }
296
+
257
297
  /** Owner and name of a github.com origin: an `owner/name` slug, or a URL or
258
298
  * SSH spelling whose host is github.com. Anything else is null. */
259
299
  export function githubCoordinates(origin: string): { owner: string; name: string } | null {
@@ -39,7 +39,9 @@ function cloneTicket(ticket: Ticket, doneState: string): Ticket {
39
39
  ...(ticket.issueLinks?.length
40
40
  ? { issueLinks: ticket.issueLinks.map((link) => ({ ...link })) }
41
41
  : {}),
42
- ...(ticket.priority === 'urgent' ? { priority: 'urgent' as const } : {}),
42
+ ...(ticket.priority !== undefined && ticket.priority !== 'normal'
43
+ ? { priority: ticket.priority }
44
+ : {}),
43
45
  }
44
46
  }
45
47
 
@@ -197,7 +199,9 @@ export class FakeTicketSource implements TicketSource {
197
199
  ? { blockedBy: [...draft.blockedBy] }
198
200
  : {}),
199
201
  ...(draft.issueLinks?.length ? { issueLinks: normalizeIssueLinks(draft.issueLinks) } : {}),
200
- ...(draft.priority === 'urgent' ? { priority: 'urgent' as const } : {}),
202
+ ...(draft.priority !== undefined && draft.priority !== 'normal'
203
+ ? { priority: draft.priority }
204
+ : {}),
201
205
  }
202
206
  this.tickets.set(id, ticket)
203
207
  if (opts.idempotencyKey !== undefined) {
@@ -248,8 +252,8 @@ export class FakeTicketSource implements TicketSource {
248
252
  if (validated.labels !== undefined) ticket.labels = [...validated.labels]
249
253
  if (validated.issueLinks?.length) ticket.issueLinks = validated.issueLinks
250
254
  else if (validated.issueLinks !== undefined) delete ticket.issueLinks
251
- if (validated.priority === 'urgent') ticket.priority = 'urgent'
252
- else if (validated.priority !== undefined) delete ticket.priority
255
+ if (validated.priority === 'normal') delete ticket.priority
256
+ else if (validated.priority !== undefined) ticket.priority = validated.priority
253
257
 
254
258
  this.updates.push({ id, patch: cloneUpdate(validated) })
255
259
  }
@@ -2,6 +2,7 @@ import { portableAssetSchema } from './portable-assets'
2
2
  import { parse as parseToml, stringify as stringifyToml } from 'smol-toml'
3
3
  import { z } from 'zod'
4
4
  import { refineUniqueIssues } from './issue-links'
5
+ import { ticketPrioritySchema } from './priority'
5
6
 
6
7
  const frontmatterSchema = z.strictObject({
7
8
  kind: z.enum(['work', 'node']).optional(),
@@ -45,7 +46,7 @@ const frontmatterSchema = z.strictObject({
45
46
  .optional(),
46
47
  /** Dispatch class. Absent ≡ normal; a hand-written `normal` is tolerated and
47
48
  * dropped on the next write. */
48
- priority: z.enum(['urgent', 'normal']).optional(),
49
+ priority: ticketPrioritySchema.optional(),
49
50
  /** Stable external-create adoption key. It travels with the ticket across
50
51
  * state-directory moves, so retries find it in any lifecycle state. */
51
52
  idempotencyKey: z.string().min(1).optional(),
@@ -105,8 +106,8 @@ export function serializeTicketFile(front: Frontmatter, body: string): string {
105
106
  if (front.issueLinks !== undefined && front.issueLinks.length > 0) {
106
107
  data.issueLinks = front.issueLinks
107
108
  }
108
- // Only urgent is written, so normal tickets round-trip byte-identically.
109
- if (front.priority === 'urgent') data.priority = front.priority
109
+ // Normal is never written, so normal tickets round-trip byte-identically.
110
+ if (front.priority !== undefined && front.priority !== 'normal') data.priority = front.priority
110
111
  if (front.idempotencyKey !== undefined) {
111
112
  data.idempotencyKey = front.idempotencyKey
112
113
  }
@@ -315,7 +315,9 @@ export class FileTicketSource implements TicketSource {
315
315
  ? { blockedBy: [...draft.blockedBy] }
316
316
  : {}),
317
317
  ...(draft.issueLinks?.length ? { issueLinks: normalizeIssueLinks(draft.issueLinks) } : {}),
318
- ...(draft.priority === 'urgent' ? { priority: 'urgent' as const } : {}),
318
+ ...(draft.priority !== undefined && draft.priority !== 'normal'
319
+ ? { priority: draft.priority }
320
+ : {}),
319
321
  ...(opts.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),
320
322
  }
321
323
  if (taken.has(front.id)) throw new Error(`requested ticket id already occupied: ${front.id}`)
@@ -724,7 +726,9 @@ export class FileTicketSource implements TicketSource {
724
726
  ? { blockedBy: [...front.blockedBy] }
725
727
  : {}),
726
728
  ...(front.issueLinks?.length ? { issueLinks: normalizeIssueLinks(front.issueLinks) } : {}),
727
- ...(front.priority === 'urgent' ? { priority: 'urgent' as const } : {}),
729
+ ...(front.priority !== undefined && front.priority !== 'normal'
730
+ ? { priority: front.priority }
731
+ : {}),
728
732
  }
729
733
  }
730
734
  }
@@ -739,7 +743,7 @@ function setIssueLinks(front: Frontmatter, links: TicketUpdate['issueLinks']): v
739
743
  /** Urgent sets the key; normal removes it. */
740
744
  function setPriority(front: Frontmatter, priority: TicketUpdate['priority']): void {
741
745
  if (priority === undefined) return
742
- if (priority === 'urgent') front.priority = priority
746
+ if (priority !== 'normal') front.priority = priority
743
747
  else delete front.priority
744
748
  }
745
749
 
@@ -443,6 +443,7 @@ export class GitHubTicketSource implements TicketSource {
443
443
  readonly readyAssignee = true
444
444
  readonly assignees = true
445
445
  readonly integrationTree = true
446
+ readonly kindLabel = NODE_LABEL
446
447
 
447
448
  private readonly transport: GitHubRequest
448
449
  private readonly owner: string
@@ -6,8 +6,15 @@ import {
6
6
  } from '../../store/remote/version'
7
7
  import { ticketGrantResponseSchema } from './remote-protocol'
8
8
 
9
- export async function ticketGrantRequest(url: string, token: string, input: unknown) {
10
- const response = await fetch(`${url.replace(/\/+$/, '')}/tickets/grants`, {
9
+ /** `fetchFn` is the host fetch (absent ⇒ global `fetch`); a bounded
10
+ * dispatcher invocation passes one that also cancels at its deadline. */
11
+ export async function ticketGrantRequest(
12
+ url: string,
13
+ token: string,
14
+ input: unknown,
15
+ fetchFn: typeof fetch = fetch,
16
+ ) {
17
+ const response = await fetchFn(`${url.replace(/\/+$/, '')}/tickets/grants`, {
11
18
  method: 'POST',
12
19
  headers: {
13
20
  authorization: `Bearer ${token}`,
@@ -40,8 +47,9 @@ export async function issueTicketGrant(
40
47
  repo: string,
41
48
  execution: string,
42
49
  kind: 'runner' | 'phase',
50
+ fetchFn?: typeof fetch,
43
51
  ) {
44
52
  return ticketGrantResponseSchema.parse(
45
- await ticketGrantRequest(url, token, { action: 'issue', repo, execution, kind }),
53
+ await ticketGrantRequest(url, token, { action: 'issue', repo, execution, kind }, fetchFn),
46
54
  )
47
55
  }
@@ -13,6 +13,8 @@ export {
13
13
  TICKET_ISSUE_LINKS_CAPABILITY,
14
14
  TICKET_PRIORITY_HEADER,
15
15
  TICKET_PRIORITY_CAPABILITY,
16
+ TICKET_PRIORITY_LEVELS_HEADER,
17
+ TICKET_PRIORITY_LEVELS_CAPABILITY,
16
18
  TICKET_DEPENDENCY_STATE_HEADER,
17
19
  TICKET_DEPENDENCY_STATE_CAPABILITY,
18
20
  TICKET_POLICY_ROLES_HEADER,
@@ -53,7 +55,10 @@ export {
53
55
  refuseUnsupportedPriority,
54
56
  withoutUnsupportedPriority,
55
57
  ticketPriority,
58
+ dispatchPriority,
59
+ byPriority,
56
60
  urgentFirst,
61
+ TICKET_PRIORITIES,
57
62
  type TicketPriority,
58
63
  } from './priority'
59
64
  export { TicketAssigneesUnsupported } from './assignees'
@@ -124,7 +124,8 @@ interface GqlIssue {
124
124
  title: string
125
125
  description: string | null
126
126
  url: string
127
- /** Linear's 0–4 scale; only 1 (Urgent) maps to `urgent`. */
127
+ /** Linear's 0–4 scale: 1 Urgent, 2 High and 4 Low map to their levels;
128
+ * 3 Medium and 0 No priority read as `normal`. */
128
129
  priority?: number
129
130
  state: { name: string; type: string } | null
130
131
  labels: { nodes: Array<{ name: string }>; pageInfo?: PageInfo }
@@ -274,12 +275,13 @@ function nextCursor(info: PageInfo | undefined, seen: Set<string>): string | nul
274
275
  // nodeLabels 1 + 1.1 + parent 1 + .1 + 1.1 + 2.1 ≈ 65, so at the contract's
275
276
  // maximum limit of 100: 100 * 65 + wrappers < 6,600. Bodies are never selected.
276
277
  const SEARCH_LABEL_PAGE_SIZE = 50
277
- const SEARCH_QUERY = `query SearchIssues($filter: IssueFilter!, $first: Int!, $after: String, $nodeLabel: IssueLabelFilter!) { issues(filter: $filter, first: $first, after: $after, includeArchived: true, orderBy: createdAt) { nodes { identifier title state { name } labels(first: ${SEARCH_LABEL_PAGE_SIZE}) { nodes { name } ${PAGE_INFO} } nodeLabels: labels(filter: $nodeLabel, first: 1) { nodes { name } } parent { identifier team { key } labels(filter: $nodeLabel, first: 1) { nodes { name } } } } ${PAGE_INFO} } }`
278
+ const SEARCH_QUERY = `query SearchIssues($filter: IssueFilter!, $first: Int!, $after: String, $nodeLabel: IssueLabelFilter!) { issues(filter: $filter, first: $first, after: $after, includeArchived: true, orderBy: createdAt) { nodes { identifier title priority state { name } labels(first: ${SEARCH_LABEL_PAGE_SIZE}) { nodes { name } ${PAGE_INFO} } nodeLabels: labels(filter: $nodeLabel, first: 1) { nodes { name } } parent { identifier team { key } labels(filter: $nodeLabel, first: 1) { nodes { name } } } } ${PAGE_INFO} } }`
278
279
  const SEARCH_CURSOR_PREFIX = 'linear1.'
279
280
 
280
281
  interface GqlSearchIssue {
281
282
  identifier: string
282
283
  title: string
284
+ priority?: number
283
285
  state: { name: string } | null
284
286
  labels: Connection<{ name: string }>
285
287
  nodeLabels: { nodes: Array<{ name: string }> }
@@ -340,6 +342,18 @@ const DELETE_RELATION_MUTATION = `mutation DeleteRelation($id: String!) { issueR
340
342
  // Linear priority: 0 = No priority, 1 = Urgent, 2 = High, 3 = Medium, 4 = Low.
341
343
  const LINEAR_NO_PRIORITY = 0
342
344
  const LINEAR_URGENT = 1
345
+ const LINEAR_HIGH = 2
346
+ const LINEAR_LOW = 4
347
+ /** Every level but `normal`, as Linear stores it. */
348
+ const LINEAR_LEVELS = { urgent: LINEAR_URGENT, high: LINEAR_HIGH, low: LINEAR_LOW } as const
349
+
350
+ /** Linear's number as a ticket level; Medium and No priority are normal. */
351
+ function linearLevel(priority: number | undefined): keyof typeof LINEAR_LEVELS | undefined {
352
+ if (priority === LINEAR_URGENT) return 'urgent'
353
+ if (priority === LINEAR_HIGH) return 'high'
354
+ if (priority === LINEAR_LOW) return 'low'
355
+ return undefined
356
+ }
343
357
  const linearReservedIssueIdSchema = z.uuidv4()
344
358
 
345
359
  type ReadQuery = <T>(
@@ -684,6 +698,9 @@ export class LinearTicketSource implements TicketSource {
684
698
  labels: issue.labels.nodes.map((label) => label.name),
685
699
  kind: issue.nodeLabels.nodes.length > 0 ? 'node' : 'work',
686
700
  ...(target !== undefined ? { target } : {}),
701
+ ...(linearLevel(issue.priority) !== undefined
702
+ ? { priority: linearLevel(issue.priority) }
703
+ : {}),
687
704
  }
688
705
  })
689
706
  const next = nextCursor(data.issues.pageInfo, new Set())
@@ -881,7 +898,8 @@ export class LinearTicketSource implements TicketSource {
881
898
  if (reservedId !== undefined) input.id = reservedId
882
899
  if (assigneeId !== undefined) input.assigneeId = assigneeId
883
900
  // `normal` needs nothing: Linear creates issues with No priority.
884
- if (draft.priority === 'urgent') input.priority = LINEAR_URGENT
901
+ if (draft.priority !== undefined && draft.priority !== 'normal')
902
+ input.priority = LINEAR_LEVELS[draft.priority]
885
903
 
886
904
  let issue: GqlIssue | null = null
887
905
  let createError: unknown
@@ -941,12 +959,13 @@ export class LinearTicketSource implements TicketSource {
941
959
  validated.target = await this.validateTree(id, { ...validated, kind: effectiveKind })
942
960
  }
943
961
  const input: Record<string, unknown> = {}
944
- if (validated.priority === 'urgent') input.priority = LINEAR_URGENT
945
- // `normal` clears only Urgent; High, Medium or Low set by a person stays.
946
- // A person setting Urgent between this read and the write keeps it.
962
+ if (validated.priority !== undefined && validated.priority !== 'normal')
963
+ input.priority = LINEAR_LEVELS[validated.priority]
964
+ // `normal` clears Urgent, High or Low; Medium set by a person stays. A
965
+ // person setting a level between this read and the write keeps it.
947
966
  else if (
948
967
  validated.priority === 'normal' &&
949
- (await this.currentPriority('update', id)) === LINEAR_URGENT
968
+ linearLevel(await this.currentPriority('update', id)) !== undefined
950
969
  )
951
970
  input.priority = LINEAR_NO_PRIORITY
952
971
  const issueId = await this.resolveIssueId('update', id)
@@ -966,7 +985,7 @@ export class LinearTicketSource implements TicketSource {
966
985
  )
967
986
  }
968
987
  }
969
- // Only a priority-only `normal` patch on a non-urgent issue gets here
988
+ // Only a priority-only `normal` patch on a Medium or No priority issue gets here
970
989
  // empty; there is nothing to write.
971
990
  if (Object.keys(input).length === 0) return
972
991
 
@@ -1578,7 +1597,7 @@ export class LinearTicketSource implements TicketSource {
1578
1597
  issue.parent.labels.nodes.some((label) => label.name === 'node')
1579
1598
  ? issue.parent.identifier
1580
1599
  : undefined
1581
- const priority = issue.priority === LINEAR_URGENT ? ('urgent' as const) : undefined
1600
+ const priority = linearLevel(issue.priority)
1582
1601
  return {
1583
1602
  kind,
1584
1603
  ...(target !== undefined ? { target } : {}),