@defrex/autobuild 1.12.0 → 1.13.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 (159) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +435 -160
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +25 -3
  5. package/docs/architecture.md +124 -53
  6. package/docs/cli.md +1 -1
  7. package/docs/configuration.md +110 -15
  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 +5 -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 +51 -12
  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 +17 -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 +527 -144
  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/repository.ts +14 -3
  54. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +27 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  60. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  61. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  62. package/packages/core/src/kernel/dispatch-capacity.ts +243 -107
  63. package/packages/core/src/kernel/done-escalations.ts +269 -0
  64. package/packages/core/src/kernel/engine.ts +28 -9
  65. package/packages/core/src/kernel/integration-landing.ts +24 -4
  66. package/packages/core/src/kernel/integration-stack.ts +39 -0
  67. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  68. package/packages/core/src/kernel/log-index-value.ts +3 -0
  69. package/packages/core/src/kernel/log-index.ts +41 -2
  70. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  71. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  72. package/packages/core/src/kernel/reducer-revisions.ts +15 -0
  73. package/packages/core/src/kernel/reducer.ts +27 -7
  74. package/packages/core/src/kernel/repository-attention.ts +14 -5
  75. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  76. package/packages/core/src/kernel/verify-stages.ts +46 -7
  77. package/packages/core/src/operator/attention.ts +28 -3
  78. package/packages/core/src/operator/done-escalations.ts +38 -0
  79. package/packages/core/src/operator/presentation.ts +1 -1
  80. package/packages/core/src/operator/protocol.ts +8 -5
  81. package/packages/core/src/operator/query.ts +33 -19
  82. package/packages/core/src/operator/registry.ts +17 -13
  83. package/packages/core/src/operator/ticket-start.ts +8 -7
  84. package/packages/core/src/operator/tickets.ts +28 -9
  85. package/packages/core/src/plugin-sdk/index.ts +10 -0
  86. package/packages/core/src/plugins/manifest.ts +14 -1
  87. package/packages/core/src/ports/forge/create.ts +8 -0
  88. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  89. package/packages/core/src/ports/forge/github.ts +3 -0
  90. package/packages/core/src/ports/tickets/contract.ts +147 -76
  91. package/packages/core/src/ports/tickets/create.ts +47 -7
  92. package/packages/core/src/ports/tickets/fake.ts +8 -4
  93. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  94. package/packages/core/src/ports/tickets/file.ts +7 -3
  95. package/packages/core/src/ports/tickets/github.ts +1 -0
  96. package/packages/core/src/ports/tickets/grants.ts +11 -3
  97. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  98. package/packages/core/src/ports/tickets/linear.ts +28 -9
  99. package/packages/core/src/ports/tickets/migration.ts +4 -4
  100. package/packages/core/src/ports/tickets/operations.ts +4 -2
  101. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  102. package/packages/core/src/ports/tickets/priority.ts +127 -21
  103. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  104. package/packages/core/src/ports/tickets/remote.ts +104 -11
  105. package/packages/core/src/ports/tickets/revision.ts +5 -3
  106. package/packages/core/src/ports/tickets/search.ts +9 -0
  107. package/packages/core/src/ports/tickets/tree.ts +8 -6
  108. package/packages/core/src/ports/types.ts +30 -15
  109. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  110. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  111. package/packages/core/src/ports/workspace/create.ts +16 -3
  112. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  113. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  114. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  115. package/packages/core/src/processes/build-execution-state.ts +4 -0
  116. package/packages/core/src/processes/build-runner.ts +14 -1
  117. package/packages/core/src/processes/dispatcher.ts +544 -212
  118. package/packages/core/src/processes/execution-settlement.ts +1 -0
  119. package/packages/core/src/processes/harvest-runner.ts +12 -7
  120. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  121. package/packages/core/src/processes/invocation-budget.ts +176 -0
  122. package/packages/core/src/processes/publication-loss.ts +38 -3
  123. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  124. package/packages/core/src/store/contract.ts +81 -3
  125. package/packages/core/src/store/event-reads.ts +30 -1
  126. package/packages/core/src/store/reduced-reads.ts +23 -0
  127. package/packages/core/src/store/reducer-value-shapes.json +6628 -6469
  128. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  129. package/packages/core/src/store/remote/client.ts +169 -29
  130. package/packages/core/src/store/remote/compatibility.ts +113 -56
  131. package/packages/core/src/store/remote/credentials.ts +4 -1
  132. package/packages/core/src/store/remote/protocol.ts +3 -0
  133. package/packages/core/src/store/remote/released-clients.json +11 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  135. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  136. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  137. package/packages/core/src/store/remote/retry.ts +406 -0
  138. package/packages/core/src/testing/dispatch-read-budget.ts +144 -10
  139. package/packages/core/src/testing/index.ts +2 -0
  140. package/packages/core/src/testing/invocation-budget.ts +42 -0
  141. package/packages/core/src/testing/reduced-read-budget.ts +381 -18
  142. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  143. package/packages/core/src/web/overview-source.ts +19 -6
  144. package/skills/guide/SKILL.md +138 -67
  145. package/skills/guide/references/integration-tree.md +12 -9
  146. package/skills/guide/references/merge-policy.md +7 -2
  147. package/skills/guide/references/operator-api.md +46 -23
  148. package/skills/guide/references/optimization-nodes.md +7 -6
  149. package/skills/guide/references/plugin-authoring.md +46 -18
  150. package/skills/guide/references/remote-store-protocol.md +51 -12
  151. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  152. package/skills/guide/references/restacking.md +48 -3
  153. package/skills/guide/references/setup.md +2 -1
  154. package/skills/guide/references/ticket-migration.md +2 -2
  155. package/skills/operate/SKILL.md +82 -51
  156. package/skills/plan/SKILL.md +4 -3
  157. package/skills/spec/SKILL.md +9 -5
  158. package/skills/tickets/SKILL.md +25 -17
  159. package/templates/hosted-service/package.json +2 -2
@@ -19,7 +19,7 @@ import { parseTicketFile, serializeTicketFile } from './file-codec'
19
19
  import { validateFileTicketId } from './requested-id'
20
20
  import { normalizeStateName } from './states'
21
21
  import { TicketIssueLinksUnsupported } from './issue-links'
22
- import { TicketPriorityUnsupported } from './priority'
22
+ import { TicketPriorityUnsupported, ticketPriority } from './priority'
23
23
  import { encodePortableAsset, decodePortableAsset, type PortableAsset } from './portable-assets'
24
24
 
25
25
  export const MANIFEST = '.ab-migration.json'
@@ -237,7 +237,7 @@ export async function exportTickets(opts: MigrationOptions): Promise<void> {
237
237
  labels: ticket.labels,
238
238
  blockedBy: ticket.blockedBy,
239
239
  issueLinks: ticket.issueLinks,
240
- ...(ticket.priority === 'urgent' ? { priority: ticket.priority } : {}),
240
+ ...(ticketPriority(ticket) !== 'normal' ? { priority: ticket.priority } : {}),
241
241
  idempotencyKey: key,
242
242
  ...(ticket.comments !== undefined ? { comments: ticket.comments } : {}),
243
243
  attachments: await currentAssets(
@@ -460,7 +460,7 @@ export async function importTickets(opts: MigrationOptions): Promise<MigrationRe
460
460
  throw new Error('target source cannot preserve kind/target metadata')
461
461
  if (!opts.source.issueLinks && tickets.some((t) => t.issueLinks?.length))
462
462
  throw new TicketIssueLinksUnsupported(opts.source.name)
463
- if (!opts.source.priority && tickets.some((t) => t.priority === 'urgent'))
463
+ if (!opts.source.priority && tickets.some((t) => ticketPriority(t) !== 'normal'))
464
464
  throw new TicketPriorityUnsupported(opts.source.name)
465
465
  const bundles = new Map<string, PortableAsset[]>()
466
466
  for (const ticket of tickets) {
@@ -588,7 +588,7 @@ export async function importTickets(opts: MigrationOptions): Promise<MigrationRe
588
588
  labels: ticket.labels,
589
589
  ...(opts.source.integrationTree ? { kind: ticket.kind ?? 'work' } : {}),
590
590
  ...(opts.source.issueLinks && links.length ? { issueLinks: links } : {}),
591
- ...(opts.source.priority && ticket.priority === 'urgent'
591
+ ...(opts.source.priority && ticketPriority(ticket) !== 'normal'
592
592
  ? { priority: ticket.priority }
593
593
  : {}),
594
594
  },
@@ -99,10 +99,12 @@ export async function createTicket(
99
99
  input: TicketDraft & { state?: string },
100
100
  options: { blockerErrorPrefix?: string; blockerErrorSuffix?: string } = {},
101
101
  ): Promise<Ticket> {
102
+ // Wrapped first: the facade gives a source without native priority its
103
+ // label fallback, so only a source that still cannot store a level refuses.
104
+ source = compatibleTicketSource(source)
102
105
  refuseUnsupportedIssueLinks(source, input)
103
106
  refuseUnsupportedPriority(source, input)
104
107
  refuseUnsupportedAssignees(source, input)
105
- source = compatibleTicketSource(source)
106
108
  const blockedBy = await knownBlockers(
107
109
  source,
108
110
  input.blockedBy ?? [],
@@ -142,10 +144,10 @@ export async function updateTicket(
142
144
  readAfter = true,
143
145
  expectedRevision?: string,
144
146
  ): Promise<Ticket | null> {
147
+ source = compatibleTicketSource(source)
145
148
  refuseUnsupportedIssueLinks(source, patch)
146
149
  refuseUnsupportedPriority(source, patch)
147
150
  refuseUnsupportedAssignees(source, patch)
148
- source = compatibleTicketSource(source)
149
151
  try {
150
152
  if (expectedRevision !== undefined)
151
153
  await mutateTicketIfRevision(source, id, expectedRevision, { kind: 'update', patch })
@@ -0,0 +1,213 @@
1
+ import type {
2
+ Ticket,
3
+ TicketCriteria,
4
+ TicketDraft,
5
+ TicketMutation,
6
+ TicketPriority,
7
+ TicketSearchHit,
8
+ TicketSource,
9
+ TicketUpdate,
10
+ } from '../types'
11
+ import { checkTicketRevision, TicketRevisionConflict } from './revision'
12
+ import { priorityRank } from './priority'
13
+
14
+ /** Every priority label starts with this prefix. */
15
+ export const PRIORITY_LABEL_PREFIX = 'priority:'
16
+
17
+ /** The labels a source without native priority stores levels as. `normal`
18
+ * has none: it is the absence of every priority label. */
19
+ export const PRIORITY_LABELS: Readonly<Record<Exclude<TicketPriority, 'normal'>, string>> = {
20
+ urgent: 'priority:urgent',
21
+ high: 'priority:high',
22
+ low: 'priority:low',
23
+ }
24
+
25
+ /** The label a level is stored as; `undefined` for `normal`. */
26
+ export function priorityLabel(level: TicketPriority): string | undefined {
27
+ return level === 'normal' ? undefined : PRIORITY_LABELS[level]
28
+ }
29
+
30
+ function labelLevel(name: string): Exclude<TicketPriority, 'normal'> | undefined {
31
+ const lower = name.toLowerCase()
32
+ for (const [level, label] of Object.entries(PRIORITY_LABELS))
33
+ if (label === lower) return level as Exclude<TicketPriority, 'normal'>
34
+ return undefined
35
+ }
36
+
37
+ /** Exact, case-insensitive match against the three priority labels. */
38
+ export function isPriorityLabel(name: string): boolean {
39
+ return labelLevel(name) !== undefined
40
+ }
41
+
42
+ /** The highest level among the labels; `undefined` when none is a priority
43
+ * label. */
44
+ export function labelPriority(labels: readonly string[]): TicketPriority | undefined {
45
+ let best: TicketPriority | undefined
46
+ for (const name of labels) {
47
+ const level = labelLevel(name)
48
+ if (level !== undefined && (best === undefined || priorityRank(level) < priorityRank(best)))
49
+ best = level
50
+ }
51
+ return best
52
+ }
53
+
54
+ /** The level read from labels, moved out of `labels` into `priority`. */
55
+ function fromLabels<T extends { labels: string[]; priority?: TicketPriority }>(value: T): T {
56
+ const { priority: _raw, ...rest } = value
57
+ const labels: readonly string[] = value.labels ?? []
58
+ const level = labelPriority(labels)
59
+ if (level === undefined) return 'priority' in value ? (rest as T) : value
60
+ return { ...rest, labels: labels.filter((name) => !isPriorityLabel(name)), priority: level } as T
61
+ }
62
+
63
+ function refusePriorityLabels(source: string, labels: readonly string[] | undefined, use: string) {
64
+ const named = (labels ?? []).filter(isPriorityLabel)
65
+ if (named.length > 0)
66
+ throw new Error(
67
+ `${named.map((name) => `"${name}"`).join(', ')} ${named.length === 1 ? 'is' : 'are'} how the ${source} ticket source stores ticket priority; ${use} — nothing was written`,
68
+ )
69
+ }
70
+
71
+ function refuseCriteria(source: string, criteria: { labels?: string[] } | undefined): void {
72
+ refusePriorityLabels(source, criteria?.labels, 'it cannot filter tickets or gate readiness')
73
+ }
74
+
75
+ function refuseWriteLabels(source: string, labels: readonly string[] | undefined): void {
76
+ refusePriorityLabels(source, labels, 'set priority with --priority instead')
77
+ }
78
+
79
+ function sameLabels(a: readonly string[], b: readonly string[]): boolean {
80
+ const left = new Set(a.map((name) => name.toLowerCase()))
81
+ const right = new Set(b.map((name) => name.toLowerCase()))
82
+ return left.size === right.size && [...left].every((name) => right.has(name))
83
+ }
84
+
85
+ /**
86
+ * The raw patch for a facade patch: the full label set rebuilt from the
87
+ * current raw labels. Visible labels come from the patch or the current
88
+ * ticket; priority labels are exactly the named level's, or the current ones
89
+ * untouched. `null` means the write changes nothing.
90
+ */
91
+ function rawPatch(
92
+ current: Ticket,
93
+ patch: TicketUpdate,
94
+ kindLabel: string | undefined,
95
+ ): TicketUpdate | null {
96
+ const { priority, ...rest } = patch
97
+ let visible = patch.labels ?? current.labels.filter((name) => !isPriorityLabel(name))
98
+ // Only a source recording kind as a label keeps that label in step with a
99
+ // kind change written beside priority; every other label is preserved.
100
+ if (kindLabel !== undefined && patch.labels === undefined && patch.kind !== undefined) {
101
+ visible = visible.filter((name) => name !== kindLabel)
102
+ if (patch.kind === 'node') visible.push(kindLabel)
103
+ }
104
+ const kept =
105
+ priority === undefined
106
+ ? current.labels.filter(isPriorityLabel)
107
+ : [priorityLabel(priority)].filter((name): name is string => name !== undefined)
108
+ const labels = [...visible, ...kept]
109
+ const others = Object.keys(rest).filter((key) => key !== 'labels')
110
+ if (others.length === 0 && sameLabels(labels, current.labels)) return null
111
+ return { ...rest, labels }
112
+ }
113
+
114
+ const REVISION_RETRIES = 2
115
+
116
+ /**
117
+ * The label fallback for a source without native priority: levels other
118
+ * than `normal` are stored as exactly one `priority:<level>` label. Reads
119
+ * map the labels a read already returned, so they cost no extra request;
120
+ * priority labels are reported as `priority`, never among `labels`, and the
121
+ * highest wins when several are present. A write naming priority or labels
122
+ * reads the raw ticket once and rebuilds its complete label set, so a
123
+ * labels replacement keeps priority and a priority write keeps every other
124
+ * label. Listing criteria and written labels that name a priority label are
125
+ * refused before any request.
126
+ */
127
+ export function priorityLabelSource(source: TicketSource): TicketSource {
128
+ const name = source.name
129
+ async function current(id: string): Promise<Ticket> {
130
+ const ticket = await source.get(id)
131
+ if (!ticket) throw new Error(`${name} ticket source: unknown ticket "${id}"`)
132
+ return ticket
133
+ }
134
+ async function guarded(id: string, revision: string, patch: TicketUpdate): Promise<void> {
135
+ const raw = await current(id)
136
+ checkTicketRevision(raw, revision)
137
+ const write = rawPatch(raw, patch, source.kindLabel)
138
+ if (write === null) return
139
+ await source.mutateIfRevision!(id, revision, { kind: 'update', patch: write })
140
+ }
141
+ async function update(id: string, patch: TicketUpdate): Promise<void> {
142
+ if (patch.priority === undefined && patch.labels === undefined) return source.update(id, patch)
143
+ refuseWriteLabels(name, patch.labels)
144
+ if (!source.mutateIfRevision) {
145
+ const write = rawPatch(await current(id), patch, source.kindLabel)
146
+ if (write !== null) await source.update(id, write)
147
+ return
148
+ }
149
+ for (let attempt = 0; ; attempt++) {
150
+ const raw = await current(id)
151
+ try {
152
+ return await guarded(id, raw.revision, patch)
153
+ } catch (error) {
154
+ if (!(error instanceof TicketRevisionConflict) || attempt >= REVISION_RETRIES) throw error
155
+ }
156
+ }
157
+ }
158
+ const facade = Object.create(source) as TicketSource
159
+ return new Proxy(facade, {
160
+ get(_facade, property) {
161
+ if (property === 'priority') return true
162
+ const value = Reflect.get(source, property, source)
163
+ if (typeof value !== 'function') return value
164
+ if (property === 'get')
165
+ return async (id: string) => {
166
+ const ticket = await source.get(id)
167
+ return ticket ? fromLabels(ticket) : null
168
+ }
169
+ if (property === 'listReady' || property === 'listPage')
170
+ return async (criteria: TicketCriteria, ...args: unknown[]) => {
171
+ refuseCriteria(name, criteria)
172
+ const listing = await value.call(source, criteria, ...args)
173
+ return { ...listing, tickets: listing.tickets.map(fromLabels) }
174
+ }
175
+ if (property === 'listAll' || property === 'listTargeting')
176
+ return async (...args: unknown[]) => {
177
+ const listing = await value.apply(source, args)
178
+ return { ...listing, tickets: listing.tickets.map(fromLabels) }
179
+ }
180
+ if (property === 'readExportSnapshot')
181
+ return async (...args: unknown[]) =>
182
+ ((await value.apply(source, args)) as Ticket[]).map(fromLabels)
183
+ if (property === 'search')
184
+ return async (query: { labels?: string[] }) => {
185
+ refuseCriteria(name, query)
186
+ const page = await value.call(source, query)
187
+ return { ...page, tickets: page.tickets.map((hit: TicketSearchHit) => fromLabels(hit)) }
188
+ }
189
+ if (property === 'create')
190
+ return async (draft: TicketDraft, ...args: unknown[]) => {
191
+ refuseWriteLabels(name, draft.labels)
192
+ const { priority, ...rest } = draft
193
+ const label = priority === undefined ? undefined : priorityLabel(priority)
194
+ const write: TicketDraft =
195
+ label === undefined ? rest : { ...rest, labels: [...(rest.labels ?? []), label] }
196
+ return fromLabels(await value.call(source, write, ...args))
197
+ }
198
+ if (property === 'update') return update
199
+ if (property === 'mutateIfRevision')
200
+ return async (id: string, revision: string, mutation: TicketMutation) => {
201
+ if (
202
+ mutation.kind !== 'update' ||
203
+ (mutation.patch.priority === undefined && mutation.patch.labels === undefined)
204
+ )
205
+ return value.call(source, id, revision, mutation)
206
+ if (!revision.trim()) throw new Error('expected revision must be nonblank')
207
+ refuseWriteLabels(name, mutation.patch.labels)
208
+ return guarded(id, revision, mutation.patch)
209
+ }
210
+ return value.bind(source)
211
+ },
212
+ })
213
+ }
@@ -1,12 +1,20 @@
1
1
  import { z } from 'zod'
2
2
  import type { TicketStartPriority } from '../../events/repository'
3
- import type { Ticket, TicketPriority, TicketSource } from '../types'
3
+ import type { BuildPriority, Ticket, TicketPriority, TicketSource } from '../types'
4
4
 
5
- export type { TicketPriority } from '../types'
5
+ export type { BuildPriority, TicketPriority } from '../types'
6
6
 
7
- export const ticketPrioritySchema = z.enum(['urgent', 'normal'])
7
+ /** Every ticket priority level, highest first. */
8
+ export const TICKET_PRIORITIES = ['urgent', 'high', 'normal', 'low'] as const
8
9
 
9
- /** A write naming `urgent` reached a source that cannot store priority. */
10
+ export const ticketPrioritySchema = z.enum(TICKET_PRIORITIES)
11
+
12
+ /** A build's slot-admission level, as operators name it: the four ticket
13
+ * levels. Persisted facts encode it compatibly (`prioritySetPayload`). */
14
+ export const buildPrioritySchema = ticketPrioritySchema
15
+
16
+ /** A write naming a level other than `normal` reached a source that cannot
17
+ * store priority. */
10
18
  export class TicketPriorityUnsupported extends Error {
11
19
  constructor(readonly source: string) {
12
20
  super(`${source} ticket source cannot store ticket priority; nothing was written`)
@@ -14,17 +22,17 @@ export class TicketPriorityUnsupported extends Error {
14
22
  }
15
23
  }
16
24
 
17
- /** Refuse before any write: only `urgent` needs the capability; `normal` is the
18
- * value every source already holds. */
25
+ /** Refuse before any write: every level but `normal` needs the capability;
26
+ * `normal` is the value every source already holds. */
19
27
  export function refuseUnsupportedPriority(
20
28
  source: Pick<TicketSource, 'name' | 'priority'>,
21
29
  patch: { priority?: unknown },
22
30
  ): void {
23
- if (patch.priority === 'urgent' && !source.priority)
31
+ if (patch.priority !== undefined && patch.priority !== 'normal' && !source.priority)
24
32
  throw new TicketPriorityUnsupported(source.name)
25
33
  }
26
34
 
27
- /** Refuse `urgent`, then drop a `normal` no-op for a source without the
35
+ /** Refuse any level but `normal`, then drop a `normal` no-op for a source without the
28
36
  * capability so its write (and wire) never names priority. */
29
37
  export function withoutUnsupportedPriority<T extends { priority?: unknown }>(
30
38
  source: Pick<TicketSource, 'name' | 'priority'>,
@@ -36,12 +44,48 @@ export function withoutUnsupportedPriority<T extends { priority?: unknown }>(
36
44
  return rest as T
37
45
  }
38
46
 
39
- /** Absent and anything but `urgent` read as normal. */
40
- export function ticketPriority(ticket: Pick<Ticket, 'priority'>): TicketPriority {
41
- return ticket.priority === 'urgent' ? 'urgent' : 'normal'
47
+ /** The stored level; absent and unrecognised values read as normal. */
48
+ export function ticketPriority(ticket: { priority?: unknown }): TicketPriority {
49
+ const level = ticket.priority
50
+ return typeof level === 'string' && (TICKET_PRIORITIES as readonly string[]).includes(level)
51
+ ? (level as TicketPriority)
52
+ : 'normal'
53
+ }
54
+
55
+ /** The level a ticket is claimed at, and the level its build takes. */
56
+ export function dispatchPriority(ticket: { priority?: unknown }): BuildPriority {
57
+ return ticketPriority(ticket)
58
+ }
59
+
60
+ /** 0 for urgent through 3 for low. */
61
+ export function priorityRank(level: TicketPriority): number {
62
+ return TICKET_PRIORITIES.indexOf(level)
63
+ }
64
+
65
+ /** Stable four-tier sort: urgent, high, normal, low, each in input order. */
66
+ export function byPriority<T extends { priority?: unknown }>(tickets: readonly T[]): T[] {
67
+ const tiers: T[][] = TICKET_PRIORITIES.map(() => [])
68
+ for (const ticket of tickets) tiers[priorityRank(ticketPriority(ticket))]?.push(ticket)
69
+ return tiers.flat()
70
+ }
71
+
72
+ /** Stable four-tier sort by a caller's level: urgent, high, normal, low,
73
+ * each in input order. */
74
+ export function byPriorityBy<T>(items: readonly T[], level: (item: T) => TicketPriority): T[] {
75
+ const tiers: T[][] = TICKET_PRIORITIES.map(() => [])
76
+ for (const item of items) tiers[priorityRank(level(item))]?.push(item)
77
+ return tiers.flat()
42
78
  }
43
79
 
44
- /** Stable partition: urgent candidates first, then the rest, each in input order. */
80
+ /** The value with `priority` always named, `normal` when absent. */
81
+ export function namedPriority<T extends { priority?: unknown }>(
82
+ value: T,
83
+ ): Omit<T, 'priority'> & { priority: TicketPriority } {
84
+ return { ...value, priority: ticketPriority(value) }
85
+ }
86
+
87
+ /** Stable partition: urgent candidates first, then the rest, each in input
88
+ * order. Kept for plugins; dispatch orders by `byPriority`. */
45
89
  export function urgentFirst<T extends Pick<Ticket, 'priority'>>(tickets: readonly T[]): T[] {
46
90
  const urgent: T[] = []
47
91
  const normal: T[] = []
@@ -50,8 +94,8 @@ export function urgentFirst<T extends Pick<Ticket, 'priority'>>(tickets: readonl
50
94
  }
51
95
 
52
96
  /** Stable partition by a caller's tier: urgent first, then the rest, each in
53
- * input order. */
54
- export function urgentFirstBy<T>(tickets: readonly T[], tier: (ticket: T) => TicketPriority): T[] {
97
+ * input order. Kept for plugins; dispatch orders by `byPriorityBy`. */
98
+ export function urgentFirstBy<T>(tickets: readonly T[], tier: (ticket: T) => BuildPriority): T[] {
55
99
  const urgent: T[] = []
56
100
  const normal: T[] = []
57
101
  for (const ticket of tickets) (tier(ticket) === 'urgent' ? urgent : normal).push(ticket)
@@ -60,16 +104,78 @@ export function urgentFirstBy<T>(tickets: readonly T[], tier: (ticket: T) => Tic
60
104
 
61
105
  export function parsePriorityFlag(value: string, flag = '--priority'): TicketPriority {
62
106
  const result = ticketPrioritySchema.safeParse(value.trim())
63
- if (!result.success) throw new Error(`${flag}: expected urgent or normal, got "${value}"`)
107
+ if (!result.success)
108
+ throw new Error(`${flag}: expected urgent, high, normal or low, got "${value}"`)
109
+ return result.data
110
+ }
111
+
112
+ /** `ab priority`: a build's slot-admission level. */
113
+ export function parseBuildPriorityFlag(value: string, flag = 'priority'): BuildPriority {
114
+ const result = buildPrioritySchema.safeParse(value.trim())
115
+ if (!result.success)
116
+ throw new Error(`${flag}: expected urgent, high, normal or low, got "${value}"`)
64
117
  return result.data
65
118
  }
66
119
 
67
- const START_PRIORITIES: readonly TicketStartPriority[] = ['manual', 'urgent', 'normal']
120
+ /** Every start request admission tier, in admission order: `manual` first,
121
+ * then the four ticket levels. */
122
+ export const START_TIERS = ['manual', 'urgent', 'high', 'normal', 'low'] as const
123
+ export type StartTier = (typeof START_TIERS)[number]
124
+
125
+ export const startTierSchema = z.enum(START_TIERS)
68
126
 
69
127
  /** `ab start --priority`: a start request's admission tier. */
70
- export function parseStartPriorityFlag(value: string, flag = '--priority'): TicketStartPriority {
71
- const priority = START_PRIORITIES.find((tier) => tier === value.trim())
72
- if (priority === undefined)
73
- throw new Error(`${flag}: expected manual, urgent or normal, got "${value}"`)
74
- return priority
128
+ export function parseStartPriorityFlag(value: string, flag = '--priority'): StartTier {
129
+ const tier = START_TIERS.find((entry) => entry === value.trim())
130
+ if (tier === undefined)
131
+ throw new Error(`${flag}: expected manual, urgent, high, normal or low, got "${value}"`)
132
+ return tier
133
+ }
134
+
135
+ /** The levels persisted facts carry in their additive `level` key. Older
136
+ * readers drop the key and see the fact's two-level field: normal. */
137
+ export type RefinedLevel = 'high' | 'low'
138
+
139
+ function refined(level: string): level is RefinedLevel {
140
+ return level === 'high' || level === 'low'
141
+ }
142
+
143
+ /** `build.created`'s priority fields for a build's level: `urgent` in
144
+ * `priority`, `high` and `low` in `level`, normal omitted. */
145
+ export function createdPriorityFields(level: BuildPriority): {
146
+ priority?: 'urgent'
147
+ level?: RefinedLevel
148
+ } {
149
+ if (level === 'urgent') return { priority: 'urgent' }
150
+ return refined(level) ? { level } : {}
151
+ }
152
+
153
+ /** A `build.priority-set` payload for a level: `priority` stays two-level
154
+ * (high and low write `normal`) and `level` refines it. */
155
+ export function prioritySetPayload(level: BuildPriority): {
156
+ priority: 'urgent' | 'normal'
157
+ level?: RefinedLevel
158
+ } {
159
+ return {
160
+ priority: level === 'urgent' ? 'urgent' : 'normal',
161
+ ...(refined(level) ? { level } : {}),
162
+ }
163
+ }
164
+
165
+ /** A start request's persisted tier fields: `priority` stays in its
166
+ * three-tier domain (high and low write `normal`) and `level` refines it. */
167
+ export function startTierFields(tier: StartTier): {
168
+ priority: TicketStartPriority
169
+ level?: RefinedLevel
170
+ } {
171
+ return refined(tier) ? { priority: 'normal', level: tier } : { priority: tier }
172
+ }
173
+
174
+ /** The admission tier a persisted start request names: its `level` when
175
+ * present, otherwise its `priority`. */
176
+ export function startTierOf(request: {
177
+ priority: TicketStartPriority
178
+ level?: RefinedLevel
179
+ }): StartTier {
180
+ return request.level ?? request.priority
75
181
  }
@@ -37,6 +37,15 @@ export const TICKET_ISSUE_LINKS_CAPABILITY = '1'
37
37
  export const TICKET_PRIORITY_HEADER = 'x-autobuild-ticket-priority'
38
38
  export const TICKET_PRIORITY_CAPABILITY = '1'
39
39
 
40
+ /** Explicit opt-in: released clients decode priority strictly as `urgent` or
41
+ * `normal`. Servers answer all four levels (and search-hit priority) only to
42
+ * clients sending it; a client sending only the priority header reads `high`
43
+ * and `low` as `normal`. Servers echo it on every ticket response, so a client
44
+ * writing `high` or `low` can tell an older server's strict-schema refusal
45
+ * from an ordinary validation failure. */
46
+ export const TICKET_PRIORITY_LEVELS_HEADER = 'x-autobuild-ticket-priority-levels'
47
+ export const TICKET_PRIORITY_LEVELS_CAPABILITY = '1'
48
+
40
49
  /** Explicit opt-in: released clients decode dependency states strictly without
41
50
  * `state`. Servers include each blocker's native state name only for clients
42
51
  * that send this header; an older server ignores it and omits the field. */
@@ -140,6 +149,7 @@ export const ticketSearchHitWireSchema = z.strictObject({
140
149
  .string()
141
150
  .refine((v) => v.trim().length > 0)
142
151
  .optional(),
152
+ priority: ticketPrioritySchema.optional(),
143
153
  })
144
154
  export const ticketSearchPageWireSchema = z.strictObject({
145
155
  tickets: z.array(ticketSearchHitWireSchema),