@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.
- package/SPEC.md +25 -3
- package/docs/architecture.md +4 -0
- package/docs/integration-tree.md +4 -2
- package/docs/remote-store-protocol.md +5 -0
- package/docs/remote-ticket-protocol.md +5 -0
- package/docs/setup.md +4 -0
- package/docs/spec-standard.md +71 -0
- package/docs/ticket-migration.md +50 -4
- package/package.json +3 -3
- package/packages/core/src/cli/build-control.ts +3 -3
- package/packages/core/src/cli/dashboard/integration-detail.ts +8 -6
- package/packages/core/src/cli/dashboard/integration-row.ts +15 -8
- package/packages/core/src/cli/dashboard/model.ts +7 -0
- package/packages/core/src/cli/dispatch-frontend.ts +5 -0
- package/packages/core/src/cli/dispatch-repository-feed.ts +2 -1
- package/packages/core/src/cli/dispatch.ts +5 -0
- package/packages/core/src/cli/help.ts +1 -0
- package/packages/core/src/cli/main.ts +11 -8
- package/packages/core/src/cli/repository-status.ts +7 -1
- package/packages/core/src/cli/ticket.ts +35 -11
- package/packages/core/src/events/payloads.ts +2 -0
- package/packages/core/src/events/policy.ts +1 -0
- package/packages/core/src/events/repository.ts +21 -0
- package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +4025 -3978
- package/packages/core/src/kernel/change-presence.ts +7 -1
- package/packages/core/src/kernel/dispatch-capacity.ts +12 -4
- package/packages/core/src/kernel/integration-completeness.ts +54 -16
- package/packages/core/src/kernel/node-parent.ts +35 -10
- package/packages/core/src/kernel/read-facts.ts +7 -0
- package/packages/core/src/kernel/reducer-registry.ts +3 -0
- package/packages/core/src/kernel/reducer.ts +1 -1
- package/packages/core/src/kernel/ticket-migrations.ts +139 -0
- package/packages/core/src/operator/query.ts +7 -1
- package/packages/core/src/operator/tickets.ts +30 -26
- package/packages/core/src/ports/tickets/linear.ts +180 -12
- package/packages/core/src/ports/tickets/migration.ts +92 -9
- package/packages/core/src/ports/types.ts +7 -0
- package/packages/core/src/processes/dispatcher.ts +164 -36
- package/packages/core/src/store/contract.ts +30 -0
- package/packages/core/src/store/reducer-value-shapes.json +5735 -5642
- package/packages/core/src/store/repo-state-events.ts +3 -2
- package/packages/core/src/testing/dispatch-read-budget.ts +3 -2
- package/skills/guide/SKILL.md +3 -1
- package/skills/guide/references/integration-tree.md +4 -2
- package/skills/guide/references/remote-store-protocol.md +5 -0
- package/skills/guide/references/remote-ticket-protocol.md +5 -0
- package/skills/guide/references/setup.md +4 -0
- package/skills/guide/references/spec-standard.md +71 -0
- package/skills/guide/references/ticket-migration.md +50 -4
- package/skills/spec/SKILL.md +16 -4
|
@@ -12,6 +12,7 @@ import { ticketRevision } from './revision'
|
|
|
12
12
|
*/
|
|
13
13
|
import { z } from 'zod'
|
|
14
14
|
import type {
|
|
15
|
+
ExportSnapshotOptions,
|
|
15
16
|
DependencyState,
|
|
16
17
|
Ticket,
|
|
17
18
|
TicketCreateOptions,
|
|
@@ -71,7 +72,7 @@ function isEntityNotFound(error: unknown): boolean {
|
|
|
71
72
|
/** The narrow slice of fetch this adapter needs — injectable for tests. */
|
|
72
73
|
export type LinearFetch = (
|
|
73
74
|
url: string,
|
|
74
|
-
init: { method: 'POST'; headers: Record<string, string>; body: string },
|
|
75
|
+
init: { method: 'POST'; headers: Record<string, string>; body: string; signal?: AbortSignal },
|
|
75
76
|
) => Promise<{
|
|
76
77
|
ok: boolean
|
|
77
78
|
status: number
|
|
@@ -250,7 +251,8 @@ function nextCursor(info: PageInfo | undefined, seen: Set<string>): string | nul
|
|
|
250
251
|
return cursor
|
|
251
252
|
}
|
|
252
253
|
|
|
253
|
-
const
|
|
254
|
+
const DETAIL_FIELDS = `${METADATA_FIELDS} id identifier title description url state { name type } labels(first: 100) { nodes { name } ${PAGE_INFO} } inverseRelations(first: 100) { nodes { ${READY_RELATIONS} } ${PAGE_INFO} } comments(first: 100, includeArchived: true, orderBy: createdAt) { nodes { body createdAt user { name } } ${PAGE_INFO} }`
|
|
255
|
+
const GET_DETAIL_QUERY = `query GetIssue($id: String!) { issue(id: $id) { ${DETAIL_FIELDS} } }`
|
|
254
256
|
const GET_ISSUE_QUERY = `query GetIssue($id: String!) { issue(id: $id) { ${ISSUE_FIELDS} } }`
|
|
255
257
|
const RESOLVE_ISSUE_QUERY = `query ResolveIssue($id: String!) { issue(id: $id) { id } }`
|
|
256
258
|
const ISSUE_STATE_QUERY = `query IssueState($id: String!) { issue(id: $id) { id state { name type } } }`
|
|
@@ -265,10 +267,136 @@ const CREATE_RELATION_MUTATION = `mutation CreateRelation($issueId: String!, $re
|
|
|
265
267
|
const DELETE_RELATION_MUTATION = `mutation DeleteRelation($id: String!) { issueRelationDelete(id: $id) { success } }`
|
|
266
268
|
const linearReservedIssueIdSchema = z.uuidv4()
|
|
267
269
|
|
|
270
|
+
type ReadQuery = <T>(
|
|
271
|
+
operation: string,
|
|
272
|
+
query: string,
|
|
273
|
+
variables: Record<string, unknown>,
|
|
274
|
+
) => Promise<T>
|
|
275
|
+
class ExportRateLimit extends TicketSourceRateLimitError {
|
|
276
|
+
constructor(
|
|
277
|
+
resetAt: number,
|
|
278
|
+
readonly exportReset?: number,
|
|
279
|
+
) {
|
|
280
|
+
super('linear', resetAt)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
285
|
+
signal?.throwIfAborted()
|
|
286
|
+
await new Promise<void>((resolve, reject) => {
|
|
287
|
+
const cleanup = () => {
|
|
288
|
+
clearTimeout(timer)
|
|
289
|
+
signal?.removeEventListener('abort', abort)
|
|
290
|
+
}
|
|
291
|
+
const abort = () => {
|
|
292
|
+
cleanup()
|
|
293
|
+
reject(signal?.reason)
|
|
294
|
+
}
|
|
295
|
+
const timer = setTimeout(() => {
|
|
296
|
+
cleanup()
|
|
297
|
+
resolve()
|
|
298
|
+
}, ms)
|
|
299
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
300
|
+
})
|
|
301
|
+
}
|
|
302
|
+
|
|
268
303
|
export class LinearTicketSource implements TicketSource {
|
|
269
304
|
readonly name = 'linear'
|
|
270
305
|
readonly integrationTree = true
|
|
271
306
|
|
|
307
|
+
async readExportSnapshot(opts: ExportSnapshotOptions = {}): Promise<Ticket[]> {
|
|
308
|
+
let completed = 0
|
|
309
|
+
let total: number | undefined
|
|
310
|
+
const progress = (resetAt?: number) => opts.progress?.({ completed, total, resetAt })
|
|
311
|
+
const read: ReadQuery = async <T>(
|
|
312
|
+
operation: string,
|
|
313
|
+
query: string,
|
|
314
|
+
variables: Record<string, unknown>,
|
|
315
|
+
): Promise<T> => {
|
|
316
|
+
for (;;) {
|
|
317
|
+
opts.signal?.throwIfAborted()
|
|
318
|
+
try {
|
|
319
|
+
return await this.gql<T>(operation, query, variables, opts.signal, true)
|
|
320
|
+
} catch (error) {
|
|
321
|
+
opts.signal?.throwIfAborted()
|
|
322
|
+
if (
|
|
323
|
+
!(error instanceof ExportRateLimit) ||
|
|
324
|
+
error.exportReset === undefined ||
|
|
325
|
+
error.exportReset <= this.now()
|
|
326
|
+
)
|
|
327
|
+
throw error
|
|
328
|
+
progress(error.exportReset)
|
|
329
|
+
while (this.now() < error.exportReset) {
|
|
330
|
+
await this.sleep(Math.min(error.exportReset - this.now(), 2_147_483_647), opts.signal)
|
|
331
|
+
opts.signal?.throwIfAborted()
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
// Linear charges .1 per scalar and 1 per object, multiplied by bounds:
|
|
337
|
+
// 20 * (15 metadata/wrappers + 2*25*1.1 labels + 25*3.5 relations
|
|
338
|
+
// + 25*2.3 comments) + 250*1.1 inventory + wrappers < 5,000 points.
|
|
339
|
+
// https://linear.app/developers/rate-limiting (query ceiling: 10,000).
|
|
340
|
+
const detailFields = DETAIL_FIELDS.replaceAll('first: 100', 'first: 25').replaceAll(
|
|
341
|
+
'first: 50',
|
|
342
|
+
'first: 25',
|
|
343
|
+
)
|
|
344
|
+
const selection = `issues(filter: $filter, first: 20, after: $after, includeArchived: true) { nodes { ${detailFields} } ${PAGE_INFO} }`
|
|
345
|
+
const inventory = `issues(filter: $filter, first: 250, after: $after, includeArchived: true) { nodes { id } ${PAGE_INFO} }`
|
|
346
|
+
const filter = { team: { key: { eq: this.teamKey } } }
|
|
347
|
+
const query = `query ExportSnapshot($filter: IssueFilter!, $after: String) { ${selection} inventory: ${inventory} }`
|
|
348
|
+
progress()
|
|
349
|
+
const first = await read<{
|
|
350
|
+
issues: Connection<GqlIssue>
|
|
351
|
+
inventory: Connection<{ id: string }>
|
|
352
|
+
}>('export', query, { filter, after: null })
|
|
353
|
+
const ids = new Set<string>()
|
|
354
|
+
const collect = (page: Connection<{ id?: string }>) => {
|
|
355
|
+
for (const issue of page.nodes) {
|
|
356
|
+
if (!issue.id || ids.has(issue.id))
|
|
357
|
+
throw new Error('linear: duplicate or missing export identity')
|
|
358
|
+
ids.add(issue.id)
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
collect(first.inventory)
|
|
362
|
+
const inventorySeen = new Set<string>()
|
|
363
|
+
let after = nextCursor(first.inventory.pageInfo, inventorySeen)
|
|
364
|
+
while (after !== null) {
|
|
365
|
+
const page = await read<{ issues: Connection<{ id: string }> }>(
|
|
366
|
+
'exportInventory',
|
|
367
|
+
`query ExportInventory($filter: IssueFilter!, $after: String) { ${inventory} }`,
|
|
368
|
+
{ filter, after },
|
|
369
|
+
)
|
|
370
|
+
collect(page.issues)
|
|
371
|
+
after = nextCursor(page.issues.pageInfo, inventorySeen)
|
|
372
|
+
}
|
|
373
|
+
total = ids.size
|
|
374
|
+
progress()
|
|
375
|
+
const tickets: Ticket[] = []
|
|
376
|
+
const seen = new Set<string>()
|
|
377
|
+
let page = first.issues
|
|
378
|
+
do {
|
|
379
|
+
for (const issue of page.nodes) {
|
|
380
|
+
if (!issue.id || !ids.delete(issue.id))
|
|
381
|
+
throw new Error('linear: export identities disagree')
|
|
382
|
+
tickets.push(await this.hydrateDetail(issue, issue.identifier, read))
|
|
383
|
+
completed++
|
|
384
|
+
progress()
|
|
385
|
+
}
|
|
386
|
+
after = nextCursor(page.pageInfo, seen)
|
|
387
|
+
if (after !== null)
|
|
388
|
+
page = (
|
|
389
|
+
await read<{ issues: Connection<GqlIssue> }>(
|
|
390
|
+
'export',
|
|
391
|
+
`query ExportDetails($filter: IssueFilter!, $after: String) { ${selection} }`,
|
|
392
|
+
{ filter, after },
|
|
393
|
+
)
|
|
394
|
+
).issues
|
|
395
|
+
} while (after !== null)
|
|
396
|
+
if (ids.size) throw new Error('linear: export identities disagree')
|
|
397
|
+
return tickets
|
|
398
|
+
}
|
|
399
|
+
|
|
272
400
|
async listAll(): Promise<TicketListing> {
|
|
273
401
|
return this.listReady({})
|
|
274
402
|
}
|
|
@@ -278,6 +406,7 @@ export class LinearTicketSource implements TicketSource {
|
|
|
278
406
|
private readonly claimedState: string
|
|
279
407
|
private readonly createState: string | undefined
|
|
280
408
|
private readonly now: () => number
|
|
409
|
+
private readonly sleep: (ms: number, signal?: AbortSignal) => Promise<void>
|
|
281
410
|
private cooldown?: TicketSourceRateLimitError
|
|
282
411
|
private readonly fetchFn: LinearFetch
|
|
283
412
|
|
|
@@ -294,6 +423,7 @@ export class LinearTicketSource implements TicketSource {
|
|
|
294
423
|
teamKey: string
|
|
295
424
|
fetchFn?: LinearFetch
|
|
296
425
|
now?: () => number
|
|
426
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>
|
|
297
427
|
/** Workflow state claim() moves the issue to (claim-before-launch, §12). */
|
|
298
428
|
claimedState?: string
|
|
299
429
|
/** Workflow state create() files new issues into; absent = Linear's team
|
|
@@ -301,6 +431,7 @@ export class LinearTicketSource implements TicketSource {
|
|
|
301
431
|
createState?: string
|
|
302
432
|
}) {
|
|
303
433
|
this.now = opts.now ?? Date.now
|
|
434
|
+
this.sleep = opts.sleep ?? abortableSleep
|
|
304
435
|
this.apiKey = opts.apiKey
|
|
305
436
|
this.teamKey = opts.teamKey
|
|
306
437
|
this.claimedState = opts.claimedState ?? 'In Progress'
|
|
@@ -429,13 +560,21 @@ export class LinearTicketSource implements TicketSource {
|
|
|
429
560
|
}
|
|
430
561
|
if (requireTeam && issue.team && issue.team.key !== this.teamKey)
|
|
431
562
|
throw new Error(`target ${id} is in a different source/team (${issue.team.key})`)
|
|
432
|
-
|
|
563
|
+
return this.hydrateDetail(issue, id)
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
private async hydrateDetail(
|
|
567
|
+
issue: GqlIssue,
|
|
568
|
+
id: string,
|
|
569
|
+
read: ReadQuery = this.gql.bind(this),
|
|
570
|
+
): Promise<Ticket> {
|
|
571
|
+
await this.completeMetadata(issue, false, read)
|
|
433
572
|
// Detail reads exhaust labels and relations independently of dispatch bounds.
|
|
434
573
|
const labels: Array<{ name: string }> = [...issue.labels.nodes]
|
|
435
574
|
const labelSeen = new Set<string>()
|
|
436
575
|
let labelAfter = nextCursor(issue.labels.pageInfo, labelSeen)
|
|
437
576
|
while (labelAfter !== null) {
|
|
438
|
-
const page: { issue: { labels: Connection<{ name: string }> } } = await
|
|
577
|
+
const page: { issue: { labels: Connection<{ name: string }> } } = await read(
|
|
439
578
|
'getLabels',
|
|
440
579
|
`query TicketLabels($id: String!, $after: String) { issue(id: $id) { labels(first: 100, after: $after) { nodes { name } ${PAGE_INFO} } } }`,
|
|
441
580
|
{ id: issue.id ?? id, after: labelAfter },
|
|
@@ -444,7 +583,7 @@ export class LinearTicketSource implements TicketSource {
|
|
|
444
583
|
labelAfter = nextCursor(page.issue.labels.pageInfo, labelSeen)
|
|
445
584
|
}
|
|
446
585
|
issue.labels = { nodes: labels }
|
|
447
|
-
await this.completeRelations([issue], true)
|
|
586
|
+
await this.completeRelations([issue], true, read)
|
|
448
587
|
const mapComment = (c: { body: string; createdAt: string; user: { name: string } | null }) => ({
|
|
449
588
|
body: c.body,
|
|
450
589
|
createdAt: c.createdAt,
|
|
@@ -460,7 +599,7 @@ export class LinearTicketSource implements TicketSource {
|
|
|
460
599
|
issue: {
|
|
461
600
|
comments: Connection<{ body: string; createdAt: string; user: { name: string } | null }>
|
|
462
601
|
}
|
|
463
|
-
} = await
|
|
602
|
+
} = await read(
|
|
464
603
|
'getComments',
|
|
465
604
|
`query TicketComments($id: String!, $after: String) { issue(id: $id) { comments(first: 100, after: $after, includeArchived: true, orderBy: createdAt) { nodes { body createdAt user { name } } ${PAGE_INFO} } } }`,
|
|
466
605
|
{ id: issue.id ?? id, after },
|
|
@@ -786,7 +925,11 @@ export class LinearTicketSource implements TicketSource {
|
|
|
786
925
|
|
|
787
926
|
/** Each alias owns a cursor. Graph reads retain the historic first 250
|
|
788
927
|
* relations; listing reads exhaust relations, including blockers after 250. */
|
|
789
|
-
private async completeRelations(
|
|
928
|
+
private async completeRelations(
|
|
929
|
+
issues: DependencyIssue[],
|
|
930
|
+
ready: boolean,
|
|
931
|
+
read: ReadQuery = this.gql.bind(this),
|
|
932
|
+
): Promise<void> {
|
|
790
933
|
const pending = issues.map((issue) => ({
|
|
791
934
|
issue,
|
|
792
935
|
seen: new Set<string>(),
|
|
@@ -819,7 +962,7 @@ export class LinearTicketSource implements TicketSource {
|
|
|
819
962
|
)
|
|
820
963
|
variables[`after${n}`] = item.after
|
|
821
964
|
})
|
|
822
|
-
const data = await
|
|
965
|
+
const data = await read<Record<string, RelationOwner | null>>(
|
|
823
966
|
'relations',
|
|
824
967
|
`query Relations(${definitions.join(', ')}) { ${selections.join(' ')} }`,
|
|
825
968
|
variables,
|
|
@@ -849,7 +992,11 @@ export class LinearTicketSource implements TicketSource {
|
|
|
849
992
|
return result
|
|
850
993
|
}
|
|
851
994
|
|
|
852
|
-
private async completeMetadata(
|
|
995
|
+
private async completeMetadata(
|
|
996
|
+
issue: GqlIssue,
|
|
997
|
+
ownLabels = true,
|
|
998
|
+
read: ReadQuery = this.gql.bind(this),
|
|
999
|
+
): Promise<void> {
|
|
853
1000
|
const complete = async (owner: {
|
|
854
1001
|
id?: string
|
|
855
1002
|
identifier: string
|
|
@@ -859,7 +1006,7 @@ export class LinearTicketSource implements TicketSource {
|
|
|
859
1006
|
let after = nextCursor(owner.labels.pageInfo, seen)
|
|
860
1007
|
const labels = [...owner.labels.nodes]
|
|
861
1008
|
while (after !== null) {
|
|
862
|
-
const page: { issue: { labels: Connection<{ name: string }> } } = await
|
|
1009
|
+
const page: { issue: { labels: Connection<{ name: string }> } } = await read(
|
|
863
1010
|
'metadataLabels',
|
|
864
1011
|
`query TicketLabels($id: String!, $after: String) { issue(id: $id) { labels(first: 100, after: $after) { nodes { name } ${PAGE_INFO} } } }`,
|
|
865
1012
|
{ id: owner.id ?? owner.identifier, after },
|
|
@@ -982,16 +1129,26 @@ export class LinearTicketSource implements TicketSource {
|
|
|
982
1129
|
operation: string,
|
|
983
1130
|
query: string,
|
|
984
1131
|
variables: Record<string, unknown>,
|
|
1132
|
+
signal?: AbortSignal,
|
|
1133
|
+
exportRead = false,
|
|
985
1134
|
): Promise<T> {
|
|
986
|
-
|
|
1135
|
+
signal?.throwIfAborted()
|
|
1136
|
+
const exportReset =
|
|
1137
|
+
this.cooldown instanceof ExportRateLimit ? this.cooldown.exportReset : undefined
|
|
1138
|
+
const cooldownUntil =
|
|
1139
|
+
exportRead && exportReset !== undefined ? exportReset : this.cooldown?.resetAt
|
|
1140
|
+
if (this.cooldown && cooldownUntil !== undefined && this.now() < cooldownUntil)
|
|
1141
|
+
throw this.cooldown
|
|
987
1142
|
const response = await this.fetchFn(LINEAR_API_URL, {
|
|
988
1143
|
method: 'POST',
|
|
1144
|
+
signal,
|
|
989
1145
|
headers: {
|
|
990
1146
|
Authorization: this.apiKey,
|
|
991
1147
|
'Content-Type': 'application/json',
|
|
992
1148
|
},
|
|
993
1149
|
body: JSON.stringify({ query, variables }),
|
|
994
1150
|
})
|
|
1151
|
+
signal?.throwIfAborted()
|
|
995
1152
|
const http = `linear ${operation}: HTTP ${response.status}`
|
|
996
1153
|
let raw: unknown
|
|
997
1154
|
try {
|
|
@@ -1000,6 +1157,7 @@ export class LinearTicketSource implements TicketSource {
|
|
|
1000
1157
|
if (!response.ok) throw new Error(http)
|
|
1001
1158
|
throw error
|
|
1002
1159
|
}
|
|
1160
|
+
signal?.throwIfAborted()
|
|
1003
1161
|
const payload = (raw !== null && typeof raw === 'object' ? raw : {}) as {
|
|
1004
1162
|
data?: T | null
|
|
1005
1163
|
errors?: GqlError[]
|
|
@@ -1015,7 +1173,17 @@ export class LinearTicketSource implements TicketSource {
|
|
|
1015
1173
|
Number.isFinite(reset) && reset > now && reset > 0 && reset <= 8.64e15
|
|
1016
1174
|
? reset
|
|
1017
1175
|
: now + 60_000
|
|
1018
|
-
|
|
1176
|
+
const kinds = ['requests', 'complexity', 'endpoint-requests']
|
|
1177
|
+
const exhausted = kinds.filter((kind) => {
|
|
1178
|
+
const remaining = response.headers?.get(`x-ratelimit-${kind}-remaining`)
|
|
1179
|
+
return remaining?.trim() && Number.isFinite(Number(remaining)) && Number(remaining) <= 0
|
|
1180
|
+
})
|
|
1181
|
+
const resets = (exhausted.length ? exhausted : kinds).flatMap((kind) => {
|
|
1182
|
+
const value = response.headers?.get(`x-ratelimit-${kind}-reset`)
|
|
1183
|
+
const date = value?.trim() ? Number(value) : NaN
|
|
1184
|
+
return Number.isFinite(date) && date > now && date <= 8.64e15 ? [date] : []
|
|
1185
|
+
})
|
|
1186
|
+
this.cooldown = new ExportRateLimit(resetAt, resets.length ? Math.max(...resets) : undefined)
|
|
1019
1187
|
throw this.cooldown
|
|
1020
1188
|
}
|
|
1021
1189
|
if (errors.length > 0) {
|
|
@@ -10,23 +10,61 @@ import { validateFileTicketId } from './requested-id'
|
|
|
10
10
|
import { normalizeStateName } from './states'
|
|
11
11
|
import { encodePortableAsset, decodePortableAsset, type PortableAsset } from './portable-assets'
|
|
12
12
|
|
|
13
|
-
const MANIFEST = '.ab-migration.json'
|
|
13
|
+
export const MANIFEST = '.ab-migration.json'
|
|
14
14
|
export const IMPORT_MAP = '.ab-import-map.json'
|
|
15
15
|
const manifestSchema = z.strictObject({
|
|
16
16
|
version: z.literal(1),
|
|
17
17
|
identity: z.string().min(1),
|
|
18
|
-
source: z.string(),
|
|
18
|
+
source: z.string().regex(/^[a-z][a-z0-9-]*(?::[\s\S]*)?$/),
|
|
19
19
|
keys: z.record(z.string(), z.string().min(1)),
|
|
20
20
|
states: z.record(z.string(), z.string()),
|
|
21
21
|
})
|
|
22
|
-
type Manifest = z.infer<typeof manifestSchema>
|
|
22
|
+
export type Manifest = z.infer<typeof manifestSchema>
|
|
23
|
+
export async function readMigrationManifest(dir: string): Promise<Manifest> {
|
|
24
|
+
return manifestSchema.parse(JSON.parse(await readFile(join(resolve(dir), MANIFEST), 'utf8')))
|
|
25
|
+
}
|
|
26
|
+
export function migrationSource(manifest: Manifest): string {
|
|
27
|
+
// v1 combines adapter name and repository provenance; URLs may contain colons.
|
|
28
|
+
return manifest.source.split(':', 1)[0]!
|
|
29
|
+
}
|
|
30
|
+
export interface MigrationResult {
|
|
31
|
+
identity: string
|
|
32
|
+
from: string
|
|
33
|
+
to: string
|
|
34
|
+
mapping: Record<string, string>
|
|
35
|
+
}
|
|
36
|
+
export async function directMigration(opts: MigrationOptions): Promise<MigrationResult> {
|
|
37
|
+
if (opts.source.name !== 'file')
|
|
38
|
+
throw new Error('direct migration recording requires a file destination')
|
|
39
|
+
const manifest = await readMigrationManifest(opts.dir)
|
|
40
|
+
const mapping: Record<string, string> = Object.create(null)
|
|
41
|
+
const exported = new FileTicketSource({ dir: resolve(opts.dir) })
|
|
42
|
+
// The manifest freezes the export inventory; the directory may now be a live
|
|
43
|
+
// tracker with additional tickets. Only the original IDs establish continuity.
|
|
44
|
+
for (const [id, key] of Object.entries(manifest.keys)) {
|
|
45
|
+
validateFileTicketId(id)
|
|
46
|
+
const ticket = await exported.get(id)
|
|
47
|
+
const destination = await opts.source.get(id)
|
|
48
|
+
if (ticket?.creationKey !== key || destination?.creationKey !== key)
|
|
49
|
+
throw new Error(`migration evidence mismatch for ${id}`)
|
|
50
|
+
mapping[id] = id
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
identity: manifest.identity,
|
|
54
|
+
from: migrationSource(manifest),
|
|
55
|
+
to: opts.source.name,
|
|
56
|
+
mapping,
|
|
57
|
+
}
|
|
58
|
+
}
|
|
23
59
|
async function atomicJson(path: string, value: unknown) {
|
|
24
60
|
const temp = `${path}.${crypto.randomUUID()}.tmp`
|
|
25
61
|
await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`)
|
|
26
62
|
await rename(temp, path)
|
|
27
63
|
}
|
|
28
|
-
async function inventory(source: TicketSource): Promise<Ticket[]> {
|
|
64
|
+
async function inventory(source: TicketSource, signal?: AbortSignal): Promise<Ticket[]> {
|
|
65
|
+
signal?.throwIfAborted()
|
|
29
66
|
const listing = await source.listReady({})
|
|
67
|
+
signal?.throwIfAborted()
|
|
30
68
|
if (listing.diagnostics.length)
|
|
31
69
|
throw new Error(`incomplete ticket scan:\n${listing.diagnostics.join('\n')}`)
|
|
32
70
|
const ids = new Set<string>()
|
|
@@ -34,7 +72,9 @@ async function inventory(source: TicketSource): Promise<Ticket[]> {
|
|
|
34
72
|
for (const ticket of listing.tickets) {
|
|
35
73
|
if (ids.has(ticket.ref.id)) throw new Error(`duplicate ticket id: ${ticket.ref.id}`)
|
|
36
74
|
ids.add(ticket.ref.id)
|
|
75
|
+
signal?.throwIfAborted()
|
|
37
76
|
const detail = await source.get(ticket.ref.id)
|
|
77
|
+
signal?.throwIfAborted()
|
|
38
78
|
if (!detail) throw new Error(`ticket disappeared: ${ticket.ref.id}`)
|
|
39
79
|
if (!detail.state) throw new Error(`ticket has no state: ${ticket.ref.id}`)
|
|
40
80
|
tickets.push(detail)
|
|
@@ -60,11 +100,17 @@ async function currentAssets(
|
|
|
60
100
|
store: TicketAssetStore | undefined,
|
|
61
101
|
repo: string,
|
|
62
102
|
id: string,
|
|
103
|
+
signal?: AbortSignal,
|
|
63
104
|
): Promise<PortableAsset[]> {
|
|
105
|
+
signal?.throwIfAborted()
|
|
64
106
|
if (!store) return []
|
|
65
107
|
const result: PortableAsset[] = []
|
|
66
|
-
|
|
108
|
+
const summaries = await store.listTicketAssets(repo, id)
|
|
109
|
+
signal?.throwIfAborted()
|
|
110
|
+
for (const summary of summaries) {
|
|
111
|
+
signal?.throwIfAborted()
|
|
67
112
|
const asset = await store.getTicketAsset(repo, id, summary.kind, summary.name, summary.revision)
|
|
113
|
+
signal?.throwIfAborted()
|
|
68
114
|
if (!asset) throw new Error(`asset disappeared: ${id} ${summary.kind}/${summary.name}`)
|
|
69
115
|
result.push(encodePortableAsset({ ...asset.meta, entries: asset.entries }))
|
|
70
116
|
}
|
|
@@ -75,10 +121,13 @@ export interface MigrationOptions {
|
|
|
75
121
|
dir: string
|
|
76
122
|
repo: string
|
|
77
123
|
assets?: TicketAssetStore
|
|
124
|
+
signal?: AbortSignal
|
|
78
125
|
print?: (line: string) => void
|
|
79
126
|
}
|
|
80
127
|
/** Publish a complete portable tracker only after every source read succeeds. */
|
|
81
128
|
export async function exportTickets(opts: MigrationOptions): Promise<void> {
|
|
129
|
+
const check = () => opts.signal?.throwIfAborted()
|
|
130
|
+
check()
|
|
82
131
|
const destination = resolve(opts.dir)
|
|
83
132
|
try {
|
|
84
133
|
if ((await readdir(destination)).length)
|
|
@@ -86,11 +135,29 @@ export async function exportTickets(opts: MigrationOptions): Promise<void> {
|
|
|
86
135
|
} catch (error) {
|
|
87
136
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
88
137
|
}
|
|
89
|
-
|
|
138
|
+
check()
|
|
139
|
+
const tickets = opts.source.readExportSnapshot
|
|
140
|
+
? await opts.source.readExportSnapshot({
|
|
141
|
+
signal: opts.signal,
|
|
142
|
+
progress: ({ completed, total, resetAt }) => {
|
|
143
|
+
opts.print?.(
|
|
144
|
+
`read ${completed}/${total ?? 'pending'} tickets${resetAt === undefined ? '' : `; waiting until ${new Date(resetAt).toISOString()}`}`,
|
|
145
|
+
)
|
|
146
|
+
},
|
|
147
|
+
})
|
|
148
|
+
: await inventory(opts.source, opts.signal)
|
|
149
|
+
check()
|
|
150
|
+
const ids = new Set<string>()
|
|
151
|
+
for (const ticket of tickets) {
|
|
152
|
+
if (ids.has(ticket.ref.id)) throw new Error(`duplicate ticket id: ${ticket.ref.id}`)
|
|
153
|
+
ids.add(ticket.ref.id)
|
|
154
|
+
if (!ticket.state) throw new Error(`ticket has no state: ${ticket.ref.id}`)
|
|
155
|
+
}
|
|
90
156
|
const names = [
|
|
91
157
|
...tickets.map((ticket) => ticket.state!),
|
|
92
158
|
...((await opts.source.listStates?.()) ?? []).map((state) => state.name),
|
|
93
159
|
]
|
|
160
|
+
check()
|
|
94
161
|
const states = uniqueStateMap(names, normalizeStateName)
|
|
95
162
|
const identity = crypto.randomUUID()
|
|
96
163
|
const manifest: Manifest = {
|
|
@@ -102,6 +169,7 @@ export async function exportTickets(opts: MigrationOptions): Promise<void> {
|
|
|
102
169
|
}
|
|
103
170
|
const records = []
|
|
104
171
|
for (const ticket of tickets) {
|
|
172
|
+
check()
|
|
105
173
|
validateFileTicketId(ticket.ref.id)
|
|
106
174
|
const key = ticket.creationKey ?? `migration:${identity}:${ticket.ref.id}`
|
|
107
175
|
manifest.keys[ticket.ref.id] = key
|
|
@@ -122,27 +190,36 @@ export async function exportTickets(opts: MigrationOptions): Promise<void> {
|
|
|
122
190
|
opts.assets ?? opts.source.assets,
|
|
123
191
|
opts.repo,
|
|
124
192
|
ticket.ref.id,
|
|
193
|
+
opts.signal,
|
|
125
194
|
),
|
|
126
195
|
},
|
|
127
196
|
ticket.body,
|
|
128
197
|
),
|
|
129
198
|
})
|
|
130
199
|
}
|
|
200
|
+
check()
|
|
131
201
|
await mkdir(dirname(destination), { recursive: true })
|
|
132
202
|
const staging = `${destination}.${identity}.tmp`
|
|
133
203
|
await mkdir(staging)
|
|
134
204
|
try {
|
|
135
|
-
for (const state of Object.values(states))
|
|
205
|
+
for (const state of Object.values(states)) {
|
|
206
|
+
check()
|
|
136
207
|
await mkdir(join(staging, state), { recursive: true })
|
|
137
|
-
|
|
208
|
+
}
|
|
209
|
+
for (const record of records) {
|
|
210
|
+
check()
|
|
138
211
|
await writeFile(join(staging, record.state, `${record.id}.md`), record.raw, { flag: 'wx' })
|
|
212
|
+
}
|
|
213
|
+
check()
|
|
139
214
|
await atomicJson(join(staging, MANIFEST), manifest)
|
|
140
215
|
// Recheck immediately before publication; never remove a populated destination.
|
|
141
216
|
try {
|
|
217
|
+
check()
|
|
142
218
|
await rmdir(destination)
|
|
143
219
|
} catch (error) {
|
|
144
220
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
145
221
|
}
|
|
222
|
+
check()
|
|
146
223
|
await rename(staging, destination)
|
|
147
224
|
} finally {
|
|
148
225
|
await rm(staging, { recursive: true, force: true })
|
|
@@ -156,7 +233,7 @@ function matchState(name: string, existing: string[]): string | undefined {
|
|
|
156
233
|
return matches[0]
|
|
157
234
|
}
|
|
158
235
|
/** Resume through creation keys, never through content similarity or mapping files. */
|
|
159
|
-
export async function importTickets(opts: MigrationOptions): Promise<
|
|
236
|
+
export async function importTickets(opts: MigrationOptions): Promise<MigrationResult> {
|
|
160
237
|
const policy = opts.source.requestedIds
|
|
161
238
|
if (!policy || !opts.source.listStates || !opts.source.addState)
|
|
162
239
|
throw new Error(`ticket source ${opts.source.name} does not support import`)
|
|
@@ -352,6 +429,12 @@ export async function importTickets(opts: MigrationOptions): Promise<void> {
|
|
|
352
429
|
}
|
|
353
430
|
}
|
|
354
431
|
opts.print?.(`mapping: ${mappingPath}`)
|
|
432
|
+
return {
|
|
433
|
+
identity: manifest.identity,
|
|
434
|
+
from: migrationSource(manifest),
|
|
435
|
+
to: opts.source.name,
|
|
436
|
+
mapping,
|
|
437
|
+
}
|
|
355
438
|
} catch (error) {
|
|
356
439
|
throw new Error(
|
|
357
440
|
`${error instanceof Error ? error.message : error}\nImport progress retained in ${mappingPath}; rerun import to finish.`,
|
|
@@ -192,7 +192,14 @@ export type TicketMutation =
|
|
|
192
192
|
| { kind: 'transition'; state: string }
|
|
193
193
|
| { kind: 'blockers'; operation: 'block' | 'unblock'; ids: string[] }
|
|
194
194
|
|
|
195
|
+
export interface ExportSnapshotOptions {
|
|
196
|
+
signal?: AbortSignal
|
|
197
|
+
progress?: (progress: { completed: number; total?: number; resetAt?: number }) => void
|
|
198
|
+
}
|
|
199
|
+
|
|
195
200
|
export interface TicketSource {
|
|
201
|
+
/** Complete export-only snapshot; ordinary dispatch reads keep their own policy. */
|
|
202
|
+
readExportSnapshot?(opts?: ExportSnapshotOptions): Promise<Ticket[]>
|
|
196
203
|
/** Opt in only when kind/target persistence, graph validation and complete
|
|
197
204
|
* enumeration are supported at every write boundary, including guarded writes. */
|
|
198
205
|
readonly integrationTree?: boolean
|