@defrex/autobuild 1.4.1 → 1.5.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 (201) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +440 -95
  3. package/bin/ab-dispatch-kernel.ts +1 -0
  4. package/docs/accounts.md +9 -0
  5. package/docs/agent-runtimes.md +1 -0
  6. package/docs/answering-blocked-builds.md +2 -1
  7. package/docs/architecture.md +290 -130
  8. package/docs/assets/headline-wide.png +0 -0
  9. package/docs/build-store.md +33 -3
  10. package/docs/cli.md +2 -1
  11. package/docs/configuration-overview.md +9 -0
  12. package/docs/configuration.md +166 -101
  13. package/docs/dispatcher-hosting.md +19 -3
  14. package/docs/dispatcher.md +9 -4
  15. package/docs/integration-overview.md +2 -2
  16. package/docs/integration-tree.md +91 -28
  17. package/docs/merge-policy.md +28 -9
  18. package/docs/operator-api.md +43 -18
  19. package/docs/operator-surfaces.md +1 -1
  20. package/docs/plugin-authoring.md +85 -8
  21. package/docs/remote-store-protocol.md +25 -7
  22. package/docs/remote-ticket-protocol.md +126 -12
  23. package/docs/restacking.md +20 -6
  24. package/docs/seams.md +2 -2
  25. package/docs/setup.md +19 -13
  26. package/docs/spec-standard.md +2 -1
  27. package/docs/ticket-dependencies.md +26 -8
  28. package/docs/ticket-migration.md +70 -7
  29. package/docs/ticket-sources.md +82 -5
  30. package/docs/tickets.md +34 -2
  31. package/docs/troubleshooting.md +2 -2
  32. package/docs/verification.md +5 -5
  33. package/docs/website.md +8 -0
  34. package/docs/workspaces.md +1 -1
  35. package/package.json +5 -4
  36. package/packages/core/src/accounts/hosted-readiness.ts +21 -0
  37. package/packages/core/src/cli/attention.ts +1 -0
  38. package/packages/core/src/cli/build-control.ts +36 -12
  39. package/packages/core/src/cli/connect.ts +9 -18
  40. package/packages/core/src/cli/context.ts +44 -0
  41. package/packages/core/src/cli/dashboard/configuration.ts +11 -0
  42. package/packages/core/src/cli/dashboard/model.ts +40 -10
  43. package/packages/core/src/cli/dashboard/queue.ts +21 -0
  44. package/packages/core/src/cli/dashboard/render.ts +40 -22
  45. package/packages/core/src/cli/dispatch-frontend.ts +63 -30
  46. package/packages/core/src/cli/dispatch-mode.ts +35 -16
  47. package/packages/core/src/cli/dispatch-repository-feed.ts +40 -11
  48. package/packages/core/src/cli/dispatch.ts +154 -47
  49. package/packages/core/src/cli/help.ts +59 -22
  50. package/packages/core/src/cli/init-hosted-accounts.ts +54 -0
  51. package/packages/core/src/cli/init-readiness-remote.ts +16 -3
  52. package/packages/core/src/cli/init-validation.ts +144 -42
  53. package/packages/core/src/cli/issue-links.ts +67 -0
  54. package/packages/core/src/cli/main.ts +32 -15
  55. package/packages/core/src/cli/pr-summary-publication.ts +38 -7
  56. package/packages/core/src/cli/publication-settlement.ts +36 -24
  57. package/packages/core/src/cli/repository-status.ts +201 -49
  58. package/packages/core/src/cli/status.ts +41 -3
  59. package/packages/core/src/cli/terminals.ts +37 -2
  60. package/packages/core/src/cli/ticket-editor.ts +20 -6
  61. package/packages/core/src/cli/ticket.ts +264 -46
  62. package/packages/core/src/cli/triage-count-sampler.ts +59 -0
  63. package/packages/core/src/cli/watch.ts +4 -0
  64. package/packages/core/src/config/live.ts +45 -4
  65. package/packages/core/src/config/load.ts +9 -0
  66. package/packages/core/src/config/pipeline-source.ts +6 -2
  67. package/packages/core/src/config/ready-assignee.ts +86 -0
  68. package/packages/core/src/config/schema.ts +164 -36
  69. package/packages/core/src/distribution-packaging.ts +1 -1
  70. package/packages/core/src/events/catalog.ts +5 -0
  71. package/packages/core/src/events/compatibility.ts +2 -1
  72. package/packages/core/src/events/payloads.ts +70 -0
  73. package/packages/core/src/events/policy.ts +8 -0
  74. package/packages/core/src/events/repository.ts +91 -28
  75. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +41 -0
  76. package/packages/core/src/kernel/build-identity.ts +12 -0
  77. package/packages/core/src/kernel/change-presence.ts +139 -6
  78. package/packages/core/src/kernel/dispatch-capacity.ts +80 -14
  79. package/packages/core/src/kernel/dispatch-status.ts +10 -1
  80. package/packages/core/src/kernel/dispatch-upgrade.ts +104 -5
  81. package/packages/core/src/kernel/engine.ts +4 -2
  82. package/packages/core/src/kernel/finalize-pr-rejection.ts +95 -0
  83. package/packages/core/src/kernel/generators/repository-journals.ts +15 -1
  84. package/packages/core/src/kernel/harvest.ts +4 -1
  85. package/packages/core/src/kernel/integration-completeness.ts +104 -17
  86. package/packages/core/src/kernel/integration-landing.ts +17 -0
  87. package/packages/core/src/kernel/integration-state.ts +17 -0
  88. package/packages/core/src/kernel/issue-keywords.ts +202 -0
  89. package/packages/core/src/kernel/janitor-failure.ts +11 -0
  90. package/packages/core/src/kernel/kernel-git.ts +87 -0
  91. package/packages/core/src/kernel/landing-readiness.ts +25 -17
  92. package/packages/core/src/kernel/log-index.ts +1 -1
  93. package/packages/core/src/kernel/node-issue-links.ts +142 -0
  94. package/packages/core/src/kernel/node-parent.ts +6 -0
  95. package/packages/core/src/kernel/node-restack-transaction.ts +2 -0
  96. package/packages/core/src/kernel/pr-summary.ts +24 -0
  97. package/packages/core/src/kernel/read-deferrals.ts +75 -12
  98. package/packages/core/src/kernel/read-facts.ts +32 -1
  99. package/packages/core/src/kernel/reconcile-restack.ts +1 -1
  100. package/packages/core/src/kernel/reducer-registry.ts +31 -1
  101. package/packages/core/src/kernel/reducer.ts +90 -2
  102. package/packages/core/src/kernel/ticket-preparation.ts +12 -0
  103. package/packages/core/src/kernel/verify-budget.ts +43 -0
  104. package/packages/core/src/operator/index.ts +3 -1
  105. package/packages/core/src/operator/presentation.ts +3 -0
  106. package/packages/core/src/operator/protocol.ts +38 -2
  107. package/packages/core/src/operator/query.ts +66 -29
  108. package/packages/core/src/operator/registry.ts +47 -26
  109. package/packages/core/src/operator/tickets.ts +77 -10
  110. package/packages/core/src/plugin-sdk/index.ts +13 -0
  111. package/packages/core/src/plugins/manifest.ts +1 -1
  112. package/packages/core/src/plugins/registry.ts +1 -0
  113. package/packages/core/src/ports/forge/contract.ts +69 -0
  114. package/packages/core/src/ports/forge/create.ts +5 -0
  115. package/packages/core/src/ports/forge/fake.ts +184 -3
  116. package/packages/core/src/ports/forge/git-rewrite.ts +4 -2
  117. package/packages/core/src/ports/forge/github.ts +175 -38
  118. package/packages/core/src/ports/forge/local-git.ts +14 -0
  119. package/packages/core/src/ports/forge/readiness.ts +10 -0
  120. package/packages/core/src/ports/forge-failure.ts +43 -0
  121. package/packages/core/src/ports/runner/claude.ts +7 -1
  122. package/packages/core/src/ports/runner/codex.ts +7 -2
  123. package/packages/core/src/ports/runner/native-cli-fixture.ts +2 -1
  124. package/packages/core/src/ports/runner/pi.ts +7 -1
  125. package/packages/core/src/ports/runner/runtime.ts +3 -0
  126. package/packages/core/src/ports/runner/start-prompt.ts +37 -0
  127. package/packages/core/src/ports/tickets/contract.ts +320 -7
  128. package/packages/core/src/ports/tickets/create.ts +72 -17
  129. package/packages/core/src/ports/tickets/fake.ts +18 -0
  130. package/packages/core/src/ports/tickets/file-codec.ts +20 -0
  131. package/packages/core/src/ports/tickets/file.ts +43 -1
  132. package/packages/core/src/ports/tickets/github-fake.ts +1123 -0
  133. package/packages/core/src/ports/tickets/github-issues.ts +431 -0
  134. package/packages/core/src/ports/tickets/github-validators.ts +194 -0
  135. package/packages/core/src/ports/tickets/github.ts +2029 -0
  136. package/packages/core/src/ports/tickets/hosted-index.ts +34 -3
  137. package/packages/core/src/ports/tickets/issue-links.ts +86 -0
  138. package/packages/core/src/ports/tickets/lifecycle.ts +60 -4
  139. package/packages/core/src/ports/tickets/linear.ts +66 -6
  140. package/packages/core/src/ports/tickets/migration.ts +290 -68
  141. package/packages/core/src/ports/tickets/operations.ts +98 -12
  142. package/packages/core/src/ports/tickets/priority.ts +55 -0
  143. package/packages/core/src/ports/tickets/remote-protocol.ts +195 -29
  144. package/packages/core/src/ports/tickets/remote.ts +188 -13
  145. package/packages/core/src/ports/tickets/revision.ts +22 -1
  146. package/packages/core/src/ports/tickets/states.ts +43 -0
  147. package/packages/core/src/ports/tickets/tree.ts +58 -12
  148. package/packages/core/src/ports/tickets/update.ts +12 -2
  149. package/packages/core/src/ports/types.ts +194 -11
  150. package/packages/core/src/ports/workspace/commit-preservation.ts +135 -13
  151. package/packages/core/src/ports/workspace/git-worktree.ts +3 -1
  152. package/packages/core/src/ports/workspace/vercel-sandbox.ts +132 -27
  153. package/packages/core/src/processes/build-runner.ts +99 -21
  154. package/packages/core/src/processes/dispatcher.ts +1080 -533
  155. package/packages/core/src/processes/execution-no-progress.ts +5 -0
  156. package/packages/core/src/processes/harvest-runner.ts +17 -8
  157. package/packages/core/src/processes/harvest.ts +5 -8
  158. package/packages/core/src/processes/tick-publication.ts +12 -2
  159. package/packages/core/src/processes/ticket-scan-schedule.ts +78 -0
  160. package/packages/core/src/processes/workspace-preservation.ts +37 -2
  161. package/packages/core/src/runtime-identity.ts +10 -2
  162. package/packages/core/src/scenarios/harness.ts +4 -0
  163. package/packages/core/src/store/adapter.ts +7 -1
  164. package/packages/core/src/store/contract.ts +83 -2
  165. package/packages/core/src/store/digest.ts +32 -1
  166. package/packages/core/src/store/reducer-value-shapes.json +4187 -3391
  167. package/packages/core/src/store/remote/protocol.ts +2 -0
  168. package/packages/core/src/store/remote/released-clients.json +22 -0
  169. package/packages/core/src/store/remote/released-reducer-values/1.5.0.json +26924 -0
  170. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  171. package/packages/core/src/store/repo-state-events.ts +2 -0
  172. package/packages/core/src/store/types.ts +5 -0
  173. package/packages/core/src/testing/dispatch-read-budget.ts +729 -123
  174. package/packages/core/src/testing/index.ts +18 -1
  175. package/packages/core/src/testing/presence-history.ts +79 -0
  176. package/packages/core/src/testing/reduced-read-budget.ts +1197 -31
  177. package/packages/core/src/testing/upgrade-generations.ts +77 -0
  178. package/skills/code-review/SKILL.md +4 -3
  179. package/skills/finalize/SKILL.md +18 -2
  180. package/skills/guide/SKILL.md +382 -139
  181. package/skills/guide/references/accounts.md +9 -0
  182. package/skills/guide/references/integration-tree.md +91 -28
  183. package/skills/guide/references/merge-policy.md +28 -9
  184. package/skills/guide/references/operator-api.md +43 -18
  185. package/skills/guide/references/plugin-authoring.md +85 -8
  186. package/skills/guide/references/remote-store-protocol.md +25 -7
  187. package/skills/guide/references/remote-ticket-protocol.md +126 -12
  188. package/skills/guide/references/restacking.md +20 -6
  189. package/skills/guide/references/setup.md +19 -13
  190. package/skills/guide/references/spec-standard.md +2 -1
  191. package/skills/guide/references/ticket-dependencies.md +26 -8
  192. package/skills/guide/references/ticket-migration.md +70 -7
  193. package/skills/harvest-review/SKILL.md +4 -3
  194. package/skills/implement/SKILL.md +20 -1
  195. package/skills/operate/SKILL.md +103 -28
  196. package/skills/plan/SKILL.md +1 -1
  197. package/skills/reconcile/SKILL.md +5 -4
  198. package/skills/spec/SKILL.md +15 -2
  199. package/skills/tickets/SKILL.md +114 -37
  200. package/templates/autobuild.toml +5 -0
  201. package/templates/hosted-service/package.json +2 -2
@@ -1,10 +1,17 @@
1
- import { compatibleTicketSource, normalizeTicket } from './tree'
1
+ import { compatibleTicketSource, normalizeSourceTicket } from './tree'
2
+ import {
3
+ normalizeIssueLinks,
4
+ refuseUnsupportedIssueLinks,
5
+ TicketIssueLinksUnsupported,
6
+ } from './issue-links'
7
+ import { refuseUnsupportedPriority, TicketPriorityUnsupported } from './priority'
2
8
  import {
3
9
  mutateTicketIfRevision,
4
10
  TicketRevisionConflict,
5
11
  TicketRevisionUnsupported,
6
12
  } from './revision'
7
- import type { Config } from '../../config/schema'
13
+ import type { Config, TicketsConfig } from '../../config/schema'
14
+ import { holdsState, TICKET_MOVE_ROLES, ticketLifecycle, type TicketMoveRole } from './lifecycle'
8
15
  import { readyCriteria } from '../../processes/dispatcher'
9
16
  import type { Ticket, TicketDraft, TicketSource, TicketUpdate } from '../types'
10
17
 
@@ -29,7 +36,7 @@ export function missingTicket(source: TicketSource, id: string): TicketOperation
29
36
  export async function requireTicket(source: TicketSource, id: string): Promise<Ticket> {
30
37
  const ticket = await source.get(id)
31
38
  if (ticket === null) throw missingTicket(source, id)
32
- return normalizeTicket(ticket, !!source.integrationTree)
39
+ return normalizeSourceTicket(source, ticket)
33
40
  }
34
41
 
35
42
  export async function requirePostMutationTicket(
@@ -44,7 +51,7 @@ export async function requirePostMutationTicket(
44
51
  `ticket "${id}" disappeared from the configured ${source.name} ticket source after ${operation}`,
45
52
  )
46
53
  }
47
- return normalizeTicket(ticket, !!source.integrationTree)
54
+ return normalizeSourceTicket(source, ticket)
48
55
  }
49
56
 
50
57
  export function ticketListCriteria(
@@ -56,6 +63,16 @@ export function ticketListCriteria(
56
63
  : filters
57
64
  }
58
65
 
66
+ /** Typed failures operator transports map themselves rather than as a generic refusal. */
67
+ function passthrough(error: unknown): boolean {
68
+ return (
69
+ error instanceof TicketRevisionConflict ||
70
+ error instanceof TicketRevisionUnsupported ||
71
+ error instanceof TicketIssueLinksUnsupported ||
72
+ error instanceof TicketPriorityUnsupported
73
+ )
74
+ }
75
+
59
76
  async function knownBlockers(
60
77
  source: TicketSource,
61
78
  blockerIds: string[],
@@ -80,6 +97,8 @@ export async function createTicket(
80
97
  input: TicketDraft & { state?: string },
81
98
  options: { blockerErrorPrefix?: string; blockerErrorSuffix?: string } = {},
82
99
  ): Promise<Ticket> {
100
+ refuseUnsupportedIssueLinks(source, input)
101
+ refuseUnsupportedPriority(source, input)
83
102
  source = compatibleTicketSource(source)
84
103
  const blockedBy = await knownBlockers(
85
104
  source,
@@ -94,14 +113,17 @@ export async function createTicket(
94
113
  body: input.body,
95
114
  ...(input.labels !== undefined ? { labels: [...input.labels] } : {}),
96
115
  ...(blockedBy.length > 0 ? { blockedBy } : {}),
116
+ ...(input.issueLinks !== undefined
117
+ ? { issueLinks: normalizeIssueLinks(input.issueLinks) }
118
+ : {}),
119
+ ...(input.priority !== undefined ? { priority: input.priority } : {}),
97
120
  }
98
121
  try {
99
122
  return input.state === undefined
100
123
  ? await source.create(draft)
101
124
  : await source.create(draft, { state: input.state })
102
125
  } catch (error) {
103
- if (error instanceof TicketRevisionConflict || error instanceof TicketRevisionUnsupported)
104
- throw error
126
+ if (passthrough(error)) throw error
105
127
  throw new TicketOperationError(
106
128
  'refusal',
107
129
  error instanceof Error ? error.message : String(error),
@@ -116,14 +138,15 @@ export async function updateTicket(
116
138
  readAfter = true,
117
139
  expectedRevision?: string,
118
140
  ): Promise<Ticket | null> {
141
+ refuseUnsupportedIssueLinks(source, patch)
142
+ refuseUnsupportedPriority(source, patch)
119
143
  source = compatibleTicketSource(source)
120
144
  try {
121
145
  if (expectedRevision !== undefined)
122
146
  await mutateTicketIfRevision(source, id, expectedRevision, { kind: 'update', patch })
123
147
  else await source.update(id, patch)
124
148
  } catch (error) {
125
- if (error instanceof TicketRevisionConflict || error instanceof TicketRevisionUnsupported)
126
- throw error
149
+ if (passthrough(error)) throw error
127
150
  throw new TicketOperationError(
128
151
  'refusal',
129
152
  error instanceof Error ? error.message : String(error),
@@ -144,8 +167,7 @@ export async function moveTicket(
144
167
  await mutateTicketIfRevision(source, id, expectedRevision, { kind: 'transition', state })
145
168
  else await source.transition(id, state)
146
169
  } catch (error) {
147
- if (error instanceof TicketRevisionConflict || error instanceof TicketRevisionUnsupported)
148
- throw error
170
+ if (passthrough(error)) throw error
149
171
  throw new TicketOperationError(
150
172
  'refusal',
151
173
  error instanceof Error ? error.message : String(error),
@@ -154,6 +176,71 @@ export async function moveTicket(
154
176
  return requirePostMutationTicket(source, id, 'the move')
155
177
  }
156
178
 
179
+ const OPTIONAL_ROLE_KEYS = {
180
+ backlog: {
181
+ key: 'backlogState',
182
+ holds: 'deferred work',
183
+ recommended: 'backlog',
184
+ about: 'Deferred on purpose; nothing dispatches from here',
185
+ },
186
+ rejected: {
187
+ key: 'rejectedState',
188
+ holds: 'declined work',
189
+ recommended: 'rejected',
190
+ about: 'Considered and declined; kept for the record',
191
+ },
192
+ } as const
193
+
194
+ /** The native state a role names, or a refusal naming the key that configures
195
+ * it. An unset optional role never falls back to a state sharing its name. */
196
+ export function roleStateName(tickets: TicketsConfig, role: string): string {
197
+ if (!(TICKET_MOVE_ROLES as readonly string[]).includes(role)) {
198
+ throw new TicketOperationError(
199
+ 'refusal',
200
+ `unknown ticket role "${role}"; expected one of ${TICKET_MOVE_ROLES.join(', ')}`,
201
+ )
202
+ }
203
+ const lifecycle = ticketLifecycle(tickets)
204
+ if (role === 'triage' || role === 'ready') return lifecycle[role]
205
+ const name = lifecycle[role as 'backlog' | 'rejected']
206
+ if (name !== undefined) return name
207
+ const { key, holds, recommended } = OPTIONAL_ROLE_KEYS[role as 'backlog' | 'rejected']
208
+ throw new TicketOperationError(
209
+ 'refusal',
210
+ `the ${role} role is not configured for this repository; set [tickets].${key} to the native state that holds ${holds} (recommended: "${recommended}")`,
211
+ )
212
+ }
213
+
214
+ /** Move a ticket into a lifecycle role through this repository's [tickets]
215
+ * names. A source that creates states gets a missing role state on first use. */
216
+ export async function moveTicketToRole(
217
+ source: TicketSource,
218
+ tickets: TicketsConfig,
219
+ id: string,
220
+ role: TicketMoveRole | string,
221
+ expectedRevision?: string,
222
+ ): Promise<Ticket> {
223
+ let state = roleStateName(tickets, role)
224
+ await requireTicket(source, id)
225
+ if (source.listStates) {
226
+ const known = (await source.listStates()).find((info) => holdsState(info.name, state))
227
+ if (known !== undefined) state = known.name
228
+ else if (source.addState) {
229
+ const about =
230
+ role === 'backlog' || role === 'rejected' ? OPTIONAL_ROLE_KEYS[role].about : undefined
231
+ try {
232
+ await source.addState(state, about === undefined ? {} : { about })
233
+ } catch (error) {
234
+ throw new TicketOperationError(
235
+ 'refusal',
236
+ error instanceof Error ? error.message : String(error),
237
+ )
238
+ }
239
+ }
240
+ }
241
+ return moveTicket(source, id, state, expectedRevision)
242
+ }
243
+
157
244
  export async function changeBlockers(
158
245
  source: TicketSource,
159
246
  id: string,
@@ -182,8 +269,7 @@ export async function changeBlockers(
182
269
  else await source.removeBlocker(id, blockerId)
183
270
  }
184
271
  } catch (error) {
185
- if (error instanceof TicketRevisionConflict || error instanceof TicketRevisionUnsupported)
186
- throw error
272
+ if (passthrough(error)) throw error
187
273
  throw new TicketOperationError(
188
274
  'refusal',
189
275
  error instanceof Error ? error.message : String(error),
@@ -0,0 +1,55 @@
1
+ import { z } from 'zod'
2
+ import type { Ticket, TicketPriority, TicketSource } from '../types'
3
+
4
+ export type { TicketPriority } from '../types'
5
+
6
+ export const ticketPrioritySchema = z.enum(['urgent', 'normal'])
7
+
8
+ /** A write naming `urgent` reached a source that cannot store priority. */
9
+ export class TicketPriorityUnsupported extends Error {
10
+ constructor(readonly source: string) {
11
+ super(`${source} ticket source cannot store ticket priority; nothing was written`)
12
+ this.name = 'TicketPriorityUnsupported'
13
+ }
14
+ }
15
+
16
+ /** Refuse before any write: only `urgent` needs the capability; `normal` is the
17
+ * value every source already holds. */
18
+ export function refuseUnsupportedPriority(
19
+ source: Pick<TicketSource, 'name' | 'priority'>,
20
+ patch: { priority?: unknown },
21
+ ): void {
22
+ if (patch.priority === 'urgent' && !source.priority)
23
+ throw new TicketPriorityUnsupported(source.name)
24
+ }
25
+
26
+ /** Refuse `urgent`, then drop a `normal` no-op for a source without the
27
+ * capability so its write (and wire) never names priority. */
28
+ export function withoutUnsupportedPriority<T extends { priority?: unknown }>(
29
+ source: Pick<TicketSource, 'name' | 'priority'>,
30
+ patch: T,
31
+ ): T {
32
+ refuseUnsupportedPriority(source, patch)
33
+ if (source.priority || !('priority' in patch)) return patch
34
+ const { priority: _priority, ...rest } = patch
35
+ return rest as T
36
+ }
37
+
38
+ /** Absent and anything but `urgent` read as normal. */
39
+ export function ticketPriority(ticket: Pick<Ticket, 'priority'>): TicketPriority {
40
+ return ticket.priority === 'urgent' ? 'urgent' : 'normal'
41
+ }
42
+
43
+ /** Stable partition: urgent candidates first, then the rest, each in input order. */
44
+ export function urgentFirst<T extends Pick<Ticket, 'priority'>>(tickets: readonly T[]): T[] {
45
+ const urgent: T[] = []
46
+ const normal: T[] = []
47
+ for (const ticket of tickets) (ticket.priority === 'urgent' ? urgent : normal).push(ticket)
48
+ return [...urgent, ...normal]
49
+ }
50
+
51
+ export function parsePriorityFlag(value: string, flag = '--priority'): TicketPriority {
52
+ const result = ticketPrioritySchema.safeParse(value.trim())
53
+ if (!result.success) throw new Error(`${flag}: expected urgent or normal, got "${value}"`)
54
+ return result.data
55
+ }
@@ -2,6 +2,9 @@ export const TICKET_TREE_HEADER = 'x-autobuild-ticket-tree'
2
2
  export const TICKET_TREE_CAPABILITY = '1'
3
3
  import { z } from 'zod'
4
4
  import { ticketRefSchema } from '../../ontology'
5
+ import { refineUniqueIssues } from './issue-links'
6
+ import { holdsState } from './lifecycle'
7
+ import { ticketPrioritySchema } from './priority'
5
8
 
6
9
  /** Explicit opt-in: released clients through 0.12 use strict decoders without revisions.
7
10
  * Source checkouts can share their release version, so version alone is insufficient. */
@@ -20,6 +23,52 @@ export type HostedTicketContext = z.infer<typeof hostedTicketContextSchema>
20
23
  export const TICKET_COMMENTS_HEADER = 'x-autobuild-ticket-comments'
21
24
  export const TICKET_COMMENTS_CAPABILITY = '1'
22
25
 
26
+ /** Explicit opt-in: published 1.2–1.4 clients decode tickets strictly without
27
+ * issue links. Servers echo it on every ticket response so a client can tell an
28
+ * older server's strict-schema refusal from an ordinary validation failure. */
29
+ export const TICKET_ISSUE_LINKS_HEADER = 'x-autobuild-ticket-issue-links'
30
+ export const TICKET_ISSUE_LINKS_CAPABILITY = '1'
31
+
32
+ /** Explicit opt-in: published 1.2–1.4 clients decode tickets strictly without
33
+ * priority. Servers answer `priority` on every ticket only to clients sending
34
+ * it and echo it on every ticket response, so a client can tell an older
35
+ * server's strict-schema refusal from an ordinary validation failure. */
36
+ export const TICKET_PRIORITY_HEADER = 'x-autobuild-ticket-priority'
37
+ export const TICKET_PRIORITY_CAPABILITY = '1'
38
+
39
+ /** Explicit opt-in: released clients decode dependency states strictly without
40
+ * `state`. Servers include each blocker's native state name only for clients
41
+ * that send this header; an older server ignores it and omits the field. */
42
+ export const TICKET_DEPENDENCY_STATE_HEADER = 'x-autobuild-ticket-dependency-state'
43
+ export const TICKET_DEPENDENCY_STATE_CAPABILITY = '1'
44
+
45
+ /** Explicit opt-in: released 1.2–1.4 clients publish and decode project ticket
46
+ * policy strictly without `backlogState`/`rejectedState`. With the header a
47
+ * publish is the complete policy (an absent role is unset); without it, absent
48
+ * roles keep their saved values and reads omit them. Servers echo it on every
49
+ * policy response so a client can tell an older server's strict refusal from an
50
+ * ordinary validation failure. */
51
+ export const TICKET_POLICY_ROLES_HEADER = 'x-autobuild-ticket-policy-roles'
52
+ export const TICKET_POLICY_ROLES_CAPABILITY = '1'
53
+
54
+ /** Services that answer `list-targeting` echo it on every ticket response,
55
+ * failures included. A client treats an ok response without it, or a 404/400
56
+ * refusal of `list-targeting` without it, as a service predating the operation,
57
+ * and declares targeted listing only after a response carried it. */
58
+ export const TICKET_TARGETING_HEADER = 'x-autobuild-ticket-targeting'
59
+ export const TICKET_TARGETING_CAPABILITY = '1'
60
+
61
+ /** The node id a client's `list-targeting` negotiation probe names. Hosted
62
+ * readable ids are `<teamKey>-<n>` or legacy `ticket-<uuid>`, so it never
63
+ * names a ticket and the probe is an indexed miss. */
64
+ export const TICKET_TARGETING_PROBE_NODE = '~negotiate'
65
+
66
+ export const issueLinkWireSchema = z.strictObject({
67
+ issue: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
68
+ intent: z.enum(['closes', 'refs']),
69
+ })
70
+ export const issueLinksWireSchema = z.array(issueLinkWireSchema).superRefine(refineUniqueIssues)
71
+
23
72
  export const ticketCommentWireSchema = z.strictObject({
24
73
  body: z.string(),
25
74
  createdAt: z.string(),
@@ -43,6 +92,8 @@ export const ticketWireSchema = z.strictObject({
43
92
  labels: z.array(z.string()),
44
93
  blockersResolved: z.boolean().optional(),
45
94
  blockedBy: z.array(z.string()).optional(),
95
+ issueLinks: issueLinksWireSchema.optional(),
96
+ priority: ticketPrioritySchema.optional(),
46
97
  })
47
98
  export const ticketListingWireSchema = z.strictObject({
48
99
  tickets: z.array(ticketWireSchema),
@@ -52,6 +103,7 @@ export const dependencyStateWireSchema = z.strictObject({
52
103
  id: z.string(),
53
104
  exists: z.boolean(),
54
105
  resolved: z.boolean(),
106
+ state: z.string().min(1).optional(),
55
107
  blockedBy: z.array(z.string()),
56
108
  })
57
109
  export const dependencyStatesWireSchema = z.array(dependencyStateWireSchema)
@@ -74,6 +126,8 @@ const draftSchema = z.strictObject({
74
126
  body: z.string(),
75
127
  labels: z.array(z.string()).optional(),
76
128
  blockedBy: z.array(z.string()).optional(),
129
+ issueLinks: issueLinksWireSchema.optional(),
130
+ priority: ticketPrioritySchema.optional(),
77
131
  })
78
132
  const createOptionsSchema = z.strictObject({
79
133
  requestedId: z.string().min(1).optional(),
@@ -91,6 +145,8 @@ const updateSchema = z
91
145
  title: z.string().optional(),
92
146
  body: z.string().optional(),
93
147
  labels: z.array(z.string()).optional(),
148
+ issueLinks: issueLinksWireSchema.optional(),
149
+ priority: ticketPrioritySchema.optional(),
94
150
  })
95
151
  .refine((value) => Object.keys(value).length > 0, 'update must name at least one field')
96
152
 
@@ -117,7 +173,9 @@ export const hostedTicketRequestSchemas = {
117
173
  }),
118
174
  ),
119
175
  'list-ready': envelope(criteriaSchema),
176
+ 'list-targeting': envelope(z.strictObject({ nodeId: z.string().min(1) })),
120
177
  states: envelope(z.strictObject({})),
178
+ 'state-counts': envelope(z.strictObject({ names: z.array(z.string().min(1)).min(1).max(16) })),
121
179
  'add-state': envelope(z.strictObject({ name: z.string(), about: z.string().optional() })),
122
180
  get: envelope(idSchema),
123
181
  claim: envelope(idSchema),
@@ -137,41 +195,143 @@ export const HOSTED_TICKET_OPERATIONS = Object.keys(
137
195
  hostedTicketRequestSchemas,
138
196
  ) as HostedTicketOperation[]
139
197
 
198
+ const policyStateSchema = z
199
+ .string()
200
+ .min(1)
201
+ .refine((value) => value.trim().length > 0, 'state must be nonblank')
202
+
203
+ const POLICY_OPTIONAL_ROLES = [
204
+ ['backlog', 'backlogState'],
205
+ ['rejected', 'rejectedState'],
206
+ ] as const
207
+ const POLICY_LIFECYCLE_ROLES = [
208
+ ['ready', 'readyState'],
209
+ ['claimed', 'claimedState'],
210
+ ['done', 'doneState'],
211
+ ['triage', 'triageState'],
212
+ ['proposal', 'proposalState'],
213
+ ] as const
214
+
215
+ interface PolicyRoleNames {
216
+ readyState: string
217
+ claimedState: string
218
+ doneState: string
219
+ triageState: string
220
+ proposalState: string
221
+ backlogState?: string | undefined
222
+ rejectedState?: string | undefined
223
+ }
224
+
225
+ /** The policy form of the config rule: backlog and rejected each hold a state
226
+ * of their own, distinct from ready, claimed, done, triage and proposal and
227
+ * from each other (case-insensitive). Create is not checked, as in config. */
228
+ interface PolicyRoleOverlap {
229
+ key: string
230
+ otherKey: string
231
+ name: string
232
+ held: string
233
+ message: string
234
+ }
235
+
236
+ function policyRoleOverlaps(tickets: PolicyRoleNames): PolicyRoleOverlap[] {
237
+ const issues: PolicyRoleOverlap[] = []
238
+ for (const [index, [role, key]] of POLICY_OPTIONAL_ROLES.entries()) {
239
+ const name = tickets[key]
240
+ if (name === undefined) continue
241
+ for (const [other, otherKey] of [
242
+ ...POLICY_LIFECYCLE_ROLES,
243
+ ...POLICY_OPTIONAL_ROLES.slice(index + 1),
244
+ ]) {
245
+ const held = tickets[otherKey]
246
+ if (held === undefined || !holdsState(name, held)) continue
247
+ issues.push({
248
+ key,
249
+ otherKey,
250
+ name,
251
+ held,
252
+ message: `${key} "${name}" names the same state as the ${other} role (${otherKey} is "${held}"); the ${role} and ${other} roles must name different states`,
253
+ })
254
+ }
255
+ }
256
+ return issues
257
+ }
258
+
140
259
  /** Project policy is separate from CRUD context and cannot be supplied by delegates. */
141
260
  export const hostedTicketPolicySchema = z.strictObject({
142
261
  version: z.literal(1),
143
- tickets: z.strictObject({
144
- source: z.literal('hosted'),
145
- teamKey: z.string().min(1),
146
- readyState: z
147
- .string()
148
- .min(1)
149
- .refine((value) => value.trim().length > 0, 'state must be nonblank'),
150
- triageState: z
151
- .string()
152
- .min(1)
153
- .refine((value) => value.trim().length > 0, 'state must be nonblank'),
154
- claimedState: z
155
- .string()
156
- .min(1)
157
- .refine((value) => value.trim().length > 0, 'state must be nonblank'),
158
- doneState: z
159
- .string()
160
- .min(1)
161
- .refine((value) => value.trim().length > 0, 'state must be nonblank'),
162
- createState: z
163
- .string()
164
- .min(1)
165
- .refine((value) => value.trim().length > 0, 'state must be nonblank'),
166
- proposalState: z
167
- .string()
168
- .min(1)
169
- .refine((value) => value.trim().length > 0, 'state must be nonblank'),
170
- readyLabels: z.array(z.string().min(1)).optional(),
171
- }),
262
+ tickets: z
263
+ .strictObject({
264
+ source: z.literal('hosted'),
265
+ teamKey: z.string().min(1),
266
+ readyState: policyStateSchema,
267
+ triageState: policyStateSchema,
268
+ claimedState: policyStateSchema,
269
+ doneState: policyStateSchema,
270
+ createState: policyStateSchema,
271
+ proposalState: policyStateSchema,
272
+ readyLabels: z.array(z.string().min(1)).optional(),
273
+ backlogState: policyStateSchema.optional(),
274
+ rejectedState: policyStateSchema.optional(),
275
+ })
276
+ .superRefine((tickets, ctx) => {
277
+ for (const issue of policyRoleOverlaps(tickets))
278
+ ctx.addIssue({
279
+ code: 'custom',
280
+ path: [issue.key],
281
+ message: issue.message,
282
+ })
283
+ }),
172
284
  })
173
285
  export type HostedTicketPolicy = z.infer<typeof hostedTicketPolicySchema>
174
286
 
287
+ const POLICY_ROLE_KEYS = ['backlogState', 'rejectedState'] as const
288
+
289
+ /** The policy a publish stores. `replace` (a roles-aware client) stores the
290
+ * publish as the complete policy. `retain-roles` (a client predating the roles)
291
+ * fills each absent role from the saved policy; when a retained role would then
292
+ * collide with a lifecycle name that publish just set, the saved policy is kept
293
+ * unchanged and `kept` names the collisions, so a mapping is never erased. */
294
+ export function publishedTicketPolicy(
295
+ previous: HostedTicketPolicy | null | undefined,
296
+ incoming: HostedTicketPolicy,
297
+ mode: 'replace' | 'retain-roles',
298
+ ): { policy: HostedTicketPolicy; kept?: string[] } {
299
+ if (mode === 'replace' || !previous) return { policy: incoming }
300
+ const retained = Object.fromEntries(
301
+ POLICY_ROLE_KEYS.flatMap((key) =>
302
+ incoming.tickets[key] === undefined && previous.tickets[key] !== undefined
303
+ ? [[key, previous.tickets[key]]]
304
+ : [],
305
+ ),
306
+ )
307
+ if (Object.keys(retained).length === 0) return { policy: incoming }
308
+ const merged = { ...incoming, tickets: { ...incoming.tickets, ...retained } }
309
+ // The publish alone was valid, so every overlap involves a retained role.
310
+ const collisions = policyRoleOverlaps(merged.tickets)
311
+ if (collisions.length > 0)
312
+ return {
313
+ policy: previous,
314
+ kept: collisions.map((issue) => {
315
+ const [saved, published] =
316
+ issue.key in retained
317
+ ? [issue, { key: issue.otherKey, name: issue.held }]
318
+ : [{ key: issue.otherKey, name: issue.held }, issue]
319
+ return `legacy publish names ${published.key} "${published.name}", which the saved ${saved.key} holds`
320
+ }),
321
+ }
322
+ return { policy: hostedTicketPolicySchema.parse(merged) }
323
+ }
324
+
325
+ /** Policy as a reader sees it: clients predating the roles decode strictly. */
326
+ export function projectTicketPolicy(
327
+ policy: HostedTicketPolicy,
328
+ rolesAware: boolean,
329
+ ): HostedTicketPolicy {
330
+ if (rolesAware) return policy
331
+ const { backlogState: _backlog, rejectedState: _rejected, ...tickets } = policy.tickets
332
+ return { ...policy, tickets }
333
+ }
334
+
175
335
  export const ticketGrantSchema = z.strictObject({
176
336
  id: z.string().min(1),
177
337
  repo: z.string().min(1),
@@ -191,6 +351,12 @@ export const ticketStateWireSchema = z.strictObject({
191
351
  about: z.string().optional(),
192
352
  })
193
353
  export const ticketStatesWireSchema = z.array(ticketStateWireSchema)
354
+ /** `state-counts` answers per-state totals only, never ticket rows. */
355
+ export const ticketStateCountWireSchema = z.strictObject({
356
+ name: z.string().min(1),
357
+ tickets: z.number().int().nonnegative(),
358
+ })
359
+ export const ticketStateCountsWireSchema = z.array(ticketStateCountWireSchema)
194
360
  export const ticketStateCreateWireSchema = z.strictObject({
195
361
  state: ticketStateWireSchema,
196
362
  created: z.boolean(),