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

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 (145) hide show
  1. package/SPEC.md +342 -23
  2. package/bin/ab-dispatch-generation.ts +93 -0
  3. package/docs/answering-blocked-builds.md +21 -3
  4. package/docs/architecture.md +170 -7
  5. package/docs/configuration.md +173 -5
  6. package/docs/integration-tree.md +91 -4
  7. package/docs/integration.md +54 -0
  8. package/docs/operator-api.md +58 -5
  9. package/docs/remote-store-protocol.md +9 -1
  10. package/docs/remote-ticket-protocol.md +5 -0
  11. package/docs/restacking.md +4 -1
  12. package/docs/setup.md +24 -0
  13. package/docs/spec-standard.md +94 -5
  14. package/docs/ticket-migration.md +50 -4
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/artifact.ts +5 -4
  17. package/packages/core/src/cli/attention.ts +2 -0
  18. package/packages/core/src/cli/binary-direct.ts +190 -0
  19. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  20. package/packages/core/src/cli/binary.ts +24 -210
  21. package/packages/core/src/cli/build-control.ts +108 -5
  22. package/packages/core/src/cli/context.ts +41 -1
  23. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  24. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  25. package/packages/core/src/cli/dashboard/integration-detail.ts +11 -6
  26. package/packages/core/src/cli/dashboard/integration-row.ts +15 -8
  27. package/packages/core/src/cli/dashboard/model.ts +41 -10
  28. package/packages/core/src/cli/dashboard/render.ts +24 -2
  29. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  30. package/packages/core/src/cli/dispatch-args.ts +53 -0
  31. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  32. package/packages/core/src/cli/dispatch-frontend.ts +57 -5
  33. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  34. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  35. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  36. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  38. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  39. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  40. package/packages/core/src/cli/dispatch-process.ts +22 -90
  41. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +6 -1
  43. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  44. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  45. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  46. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  47. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  48. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  49. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  50. package/packages/core/src/cli/dispatch.ts +609 -60
  51. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  52. package/packages/core/src/cli/harvest.ts +28 -11
  53. package/packages/core/src/cli/help.ts +7 -3
  54. package/packages/core/src/cli/installation.ts +5 -3
  55. package/packages/core/src/cli/main-checkout.ts +59 -0
  56. package/packages/core/src/cli/main.ts +26 -53
  57. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  58. package/packages/core/src/cli/repo-state.ts +3 -58
  59. package/packages/core/src/cli/repository-status.ts +74 -4
  60. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  61. package/packages/core/src/cli/status.ts +57 -3
  62. package/packages/core/src/cli/ticket.ts +35 -11
  63. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  64. package/packages/core/src/cli/wait.ts +3 -0
  65. package/packages/core/src/cli/watch.ts +7 -0
  66. package/packages/core/src/config/live.ts +1 -0
  67. package/packages/core/src/config/schema.ts +8 -4
  68. package/packages/core/src/distribution-packaging.ts +116 -0
  69. package/packages/core/src/events/catalog.ts +6 -0
  70. package/packages/core/src/events/payloads.ts +55 -9
  71. package/packages/core/src/events/policy.ts +26 -0
  72. package/packages/core/src/events/repository.ts +205 -4
  73. package/packages/core/src/events/runtime.ts +16 -0
  74. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +6537 -4053
  75. package/packages/core/src/kernel/change-presence.ts +7 -1
  76. package/packages/core/src/kernel/dispatch-capacity.ts +12 -4
  77. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  78. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  79. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  80. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  81. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  82. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  83. package/packages/core/src/kernel/harvest.ts +98 -4
  84. package/packages/core/src/kernel/integration-attention.ts +20 -0
  85. package/packages/core/src/kernel/integration-completeness.ts +54 -16
  86. package/packages/core/src/kernel/integration-state.ts +80 -11
  87. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  88. package/packages/core/src/kernel/mixed-version.ts +34 -0
  89. package/packages/core/src/kernel/node-parent.ts +35 -10
  90. package/packages/core/src/kernel/node-polling.ts +160 -0
  91. package/packages/core/src/kernel/read-facts.ts +47 -5
  92. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  93. package/packages/core/src/kernel/reducer.ts +75 -14
  94. package/packages/core/src/kernel/service-facts.ts +11 -4
  95. package/packages/core/src/kernel/ticket-migrations.ts +139 -0
  96. package/packages/core/src/operator/presentation.ts +7 -0
  97. package/packages/core/src/operator/query.ts +13 -3
  98. package/packages/core/src/operator/registry.ts +1 -1
  99. package/packages/core/src/operator/tickets.ts +30 -26
  100. package/packages/core/src/plugins/load.ts +4 -1
  101. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  102. package/packages/core/src/ports/forge/contract.ts +29 -0
  103. package/packages/core/src/ports/forge/github.ts +189 -61
  104. package/packages/core/src/ports/forge-failure.ts +1 -0
  105. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  106. package/packages/core/src/ports/runner/session-env.ts +1 -0
  107. package/packages/core/src/ports/tickets/linear.ts +180 -12
  108. package/packages/core/src/ports/tickets/migration.ts +92 -9
  109. package/packages/core/src/ports/types.ts +17 -0
  110. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  111. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  112. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  113. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  114. package/packages/core/src/processes/build-child-exit.ts +5 -26
  115. package/packages/core/src/processes/build-runner.ts +81 -11
  116. package/packages/core/src/processes/dispatcher.ts +418 -59
  117. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  118. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  119. package/packages/core/src/processes/execution-settlement.ts +16 -7
  120. package/packages/core/src/processes/harvest-runner.ts +328 -292
  121. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  122. package/packages/core/src/runtime-identity.ts +22 -3
  123. package/packages/core/src/store/contract.ts +183 -0
  124. package/packages/core/src/store/local/store.ts +197 -72
  125. package/packages/core/src/store/reduced-reads.ts +8 -0
  126. package/packages/core/src/store/reducer-value-shapes.json +8915 -6344
  127. package/packages/core/src/store/remote/client.ts +43 -0
  128. package/packages/core/src/store/repo-state-events.ts +21 -3
  129. package/packages/core/src/store/types.ts +7 -0
  130. package/packages/core/src/testing/dispatch-read-budget.ts +3 -2
  131. package/skills/guide/SKILL.md +234 -24
  132. package/skills/guide/references/integration-tree.md +91 -4
  133. package/skills/guide/references/operator-api.md +53 -4
  134. package/skills/guide/references/plugin-authoring.md +45 -4
  135. package/skills/guide/references/remote-store-protocol.md +9 -1
  136. package/skills/guide/references/remote-ticket-protocol.md +5 -0
  137. package/skills/guide/references/restacking.md +4 -1
  138. package/skills/guide/references/setup.md +24 -0
  139. package/skills/guide/references/spec-standard.md +94 -5
  140. package/skills/guide/references/ticket-migration.md +50 -4
  141. package/skills/harvest/SKILL.md +4 -0
  142. package/skills/harvest-review/SKILL.md +4 -0
  143. package/skills/operate/SKILL.md +78 -8
  144. package/skills/spec/SKILL.md +35 -5
  145. package/skills/tickets/SKILL.md +19 -0
@@ -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 GET_DETAIL_QUERY = `query GetIssue($id: String!) { issue(id: $id) { ${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} } } }`
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
- await this.completeMetadata(issue, false)
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 this.gql(
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 this.gql(
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(issues: DependencyIssue[], ready: boolean): Promise<void> {
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 this.gql<Record<string, RelationOwner | null>>(
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(issue: GqlIssue, ownLabels = true): Promise<void> {
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 this.gql(
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
- if (this.cooldown && this.now() < this.cooldown.resetAt) throw this.cooldown
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
- this.cooldown = new TicketSourceRateLimitError(this.name, resetAt)
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
- for (const summary of await store.listTicketAssets(repo, id)) {
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
- const tickets = await inventory(opts.source)
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
- for (const record of records)
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<void> {
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
@@ -519,6 +526,16 @@ export type {
519
526
  } from './forge-failure'
520
527
 
521
528
  export interface Forge {
529
+ /** Optional observation epoch. Concurrent operations outside the callback stay independent. */
530
+ withReadScope?<T>(work: () => Promise<T>): Promise<T>
531
+ /** Prime opened-node observations; absent capabilities preserve ordinary reads. */
532
+ primeNodeReads?(input: {
533
+ workspacePath: string
534
+ parent: string
535
+ head: string
536
+ prNumber?: number
537
+ }): Promise<void>
538
+
522
539
  /** Optional API 1.8 capability. Absence means unavailable counts. */
523
540
  observeRequests?(observer: import('./forge-failure').ForgeRequestObserver): () => void
524
541