@defrex/autobuild 1.0.0-beta.2 → 1.0.0-beta.3

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 (50) hide show
  1. package/SPEC.md +25 -3
  2. package/docs/architecture.md +4 -0
  3. package/docs/integration-tree.md +4 -2
  4. package/docs/remote-store-protocol.md +5 -0
  5. package/docs/remote-ticket-protocol.md +5 -0
  6. package/docs/setup.md +4 -0
  7. package/docs/spec-standard.md +71 -0
  8. package/docs/ticket-migration.md +50 -4
  9. package/package.json +3 -3
  10. package/packages/core/src/cli/build-control.ts +3 -3
  11. package/packages/core/src/cli/dashboard/integration-detail.ts +8 -6
  12. package/packages/core/src/cli/dashboard/integration-row.ts +15 -8
  13. package/packages/core/src/cli/dashboard/model.ts +7 -0
  14. package/packages/core/src/cli/dispatch-frontend.ts +5 -0
  15. package/packages/core/src/cli/dispatch-repository-feed.ts +2 -1
  16. package/packages/core/src/cli/dispatch.ts +5 -0
  17. package/packages/core/src/cli/help.ts +1 -0
  18. package/packages/core/src/cli/main.ts +11 -8
  19. package/packages/core/src/cli/repository-status.ts +7 -1
  20. package/packages/core/src/cli/ticket.ts +35 -11
  21. package/packages/core/src/events/payloads.ts +2 -0
  22. package/packages/core/src/events/policy.ts +1 -0
  23. package/packages/core/src/events/repository.ts +21 -0
  24. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +4025 -3978
  25. package/packages/core/src/kernel/change-presence.ts +7 -1
  26. package/packages/core/src/kernel/dispatch-capacity.ts +12 -4
  27. package/packages/core/src/kernel/integration-completeness.ts +54 -16
  28. package/packages/core/src/kernel/node-parent.ts +35 -10
  29. package/packages/core/src/kernel/read-facts.ts +7 -0
  30. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  31. package/packages/core/src/kernel/reducer.ts +1 -1
  32. package/packages/core/src/kernel/ticket-migrations.ts +139 -0
  33. package/packages/core/src/operator/query.ts +7 -1
  34. package/packages/core/src/operator/tickets.ts +30 -26
  35. package/packages/core/src/ports/tickets/linear.ts +180 -12
  36. package/packages/core/src/ports/tickets/migration.ts +92 -9
  37. package/packages/core/src/ports/types.ts +7 -0
  38. package/packages/core/src/processes/dispatcher.ts +164 -36
  39. package/packages/core/src/store/contract.ts +30 -0
  40. package/packages/core/src/store/reducer-value-shapes.json +5735 -5642
  41. package/packages/core/src/store/repo-state-events.ts +3 -2
  42. package/packages/core/src/testing/dispatch-read-budget.ts +3 -2
  43. package/skills/guide/SKILL.md +3 -1
  44. package/skills/guide/references/integration-tree.md +4 -2
  45. package/skills/guide/references/remote-store-protocol.md +5 -0
  46. package/skills/guide/references/remote-ticket-protocol.md +5 -0
  47. package/skills/guide/references/setup.md +4 -0
  48. package/skills/guide/references/spec-standard.md +71 -0
  49. package/skills/guide/references/ticket-migration.md +50 -4
  50. package/skills/spec/SKILL.md +16 -4
@@ -1,3 +1,4 @@
1
+ import type { TicketRef } from '../ontology'
1
2
  import type { BuildRecord, BuildDigest } from '../store/types'
2
3
  import type { CurrentBuildFacts } from '../store/reduced-reads'
3
4
  import type { BuildState } from './reducer'
@@ -17,9 +18,14 @@ export function blockerBuild(
17
18
  entries: PresenceBuild[],
18
19
  source: string,
19
20
  id: string,
21
+ identity: (ref: TicketRef, build?: string) => string = (ref) =>
22
+ JSON.stringify([ref.source, ref.id]),
20
23
  ): PresenceBuild | string | undefined {
21
24
  const generations = entries
22
- .filter(({ record }) => record.ticket?.source === source && record.ticket.id === id)
25
+ .filter(
26
+ ({ record }) =>
27
+ record.ticket && identity(record.ticket, record.slug) === identity({ source, id }),
28
+ )
23
29
  .sort(
24
30
  (a, b) =>
25
31
  b.record.createdAt.localeCompare(a.record.createdAt) ||
@@ -1,3 +1,4 @@
1
+ import type { TicketRef } from '../ontology'
1
2
  import type { BuildRecord } from '../store/types'
2
3
  import type { BuildState } from './reducer'
3
4
  import { integrationNeedsRunner } from './integration-state'
@@ -30,11 +31,15 @@ export function occupiesCapacity(build: CapacityBuild, now: Date): boolean {
30
31
  )
31
32
  }
32
33
 
34
+ type Identity = (ref: TicketRef, build?: string) => string
35
+ const exactIdentity: Identity = (ref) => JSON.stringify([ref.source, ref.id])
36
+
33
37
  /** Follow accepted build identities, validating the source-qualified ticket at every edge. */
34
38
  function descendsFrom(
35
39
  build: CapacityBuild,
36
40
  node: string,
37
41
  builds: Map<string, CapacityBuild>,
42
+ identity: Identity,
38
43
  ): boolean {
39
44
  const seen = new Set<string>([build.record.slug])
40
45
  let target = build.state.target
@@ -45,8 +50,9 @@ function descendsFrom(
45
50
  if (
46
51
  parent?.state.kind !== 'node' ||
47
52
  parent.record.repo !== build.record.repo ||
48
- parent.record.ticket?.source !== target.ticket.source ||
49
- parent.record.ticket.id !== target.ticket.id
53
+ !parent.record.ticket ||
54
+ identity(parent.record.ticket, parent.record.slug) !==
55
+ identity(target.ticket, build.record.slug)
50
56
  )
51
57
  return false
52
58
  if (parent.record.slug === node) return true
@@ -59,6 +65,7 @@ export function nodeCapacity(
59
65
  builds: readonly CapacityBuild[],
60
66
  node: string,
61
67
  now: Date,
68
+ identity: Identity = exactIdentity,
62
69
  ): {
63
70
  occupied: number
64
71
  excludedDescendants: string[]
@@ -70,7 +77,7 @@ export function nodeCapacity(
70
77
  if (build.record.slug === node || !occupiesCapacity(build, now)) continue
71
78
  if (
72
79
  (build.state.status === 'blocked' || build.state.status === 'paused') &&
73
- descendsFrom(build, node, identities)
80
+ descendsFrom(build, node, identities, identity)
74
81
  )
75
82
  excludedDescendants.push(build.record.slug)
76
83
  else occupied++
@@ -82,6 +89,7 @@ export function dispatchCapacity(
82
89
  builds: readonly CapacityBuild[],
83
90
  configured: number,
84
91
  now: Date,
92
+ identity: Identity = exactIdentity,
85
93
  ): DispatchCapacity {
86
94
  const unique = [...new Map(builds.map((build) => [build.record.slug, build])).values()]
87
95
  const occupied = unique.filter((build) => occupiesCapacity(build, now)).length
@@ -95,7 +103,7 @@ export function dispatchCapacity(
95
103
  !(build.record.lease && Date.parse(build.record.lease.expiresAt) > now.getTime())
96
104
  )
97
105
  return false
98
- const admission = nodeCapacity(unique, build.record.slug, now)
106
+ const admission = nodeCapacity(unique, build.record.slug, now, identity)
99
107
  return (
100
108
  occupied > configured &&
101
109
  admission.excludedDescendants.length > 0 &&
@@ -1,3 +1,4 @@
1
+ import { readTicketMigrations, resolveTicketRef, type TicketMigrations } from './ticket-migrations'
1
2
  import type { BuildState } from './reducer'
2
3
  import type { TicketSource, TicketListing } from '../ports/types'
3
4
  import type { BuildStore, BuildRecord } from '../store/types'
@@ -8,6 +9,7 @@ import type { EventPayload } from '../events/payloads'
8
9
  /** One exhaustive source sample shared by every node in a dispatcher pass.
9
10
  * Scheduling may be cached; publication always requests a sample from this pass. */
10
11
  export interface IntegrationObservationInputs {
12
+ migrations?: TicketMigrations
11
13
  listing: TicketListing
12
14
  builds: { record: BuildRecord; state: BuildState }[]
13
15
  }
@@ -22,7 +24,7 @@ export async function integrationObservationInputs(
22
24
  const builds = []
23
25
  for (const record of await store.listBuildsForRepo(repo))
24
26
  builds.push({ record, state: (await readBuildFacts(store, record.slug)).value.state })
25
- return { listing, builds }
27
+ return { listing, builds, migrations: await readTicketMigrations(store, repo) }
26
28
  }
27
29
 
28
30
  /** A failed or partial enumeration cannot authorize verification or publication. */
@@ -35,6 +37,7 @@ export async function observeIntegration(
35
37
  const record = await store.getBuild(slug)
36
38
  const state = (await readBuildFacts(store, slug)).value.state
37
39
  const observation: EventPayload<'integration.observed'> = {
40
+ membershipSource: state.integration?.observation?.membershipSource,
38
41
  openChildren: [],
39
42
  diagnostics: [],
40
43
  contributions: [...(state.integration?.observation?.contributions ?? [])],
@@ -45,24 +48,31 @@ export async function observeIntegration(
45
48
  try {
46
49
  if (!record?.ticket || !tickets.integrationTree || !tickets.listAll)
47
50
  throw new Error('ticket source cannot establish exhaustive integration completeness')
48
- if (record.ticket.source !== tickets.name)
49
- throw new Error('configured ticket source differs from the frozen node source')
50
- const { listing, builds } = await (inputs
51
- ? inputs()
52
- : integrationObservationInputs(store, tickets, record.repo))
51
+ const {
52
+ listing,
53
+ builds,
54
+ migrations: supplied,
55
+ } = await (inputs ? inputs() : integrationObservationInputs(store, tickets, record.repo))
56
+ const migrations = supplied ?? (await readTicketMigrations(store, record.repo))
57
+ const nodeRef = resolveTicketRef(migrations, record.ticket, tickets.name, slug)
58
+ observation.membershipSource = tickets.name
59
+ const current = (build: BuildRecord) =>
60
+ build.ticket
61
+ ? resolveTicketRef(migrations, build.ticket, tickets.name, build.slug)
62
+ : undefined
53
63
  observation.diagnostics.push(...listing.diagnostics)
54
64
  for (const ticket of listing.tickets)
55
- if (ticket.target === record.ticket.id && !ticket.resolved) children.add(ticket.ref.id)
65
+ if (ticket.target === nodeRef.id && !ticket.resolved) children.add(ticket.ref.id)
56
66
  // Frozen claims survive edits to the source ticket's target.
57
67
  for (const { record: build, state: child } of builds) {
58
68
  if (child.target?.build === slug && child.status !== 'done' && child.status !== 'aborted')
59
- children.add(build.ticket?.id ?? build.slug)
69
+ children.add(current(build)?.id ?? build.slug)
60
70
  if (
61
71
  [child.nodeRestack?.parentRequest, child.nodeRestack?.parentChange].some(
62
72
  (move) => move && (move.old.target?.build === slug || move.next.target?.build === slug),
63
73
  )
64
74
  )
65
- children.add(build.ticket?.id ?? build.slug)
75
+ children.add(current(build)?.id ?? build.slug)
66
76
  if (child.target?.build === slug && child.prState === 'merged')
67
77
  observation.contributions.push(build.slug)
68
78
  }
@@ -99,26 +109,54 @@ export async function observeIntegration(
99
109
  for (const contribution of [...new Set(observation.contributions)].sort()) {
100
110
  const build = builds.find((b) => b.record.slug === contribution)?.record
101
111
  put(
102
- build?.ticket?.source ?? record.ticket.source,
103
- build?.ticket?.id ?? contribution,
112
+ build ? (current(build)?.source ?? tickets.name) : tickets.name,
113
+ build ? (current(build)?.id ?? contribution) : contribution,
104
114
  build?.ticket?.title,
105
115
  contribution,
106
116
  )
107
117
  }
108
118
  for (const { record: build } of builds)
109
- if (children.has(build.ticket?.id ?? build.slug))
119
+ if (
120
+ (build.ticket?.source === tickets.name ||
121
+ builds.some(
122
+ (entry) =>
123
+ entry.record.slug === build.slug &&
124
+ (entry.state.target?.build === slug ||
125
+ observation.contributions.includes(build.slug)),
126
+ )) &&
127
+ children.has(current(build)?.id ?? build.slug)
128
+ )
110
129
  put(
111
- build.ticket?.source ?? record.ticket.source,
112
- build.ticket?.id ?? build.slug,
130
+ current(build)?.source ?? tickets.name,
131
+ current(build)?.id ?? build.slug,
113
132
  build.ticket?.title,
114
133
  )
134
+ for (const { record: build, state: child } of builds) {
135
+ if (
136
+ !build.ticket ||
137
+ child.target?.build !== slug ||
138
+ child.status === 'done' ||
139
+ child.status === 'aborted'
140
+ )
141
+ continue
142
+ const ref = current(build)!
143
+ if (
144
+ ref.source === build.ticket.source &&
145
+ ref.id === build.ticket.id &&
146
+ nodeRef.source === record.ticket.source &&
147
+ nodeRef.id === record.ticket.id
148
+ )
149
+ continue
150
+ const entry = display.get(JSON.stringify([ref.source, ref.id]))
151
+ if (entry) entry.claims = [...new Set([...(entry.claims ?? []), build.slug])].sort()
152
+ }
115
153
  for (const ticket of listing.tickets)
116
154
  if (
117
- (ticket.ref.source === record.ticket.source && children.has(ticket.ref.id)) ||
155
+ (ticket.ref.source === tickets.name && children.has(ticket.ref.id)) ||
118
156
  display.has(JSON.stringify([ticket.ref.source, ticket.ref.id]))
119
157
  )
120
158
  put(ticket.ref.source, ticket.ref.id, ticket.title, undefined, true)
121
- for (const id of children) put(record.ticket.source, id)
159
+ for (const id of children) put(tickets.name, id)
122
160
  if (observation.diagnostics.length)
123
161
  for (const previous of state.integration?.observation?.children ?? [])
124
162
  if (!display.has(JSON.stringify([previous.source, previous.id])))
@@ -1,3 +1,4 @@
1
+ import { currentTicketRef, readTicketMigrations, resolveTicketRef } from './ticket-migrations'
1
2
  import { randomUUID } from 'node:crypto'
2
3
  import { DISPATCHER } from '../events/envelope'
3
4
  import type { EventPayload } from '../events/payloads'
@@ -26,17 +27,29 @@ function refuse(message: string): never {
26
27
  throw new TicketOperationError('refusal', message)
27
28
  }
28
29
  export async function newestTicketBuild(ctx: ParentContext, ticket: Ticket) {
29
- const namespace = (source: string) =>
30
- source === 'database' && ctx.configuredSource === 'hosted' ? 'hosted' : source
31
- const candidates = (await ctx.store.listBuildsForRepo(ctx.repo)).filter(
32
- (b) => b.ticket && namespace(b.ticket.source) === namespace(ticket.ref.source),
33
- )
30
+ const candidates = await ctx.store.listBuildsForRepo(ctx.repo)
31
+ if (!candidates.length) return undefined
32
+ const migrations = await readTicketMigrations(ctx.store, ctx.repo)
34
33
  const matches: BuildRecord[] = []
35
34
  for (const build of candidates) {
36
- if (build.ticket!.id === ticket.ref.id) matches.push(build)
37
- else if (
38
- ctx.configuredSource === 'hosted' &&
39
- (await ctx.source.get(build.ticket!.id))?.ref.id === ticket.ref.id
35
+ if (!build.ticket) continue
36
+ let ref = build.ticket
37
+ try {
38
+ ref = resolveTicketRef(
39
+ migrations,
40
+ build.ticket,
41
+ ctx.source.name === 'database' && ctx.configuredSource === 'hosted'
42
+ ? 'hosted'
43
+ : ctx.source.name,
44
+ build.slug,
45
+ )
46
+ } catch {
47
+ continue
48
+ }
49
+ if (
50
+ ref.id === ticket.ref.id ||
51
+ (ctx.configuredSource === 'hosted' &&
52
+ (await ctx.source.get(ref.id))?.ref.id === ticket.ref.id)
40
53
  )
41
54
  matches.push(build)
42
55
  }
@@ -124,7 +137,19 @@ export async function updateTicketTarget(
124
137
  if (!record) return updateTicket(ctx.source, id, canonicalPatch, true, expectedRevision)
125
138
  let state = (await readBuildFacts(ctx.store, record.slug)).value.state
126
139
  const active = state.status !== 'done' && state.status !== 'aborted'
127
- const frozenId = state.target?.ticket.id
140
+ const frozenId = state.target
141
+ ? (
142
+ await currentTicketRef(
143
+ ctx.store,
144
+ ctx.repo,
145
+ ctx.source.name === 'database' && ctx.configuredSource === 'hosted'
146
+ ? 'hosted'
147
+ : ctx.source.name,
148
+ state.target.ticket,
149
+ record.slug,
150
+ )
151
+ ).id
152
+ : undefined
128
153
  const effective =
129
154
  frozenId === undefined ? undefined : ((await ctx.source.get(frozenId))?.ref.id ?? frozenId)
130
155
  if (state.kind !== 'node') {
@@ -1,3 +1,4 @@
1
+ import { ticketMigrationsReducer } from './ticket-migrations'
1
2
  import {
2
3
  advanceCompatibility,
3
4
  initialCompatibility,
@@ -57,6 +58,7 @@ export const buildStreamSeedReducer = defineReducer<BuildStreamSeed, AbEvent, Bu
57
58
  rawEvents: true,
58
59
  version:
59
60
  4 +
61
+ ticketMigrationsReducer.version +
60
62
  leafRestackReducer.version +
61
63
  buildReducer.version +
62
64
  currentDeferralObservationReducer.version,
@@ -492,6 +494,7 @@ export interface RepositoryReadAcc {
492
494
  settings: ReturnType<typeof dispatchSettingsReducer.initial>
493
495
  harvest: ReturnType<typeof harvestReducer.initial>
494
496
  forgeHealth: ReturnType<typeof forgeHealthReducer.initial>
497
+ ticketMigrations: ReturnType<typeof ticketMigrationsReducer.initial>
495
498
  health: ReturnType<typeof ticketSourceHealthReducer.initial>
496
499
  autoMerge: ReturnType<typeof autoMergeDefaultReducer.initial>
497
500
  config: ReturnType<typeof effectiveConfigReducer.initial>
@@ -508,6 +511,7 @@ export const repositoryReadFactsReducer = defineReducer({
508
511
  rawEvents: true,
509
512
  version:
510
513
  4 +
514
+ ticketMigrationsReducer.version +
511
515
  dispatcherRunFactsReducer('version').version +
512
516
  openHarvestExecutionsReducer.version +
513
517
  forgeHealthReducer.version +
@@ -537,6 +541,7 @@ export const repositoryReadFactsReducer = defineReducer({
537
541
  settings: dispatchSettingsReducer.initial(),
538
542
  harvest: harvestReducer.initial(),
539
543
  forgeHealth: forgeHealthReducer.initial(),
544
+ ticketMigrations: ticketMigrationsReducer.initial(),
540
545
  health: ticketSourceHealthReducer.initial(),
541
546
  autoMerge: autoMergeDefaultReducer.initial(),
542
547
  config: effectiveConfigReducer.initial(),
@@ -551,6 +556,7 @@ export const repositoryReadFactsReducer = defineReducer({
551
556
  acc.settings = dispatchSettingsReducer.advance(acc.settings, events)
552
557
  acc.harvest = harvestReducer.advance(acc.harvest, events)
553
558
  acc.forgeHealth = forgeHealthReducer.advance(acc.forgeHealth, events)
559
+ acc.ticketMigrations = ticketMigrationsReducer.advance(acc.ticketMigrations, events)
554
560
  acc.health = ticketSourceHealthReducer.advance(acc.health, events)
555
561
  acc.autoMerge = autoMergeDefaultReducer.advance(acc.autoMerge, events)
556
562
  acc.config = effectiveConfigReducer.advance(acc.config, events)
@@ -659,6 +665,7 @@ export const repositoryReadFactsReducer = defineReducer({
659
665
  settings: dispatchSettingsReducer.finish(acc.settings),
660
666
  harvest: harvestReducer.finish(acc.harvest),
661
667
  forgeHealth: forgeHealthReducer.finish(acc.forgeHealth),
668
+ ticketMigrations: ticketMigrationsReducer.finish(acc.ticketMigrations),
662
669
  health: ticketSourceHealthReducer.finish(acc.health),
663
670
  autoMerge: autoMergeDefaultReducer.finish(acc.autoMerge),
664
671
  config: effectiveConfigReducer.finish(acc.config),
@@ -1,3 +1,4 @@
1
+ import { ticketMigrationsReducer } from './ticket-migrations'
1
2
  import { forgeHealthReducer } from './forge-health'
2
3
  import { decodeStoredEvent } from '../events/compatibility'
3
4
  import { nodeRestackReducer } from './node-restack-state'
@@ -85,6 +86,7 @@ export interface RegisteredReducer {
85
86
  /** Parameterized reducers are registered with representative arguments; the
86
87
  * accumulator shape does not depend on them. */
87
88
  const REGISTERED: Record<string, Omit<RegisteredReducer, 'valueRead'>> = {
89
+ ticketMigrations: { reducer: ticketMigrationsReducer, covers: [] },
88
90
  nodeRestack: { reducer: nodeRestackReducer, covers: ['advanceNodeRestack'] },
89
91
  leafRestack: { reducer: leafRestackReducer, covers: ['advanceLeafRestack'] },
90
92
  baseBranchValue: { reducer: optionalValue(baseBranchReducer), covers: [] },
@@ -211,6 +213,7 @@ const valueExclusions: Record<string, string> = {
211
213
  ),
212
214
  }
213
215
  const repositoryValues = new Set([
216
+ 'ticketMigrations',
214
217
  'forgeHealthValue',
215
218
  'repositoryReadFacts',
216
219
  'dispatcherRunFacts',
@@ -430,7 +430,7 @@ export interface BuildAcc {
430
430
  }
431
431
 
432
432
  /** Bump when `BuildAcc`'s shape or the fold's semantics change. */
433
- export const BUILD_REDUCER_VERSION = 17
433
+ export const BUILD_REDUCER_VERSION = 18
434
434
 
435
435
  function initialBuildAcc(): BuildAcc {
436
436
  return {
@@ -0,0 +1,139 @@
1
+ import { readRepositoryFacts } from '../store/reduced-reads'
2
+ import type { TicketRef } from '../ontology'
3
+ import type { Actor } from '../events/envelope'
4
+ import type { RepositoryEvent, RepositoryEventPayload } from '../events/repository'
5
+ import { validateRepositoryEventWrite } from '../events/repository'
6
+ import type { BuildStore } from '../store/types'
7
+ import { defineReducer } from './incremental'
8
+
9
+ type Migration = RepositoryEventPayload<'tickets.migration-recorded'>
10
+ export interface TicketMigrations {
11
+ migrations: Migration[]
12
+ }
13
+ const key = (ref: TicketRef) => JSON.stringify([ref.source, ref.id])
14
+ function stable(value: Migration): string {
15
+ return JSON.stringify([value.from, value.to, Object.entries(value.mapping).sort()])
16
+ }
17
+ function add(state: TicketMigrations, migration: Migration) {
18
+ const previous = state.migrations.find((m) => m.identity === migration.identity)
19
+ if (previous) {
20
+ if (stable(previous) !== stable(migration))
21
+ throw new Error(`conflicting ticket migration ${migration.identity}`)
22
+ return
23
+ }
24
+ for (const old of state.migrations)
25
+ if (old.from !== old.to && migration.from !== migration.to && old.from === migration.from)
26
+ for (const [id, next] of Object.entries(migration.mapping))
27
+ if (Object.hasOwn(old.mapping, id) && (old.to !== migration.to || old.mapping[id] !== next))
28
+ throw new Error(`conflicting ticket migration for ${migration.from}:${id}`)
29
+ state.migrations.push(migration)
30
+ // Reject cycles even before any build consults the evidence.
31
+ for (const m of state.migrations)
32
+ for (const id of Object.keys(m.mapping)) walk(state, { source: m.from, id })
33
+ }
34
+ function walk(
35
+ state: TicketMigrations,
36
+ original: TicketRef,
37
+ destination?: string,
38
+ build = 'unknown',
39
+ ): TicketRef {
40
+ let current = original
41
+ const visited = new Set<string>()
42
+ while (current.source !== destination) {
43
+ if (visited.has(key(current)))
44
+ throw new Error(`ticket migration cycle at ${current.source}:${current.id}`)
45
+ visited.add(key(current))
46
+ const routes = state.migrations.filter((m) => m.from === current.source && m.from !== m.to)
47
+ const route = routes.find((m) => Object.hasOwn(m.mapping, current.id))
48
+ if (!route) {
49
+ if (destination === undefined) return current
50
+ throw new Error(
51
+ `build ${build} ticket ${original.source}:${original.id}: ${routes.length ? 'recorded migration does not cover id' : 'configured ticket source differs from the frozen node source'}; record continuity with ab ticket migration record <export-dir>`,
52
+ )
53
+ }
54
+ if (route.to === current.source && route.mapping[current.id] === current.id) return current
55
+ current = { ...current, source: route.to, id: route.mapping[current.id]! }
56
+ }
57
+ return current
58
+ }
59
+ export const ticketMigrationsReducer = defineReducer<
60
+ TicketMigrations,
61
+ RepositoryEvent,
62
+ TicketMigrations
63
+ >({
64
+ version: 1,
65
+ initial: () => ({ migrations: [] }),
66
+ fold(acc, events) {
67
+ for (const event of events)
68
+ if (event.type === 'tickets.migration-recorded') add(acc, event.payload)
69
+ },
70
+ finish: (acc) => acc,
71
+ })
72
+ export function resolveTicketRef(
73
+ state: TicketMigrations,
74
+ ref: TicketRef,
75
+ destination: string,
76
+ build?: string,
77
+ ): TicketRef {
78
+ // Preserve the pre-existing database/hosted adapter compatibility.
79
+ const hosted = destination === 'hosted' || destination === 'database'
80
+ const compatible = ref.source === 'database' && hosted ? { ...ref, source: 'hosted' } : ref
81
+ const current = walk(
82
+ state,
83
+ compatible,
84
+ destination === 'database' ? 'hosted' : destination,
85
+ build,
86
+ )
87
+ return destination === 'database' ? { ...current, source: 'database' } : current
88
+ }
89
+ export function migrationIdentity(state: TicketMigrations, destination: string) {
90
+ return (ref: TicketRef, build?: string): string => {
91
+ try {
92
+ return key(resolveTicketRef(state, ref, destination, build))
93
+ } catch (error) {
94
+ if (state.migrations.some((m) => m.from === ref.source && m.from !== m.to)) throw error
95
+ return key(ref)
96
+ }
97
+ }
98
+ }
99
+ /** Comparison only for all-history scans. Uncovered history remains in its
100
+ * original namespace and cannot alias a current-source ticket. Live claims,
101
+ * frozen membership and current-ticket operations must use strict resolution. */
102
+ export function historicalTicketIdentity(state: TicketMigrations, destination: string) {
103
+ const identity = migrationIdentity(state, destination)
104
+ return (ref: TicketRef, build?: string): string => {
105
+ try {
106
+ return identity(ref, build)
107
+ } catch {
108
+ return key(ref)
109
+ }
110
+ }
111
+ }
112
+ export async function readTicketMigrations(
113
+ store: BuildStore,
114
+ repo: string,
115
+ ): Promise<TicketMigrations> {
116
+ return (await readRepositoryFacts(store, repo)).value.ticketMigrations
117
+ }
118
+ export async function currentTicketRef(
119
+ store: BuildStore,
120
+ repo: string,
121
+ destination: string,
122
+ ref: TicketRef,
123
+ build?: string,
124
+ ) {
125
+ return resolveTicketRef(await readTicketMigrations(store, repo), ref, destination, build)
126
+ }
127
+ export async function recordTicketMigration(
128
+ store: BuildStore,
129
+ repo: string,
130
+ actor: Actor,
131
+ migration: Migration,
132
+ ) {
133
+ validateRepositoryEventWrite({ actor, type: 'tickets.migration-recorded', payload: migration })
134
+ const state = structuredClone(await readTicketMigrations(store, repo))
135
+ const repeated = state.migrations.some((m) => m.identity === migration.identity)
136
+ add(state, migration)
137
+ if (!repeated)
138
+ await store.appendRepo(repo, { actor, type: 'tickets.migration-recorded', payload: migration })
139
+ }
@@ -1,3 +1,4 @@
1
+ import { migrationIdentity } from '../kernel/ticket-migrations'
1
2
  import { enrichIntegrationRows } from '../cli/dashboard/integration-row'
2
3
  import { dispatchCapacity, type CapacityBuild } from '../kernel/dispatch-capacity'
3
4
  import { forgeReadinessWarnings } from '../kernel/dispatch-status'
@@ -428,7 +429,12 @@ async function dashboardFromView(
428
429
  ...forgeReadinessWarnings(status),
429
430
  ...(status.warningNotice !== undefined ? [status.warningNotice] : []),
430
431
  ]
431
- const capacityProjection = dispatchCapacity(capacityBuilds, config.capacity, opts.clock())
432
+ const capacityProjection = dispatchCapacity(
433
+ capacityBuilds,
434
+ config.capacity,
435
+ opts.clock(),
436
+ migrationIdentity(repositoryEvents.ticketMigrations, config.tickets.source),
437
+ )
432
438
  const model = buildDashboardFromProjected(
433
439
  enrichIntegrationRows(projected, records),
434
440
  {
@@ -1,3 +1,8 @@
1
+ import {
2
+ currentTicketRef,
3
+ readTicketMigrations,
4
+ resolveTicketRef,
5
+ } from '../kernel/ticket-migrations'
1
6
  import { updateTicketTarget } from '../kernel/node-parent'
2
7
  import { projectTicketTree, compatibleTicketSource } from '../ports/tickets/tree'
3
8
  import { readBuildFacts } from '../store/reduced-reads'
@@ -117,31 +122,31 @@ async function matchingBuild(
117
122
  source: TicketSource,
118
123
  configuredSource: string,
119
124
  ): Promise<OperatorTicketBuild | null> {
120
- // The service's database adapter implements the externally named hosted source.
121
- const hosted =
122
- source.name === 'hosted' || (configuredSource === 'hosted' && source.name === 'database')
123
- const candidates = (await store.listBuilds()).filter(
124
- (record) =>
125
- record.repo === repo &&
126
- (record.ticket?.source === source.name || (hosted && record.ticket?.source === 'hosted')),
127
- )
128
- const matches = candidates.filter((record) => record.ticket!.id === id)
129
- // The service database store always projects current ids, even when there is
130
- // no matching build. Only a hosted client over an unprojected legacy store
131
- // needs fallback lookups; failure must not undo a mutation.
132
- if (matches.length === 0 && source.name === 'hosted') {
133
- const identities = new Map<string, string>()
125
+ const candidates = await store.listBuildsForRepo(repo)
126
+ if (!candidates.length) return null
127
+ const migrations = await readTicketMigrations(store, repo)
128
+ const normalized = []
129
+ for (const record of candidates) {
130
+ if (!record.ticket) continue
134
131
  try {
135
- for (const record of candidates) {
136
- const raw = record.ticket!.id
137
- if (!identities.has(raw)) {
138
- const ticket = await source.get(raw)
139
- identities.set(raw, ticket?.ref.source === source.name ? ticket.ref.id : raw)
140
- }
141
- if (identities.get(raw) === id) matches.push(record)
142
- }
132
+ const ref = resolveTicketRef(
133
+ migrations,
134
+ record.ticket,
135
+ source.name === 'database' && configuredSource === 'hosted' ? 'hosted' : source.name,
136
+ record.slug,
137
+ )
138
+ normalized.push({ record, ref })
139
+ } catch {
140
+ /* unrelated historical source has no current ticket association */
141
+ }
142
+ }
143
+ const matches = normalized.filter(({ ref }) => ref.id === id).map(({ record }) => record)
144
+ if (!matches.length && source.name === 'hosted') {
145
+ try {
146
+ for (const { record, ref } of normalized)
147
+ if ((await source.get(ref.id))?.ref.id === id) matches.push(record)
143
148
  } catch {
144
- // Build association is optional presentation; keep the successful ticket result.
149
+ /* optional alias association must not undo a successful mutation */
145
150
  }
146
151
  }
147
152
  const projected = await Promise.all(
@@ -273,9 +278,8 @@ export async function prepareOperatorTicketAssets(opts: {
273
278
  throw new Error('ticket operator backend is not configured')
274
279
  }
275
280
  const { context, source } = await openOperatorTickets({ ...opts, backend: opts.backend })
276
- if (context.tickets.source !== opts.ref.source)
277
- throw new Error('build ticket source differs from configured source')
278
- return preparePinnedAssets(source, opts.store, opts.repo, opts.ref.id)
281
+ const ref = await currentTicketRef(opts.store, opts.repo, context.tickets.source, opts.ref)
282
+ return preparePinnedAssets(source, opts.store, opts.repo, ref.id)
279
283
  }
280
284
 
281
285
  export async function listOperatorTicketStates(opts: {