@defrex/autobuild 1.0.0-beta.3 → 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 (130) hide show
  1. package/SPEC.md +317 -20
  2. package/bin/ab-dispatch-generation.ts +93 -0
  3. package/docs/answering-blocked-builds.md +21 -3
  4. package/docs/architecture.md +166 -7
  5. package/docs/configuration.md +173 -5
  6. package/docs/integration-tree.md +87 -2
  7. package/docs/integration.md +54 -0
  8. package/docs/operator-api.md +58 -5
  9. package/docs/remote-store-protocol.md +4 -1
  10. package/docs/restacking.md +4 -1
  11. package/docs/setup.md +20 -0
  12. package/docs/spec-standard.md +23 -5
  13. package/package.json +3 -3
  14. package/packages/core/src/cli/artifact.ts +5 -4
  15. package/packages/core/src/cli/attention.ts +2 -0
  16. package/packages/core/src/cli/binary-direct.ts +190 -0
  17. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  18. package/packages/core/src/cli/binary.ts +24 -210
  19. package/packages/core/src/cli/build-control.ts +105 -2
  20. package/packages/core/src/cli/context.ts +41 -1
  21. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  22. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  23. package/packages/core/src/cli/dashboard/integration-detail.ts +3 -0
  24. package/packages/core/src/cli/dashboard/model.ts +34 -10
  25. package/packages/core/src/cli/dashboard/render.ts +24 -2
  26. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  27. package/packages/core/src/cli/dispatch-args.ts +53 -0
  28. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  29. package/packages/core/src/cli/dispatch-frontend.ts +52 -5
  30. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  31. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  32. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  33. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  34. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  35. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  36. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  37. package/packages/core/src/cli/dispatch-process.ts +22 -90
  38. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  39. package/packages/core/src/cli/dispatch-repository-feed.ts +5 -1
  40. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  41. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  42. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  43. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  44. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  45. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  46. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  47. package/packages/core/src/cli/dispatch.ts +604 -60
  48. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  49. package/packages/core/src/cli/harvest.ts +28 -11
  50. package/packages/core/src/cli/help.ts +6 -3
  51. package/packages/core/src/cli/installation.ts +5 -3
  52. package/packages/core/src/cli/main-checkout.ts +59 -0
  53. package/packages/core/src/cli/main.ts +15 -45
  54. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  55. package/packages/core/src/cli/repo-state.ts +3 -58
  56. package/packages/core/src/cli/repository-status.ts +67 -3
  57. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  58. package/packages/core/src/cli/status.ts +57 -3
  59. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  60. package/packages/core/src/cli/wait.ts +3 -0
  61. package/packages/core/src/cli/watch.ts +7 -0
  62. package/packages/core/src/config/live.ts +1 -0
  63. package/packages/core/src/config/schema.ts +8 -4
  64. package/packages/core/src/distribution-packaging.ts +116 -0
  65. package/packages/core/src/events/catalog.ts +6 -0
  66. package/packages/core/src/events/payloads.ts +53 -9
  67. package/packages/core/src/events/policy.ts +25 -0
  68. package/packages/core/src/events/repository.ts +184 -4
  69. package/packages/core/src/events/runtime.ts +16 -0
  70. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +2515 -78
  71. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  72. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  73. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  74. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  75. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  76. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  77. package/packages/core/src/kernel/harvest.ts +98 -4
  78. package/packages/core/src/kernel/integration-attention.ts +20 -0
  79. package/packages/core/src/kernel/integration-state.ts +80 -11
  80. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  81. package/packages/core/src/kernel/mixed-version.ts +34 -0
  82. package/packages/core/src/kernel/node-polling.ts +160 -0
  83. package/packages/core/src/kernel/read-facts.ts +40 -5
  84. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  85. package/packages/core/src/kernel/reducer.ts +75 -14
  86. package/packages/core/src/kernel/service-facts.ts +11 -4
  87. package/packages/core/src/operator/presentation.ts +7 -0
  88. package/packages/core/src/operator/query.ts +6 -2
  89. package/packages/core/src/operator/registry.ts +1 -1
  90. package/packages/core/src/plugins/load.ts +4 -1
  91. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  92. package/packages/core/src/ports/forge/contract.ts +29 -0
  93. package/packages/core/src/ports/forge/github.ts +189 -61
  94. package/packages/core/src/ports/forge-failure.ts +1 -0
  95. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  96. package/packages/core/src/ports/runner/session-env.ts +1 -0
  97. package/packages/core/src/ports/types.ts +10 -0
  98. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  99. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  100. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  101. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  102. package/packages/core/src/processes/build-child-exit.ts +5 -26
  103. package/packages/core/src/processes/build-runner.ts +81 -11
  104. package/packages/core/src/processes/dispatcher.ts +254 -23
  105. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  106. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  107. package/packages/core/src/processes/execution-settlement.ts +16 -7
  108. package/packages/core/src/processes/harvest-runner.ts +328 -292
  109. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  110. package/packages/core/src/runtime-identity.ts +22 -3
  111. package/packages/core/src/store/contract.ts +153 -0
  112. package/packages/core/src/store/local/store.ts +197 -72
  113. package/packages/core/src/store/reduced-reads.ts +8 -0
  114. package/packages/core/src/store/reducer-value-shapes.json +5783 -3305
  115. package/packages/core/src/store/remote/client.ts +43 -0
  116. package/packages/core/src/store/repo-state-events.ts +20 -3
  117. package/packages/core/src/store/types.ts +7 -0
  118. package/skills/guide/SKILL.md +231 -23
  119. package/skills/guide/references/integration-tree.md +87 -2
  120. package/skills/guide/references/operator-api.md +53 -4
  121. package/skills/guide/references/plugin-authoring.md +45 -4
  122. package/skills/guide/references/remote-store-protocol.md +4 -1
  123. package/skills/guide/references/restacking.md +4 -1
  124. package/skills/guide/references/setup.md +20 -0
  125. package/skills/guide/references/spec-standard.md +23 -5
  126. package/skills/harvest/SKILL.md +4 -0
  127. package/skills/harvest-review/SKILL.md +4 -0
  128. package/skills/operate/SKILL.md +78 -8
  129. package/skills/spec/SKILL.md +19 -1
  130. package/skills/tickets/SKILL.md +19 -0
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
1
2
  import { isForgeFailure, type ForgeRequestObserver } from '../forge-failure'
2
3
  import {
3
4
  forgeRequestContext,
@@ -152,9 +153,18 @@ const restPrState = z
152
153
  auto_merge: z.object({}).passthrough().nullable().optional(),
153
154
  mergeable: z.boolean().nullable(),
154
155
  merge_commit_sha: z.string().min(1).nullable(),
155
- head: z.object({ sha: z.string().min(1) }).optional(),
156
+ head: z
157
+ .object({
158
+ sha: z.string().min(1),
159
+ ref: z.string().optional(),
160
+ repo: z.object({ full_name: z.string() }).nullable().optional(),
161
+ })
162
+ .optional(),
156
163
  })
157
164
  .passthrough()
165
+ .refine((view) => !view.merged || view.merge_commit_sha !== null, {
166
+ message: 'GitHub reports PR merged with no merge_commit_sha',
167
+ })
158
168
 
159
169
  const restNativeAutoMerge = z
160
170
  .object({
@@ -175,6 +185,12 @@ const restAutoMergeView = z
175
185
 
176
186
  const restRepositoryAutoMerge = z.object({ allow_auto_merge: z.boolean() }).passthrough()
177
187
 
188
+ const nodeComparison = z.object({
189
+ base_commit: z.object({ sha: z.string().min(1) }),
190
+ ahead_by: z.number().int().nonnegative(),
191
+ behind_by: z.number().int().nonnegative(),
192
+ })
193
+
178
194
  const restBranchHead = z
179
195
  .object({ commit: z.object({ sha: z.string().min(1) }).passthrough() })
180
196
  .passthrough()
@@ -556,14 +572,15 @@ const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout
556
572
  * single tick cannot absorb. */
557
573
  export const MERGEABILITY_RETRY_DELAYS_MS = [1000, 2000, 4000, 5000, 6000, 6000, 6000]
558
574
 
559
- /** Hard cap on the janitor poll's per-PR ETag cache. One small entry per PR
560
- * ever polled in a dispatcher process lifetime makes hitting this in practice
561
- * implausible; the cap is hygiene, not a load-bearing bound. */
562
- const PR_STATE_CACHE_CAP = 512
575
+ /** Bounded validated HTTP representations; eviction falls back to fresh GETs. */
576
+ const REPRESENTATION_CACHE_CAP = 512
563
577
 
564
578
  export class GitHubForge implements Forge {
565
579
  get rewrite() {
566
- return gitRewrite(this.exec, false)
580
+ return gitRewrite(async (cmd, opts) => {
581
+ if (cmd.includes('push')) this.invalidateReads()
582
+ return this.exec(cmd, opts)
583
+ }, false)
567
584
  }
568
585
  get kernelRewrite() {
569
586
  return gitRewrite(this.kernelExec, false)
@@ -571,6 +588,7 @@ export class GitHubForge implements Forge {
571
588
  /** Credentials exist only in the trusted subprocess environment, never in
572
589
  * argv, repository config, remote URLs, or the resolving agent's environment. */
573
590
  readonly kernelExec: Exec = async (cmd, opts) => {
591
+ if (cmd.includes('push')) this.invalidateReads()
574
592
  const repo = await this.repoCoordinates()
575
593
  if (!repo) throw new Error('kernel Git requires explicit GitHub repository coordinates')
576
594
  const credential = typeof this.token === 'function' ? await this.token() : this.token
@@ -621,17 +639,79 @@ export class GitHubForge implements Forge {
621
639
  private readonly repoRoot?: string
622
640
  private readonly env: Readonly<Record<string, string | undefined>>
623
641
  private coordinates?: RepoCoordinates | null
624
- /** Per-PR ETag cache for the janitor poll, keyed `owner/name#number`.
625
- * Conditional revalidation per GitHub's documented best practices: every
626
- * REST response carries an `ETag`, and re-GETting with `If-None-Match`
627
- * answers 304 Not Modified — which does not count against the primary rate
628
- * limit — whenever the representation is unchanged. The cache lives only
629
- * for this adapter instance (the dispatcher constructs one forge and holds
630
- * it across janitor ticks), so a process restart is cache loss: exactly
631
- * today's first-poll behavior. Capped with oldest-inserted eviction; a miss
632
- * is an ordinary unconditional poll, so eviction is harmless by
633
- * construction. */
634
- private readonly prStateCache = new Map<string, { etag: string; state: PrState }>()
642
+ private readonly representations = new Map<string, { etag: string; value: unknown }>()
643
+ private readonly reads = new AsyncLocalStorage<Map<string, Promise<unknown>>>()
644
+
645
+ private readonly activeScopes = new Set<Map<string, Promise<unknown>>>()
646
+ private readEpoch = 0
647
+
648
+ async withReadScope<T>(work: () => Promise<T>): Promise<T> {
649
+ const scope = new Map<string, Promise<unknown>>()
650
+ this.activeScopes.add(scope)
651
+ try {
652
+ return await this.reads.run(scope, work)
653
+ } finally {
654
+ scope.clear()
655
+ this.activeScopes.delete(scope)
656
+ }
657
+ }
658
+
659
+ private memo<T>(key: string, work: () => Promise<T>): Promise<T> {
660
+ const scope = this.reads.getStore()
661
+ if (!scope || !this.activeScopes.has(scope)) return work()
662
+ const existing = scope.get(key)
663
+ if (existing) return existing as Promise<T>
664
+ const result = Promise.resolve().then(work)
665
+ scope.set(key, result)
666
+ return result
667
+ }
668
+
669
+ private invalidateReads(): void {
670
+ this.readEpoch++
671
+ for (const scope of this.activeScopes) scope.clear()
672
+ this.representations.clear()
673
+ }
674
+
675
+ /** These reads all use GET with the transport's fixed JSON representation
676
+ * headers. The full repository-qualified path (including query, if any)
677
+ * is therefore the exact resource key; raw/file/readiness reads stay separate.
678
+ * Only validated representations receive validators. */
679
+ private async revalidate<T>(schema: z.ZodType<T>, path: string, operation: string): Promise<T> {
680
+ return this.memo(`http:${path}`, () => this.revalidateResource(schema, path, operation))
681
+ }
682
+
683
+ private async revalidateResource<T>(
684
+ schema: z.ZodType<T>,
685
+ path: string,
686
+ operation: string,
687
+ ): Promise<T> {
688
+ const epoch = this.readEpoch
689
+ const cached = this.representations.get(path)
690
+ try {
691
+ const response = await this.request(
692
+ 'GET',
693
+ path,
694
+ cached ? { headers: { 'If-None-Match': cached.etag } } : undefined,
695
+ )
696
+ if (response.status === 304) {
697
+ if (!cached) throw new Error(`unsolicited GitHub 304 for ${operation}`)
698
+ return cached.value as T
699
+ }
700
+ const value = this.parse(schema, response, operation)
701
+ if (epoch !== this.readEpoch) return value
702
+ this.representations.delete(path)
703
+ if (response.headers.etag)
704
+ this.representations.set(path, { etag: response.headers.etag, value })
705
+ while (this.representations.size > REPRESENTATION_CACHE_CAP) {
706
+ this.representations.delete(this.representations.keys().next().value!)
707
+ }
708
+ return value
709
+ } catch (error) {
710
+ if (epoch === this.readEpoch) this.representations.delete(path)
711
+ throw error
712
+ }
713
+ }
714
+
635
715
  /** Bounded waits between mergeability re-queries on the UNKNOWN path. */
636
716
  private readonly mergeabilityRetryDelaysMs: number[]
637
717
 
@@ -667,11 +747,19 @@ export class GitHubForge implements Forge {
667
747
  const transport = opts.transport ?? createGitHubFetchTransport({ token: this.token })
668
748
  this.transport = async (...args) =>
669
749
  guardedForgeRequest(async () => {
670
- for (const observer of this.requestObservers) observer(forgeRequestContext())
750
+ const context = forgeRequestContext()
751
+ let outcome: 'restPrimary' | 'restNotModified' | 'graphql' | undefined
752
+ if (args[1] === 'graphql') outcome = 'graphql'
671
753
  try {
672
- return await transport(...args)
754
+ const response = await transport(...args)
755
+ outcome ??= response.status === 304 ? 'restNotModified' : 'restPrimary'
756
+ return response
673
757
  } catch (error) {
758
+ if (error instanceof GitHubApiError) outcome ??= 'restPrimary'
674
759
  throw classifyGitHubFailure(error, this.now())
760
+ } finally {
761
+ for (const observer of this.requestObservers)
762
+ observer({ ...context, ...(outcome ? { outcome } : {}) })
675
763
  }
676
764
  })
677
765
  if (opts.repository !== undefined && opts.repository !== '') {
@@ -738,6 +826,7 @@ export class GitHubForge implements Forge {
738
826
  path: string,
739
827
  opts?: GitHubRequestOpts,
740
828
  ): Promise<GitHubResponse> {
829
+ if (method !== 'GET' && path !== 'graphql') this.invalidateReads()
741
830
  return this.transport(method, path, opts)
742
831
  }
743
832
 
@@ -767,6 +856,7 @@ export class GitHubForge implements Forge {
767
856
  query: string,
768
857
  variables: Record<string, unknown>,
769
858
  ): Promise<T> {
859
+ if (/^\s*mutation\b/.test(query)) this.invalidateReads()
770
860
  const response = await this.request('POST', 'graphql', { body: { query, variables } })
771
861
  const envelope = z
772
862
  .object({
@@ -806,12 +896,14 @@ export class GitHubForge implements Forge {
806
896
  /** Ordinary phase publication extends history; reconcile uses the separate guarded rewrite capability.
807
897
  * Only ever called from worktree-side terminals and contract fixtures. */
808
898
  async confirmPublication(workspacePath: string, branch: string, sha: string): Promise<boolean> {
899
+ this.invalidateReads()
809
900
  if ((await remoteBranchHead(this.exec, workspacePath, branch)) !== sha) return false
810
901
  await refreshBranchCache(this.exec, workspacePath, branch, sha)
811
902
  return true
812
903
  }
813
904
 
814
905
  async pushBranch(workspacePath: string, branch: string, sha?: string): Promise<void> {
906
+ this.invalidateReads()
815
907
  await publishBranch(this.exec, workspacePath, branch, sha)
816
908
  }
817
909
 
@@ -888,16 +980,7 @@ export class GitHubForge implements Forge {
888
980
  async getPrState(_workspacePath: string, number: number): Promise<PrState> {
889
981
  const { owner, name } = await this.requireCoordinates()
890
982
  const prPath = `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${number}`
891
- const cacheKey = `${owner}/${name}#${number}`
892
- const cached = this.prStateCache.get(cacheKey)
893
- const response =
894
- cached !== undefined
895
- ? await this.request('GET', prPath, { headers: { 'If-None-Match': cached.etag } })
896
- : await this.request('GET', prPath)
897
- if (response.status === 304 && cached !== undefined) {
898
- return cached.state
899
- }
900
- const view = this.parse(restPrState, response, `PR #${number} poll`)
983
+ const view = await this.prView(number, prPath)
901
984
  let state: PrState
902
985
  if (view.merged) {
903
986
  // §15.7 [D1]: pr.merged records the squash commit as the landing
@@ -923,22 +1006,61 @@ export class GitHubForge implements Forge {
923
1006
  }
924
1007
  }
925
1008
  }
926
- const etag = response.headers.etag
927
- if (etag === undefined || etag === '') {
928
- // No revalidation token on this 200: drop any stale entry so a future
929
- // poll can never replay it against a changed representation.
930
- this.prStateCache.delete(cacheKey)
1009
+ return state
1010
+ }
1011
+
1012
+ private prView(number: number, path: string) {
1013
+ return this.memo(`pr:${number}`, () => this.revalidate(restPrState, path, `PR #${number} poll`))
1014
+ }
1015
+
1016
+ async primeNodeReads(input: {
1017
+ workspacePath: string
1018
+ parent: string
1019
+ head: string
1020
+ prNumber?: number
1021
+ }): Promise<void> {
1022
+ const scope = this.reads.getStore()
1023
+ if (!scope || !this.activeScopes.has(scope)) return
1024
+ const epoch = this.readEpoch
1025
+ const { owner, name } = await this.requireCoordinates()
1026
+ const root = `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
1027
+ let headSha: string
1028
+ let parentSha: string
1029
+ let ahead: number
1030
+ if (input.prNumber !== undefined) {
1031
+ const view = await this.prView(input.prNumber, `${root}/pulls/${input.prNumber}`)
1032
+ if (view.merged || view.state === 'closed') return
1033
+ if (
1034
+ view.head?.ref !== input.head ||
1035
+ view.head.repo?.full_name.toLowerCase() !== `${owner}/${name}`.toLowerCase()
1036
+ )
1037
+ return
1038
+ headSha = view.head.sha
1039
+ const comparison = await this.revalidate(
1040
+ nodeComparison,
1041
+ `${root}/compare/${encodeURIComponent(input.parent)}...${encodeURIComponent(headSha)}`,
1042
+ 'node observation',
1043
+ )
1044
+ parentSha = comparison.base_commit.sha
1045
+ ahead = comparison.ahead_by
931
1046
  } else {
932
- this.prStateCache.set(cacheKey, { etag, state })
933
- // Hard capacity cap with oldest-inserted eviction (JS Map iteration
934
- // order). The just-inserted entry is newest, so it survives.
935
- while (this.prStateCache.size > PR_STATE_CACHE_CAP) {
936
- const oldest = this.prStateCache.keys().next()
937
- if (oldest.done === true) break
938
- this.prStateCache.delete(oldest.value)
939
- }
1047
+ parentSha = await this.remoteBranchSha(input.parent)
1048
+ const comparison = await this.revalidate(
1049
+ nodeComparison,
1050
+ `${root}/compare/${encodeURIComponent(input.head)}...${encodeURIComponent(parentSha)}`,
1051
+ 'node observation',
1052
+ )
1053
+ headSha = comparison.base_commit.sha
1054
+ ahead = comparison.behind_by
940
1055
  }
941
- return state
1056
+ if (epoch !== this.readEpoch) return this.primeNodeReads(input)
1057
+ if (!this.activeScopes.has(scope)) return
1058
+ scope.set(`branch:${input.parent}`, Promise.resolve(parentSha))
1059
+ scope.set(`branch:${input.head}`, Promise.resolve(headSha))
1060
+ scope.set(
1061
+ `compare:${input.parent}:${input.head}`,
1062
+ Promise.resolve({ parentSha, headSha, ahead }),
1063
+ )
942
1064
  }
943
1065
 
944
1066
  async mergeLinearStack(
@@ -1089,7 +1211,7 @@ export class GitHubForge implements Forge {
1089
1211
  pr.head.sha !== before.headSha
1090
1212
  )
1091
1213
  throw new Error(`PR #${number} retarget acknowledgement disagrees with requested base/head`)
1092
- this.prStateCache.delete(`${owner}/${name}#${number}`)
1214
+ this.invalidateReads()
1093
1215
  }
1094
1216
 
1095
1217
  async inspectLandingPr(_workspacePath: string, number: number) {
@@ -1143,7 +1265,7 @@ export class GitHubForge implements Forge {
1143
1265
  const { owner, name } = await this.requireCoordinates()
1144
1266
  const repoPath = `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
1145
1267
  try {
1146
- await this.request('GET', `${repoPath}/git/ref/heads/${branch}`)
1268
+ await this.request('GET', `${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`)
1147
1269
  } catch (error) {
1148
1270
  if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
1149
1271
  if (error instanceof GitHubApiError && error.status === 404) return // idempotent
@@ -1739,17 +1861,19 @@ export class GitHubForge implements Forge {
1739
1861
  private async nodeRef(branch: string): Promise<string> {
1740
1862
  if (!isValidGitBranchName(branch)) throw new Error('invalid node branch')
1741
1863
  const { owner, name } = await this.requireCoordinates()
1742
- const result = await this.getJson(
1743
- z.object({ object: z.object({ sha: z.string().min(1) }) }),
1744
- `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/git/ref/heads/${branch}`,
1745
- 'node ref',
1746
- )
1747
- return result.object.sha
1864
+ return this.memo(`branch:${branch}`, async () => {
1865
+ const result = await this.revalidate(
1866
+ z.object({ object: z.object({ sha: z.string().min(1) }) }),
1867
+ `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/git/ref/heads/${encodeURIComponent(branch)}`,
1868
+ 'node ref',
1869
+ )
1870
+ return result.object.sha
1871
+ })
1748
1872
  }
1749
1873
 
1750
1874
  private async compareShas(parentSha: string, headSha: string) {
1751
1875
  const { owner, name } = await this.requireCoordinates()
1752
- return this.getJson(
1876
+ return this.revalidate(
1753
1877
  z.object({
1754
1878
  ahead_by: z.number().int().nonnegative(),
1755
1879
  behind_by: z.number().int().nonnegative(),
@@ -1796,19 +1920,23 @@ export class GitHubForge implements Forge {
1796
1920
  }
1797
1921
 
1798
1922
  async compareBranches(parent: string, head: string) {
1799
- const parentSha = await this.nodeRef(parent)
1800
- const headSha = await this.nodeRef(head)
1801
- return { parentSha, headSha, ahead: (await this.compareShas(parentSha, headSha)).ahead_by }
1923
+ return this.memo(`compare:${parent}:${head}`, async () => {
1924
+ const parentSha = await this.nodeRef(parent)
1925
+ const headSha = await this.nodeRef(head)
1926
+ return { parentSha, headSha, ahead: (await this.compareShas(parentSha, headSha)).ahead_by }
1927
+ })
1802
1928
  }
1803
1929
 
1804
1930
  async remoteBranchSha(branch: string): Promise<string> {
1805
1931
  const { owner, name } = await this.requireCoordinates()
1806
- const branchHead = await this.getJson(
1807
- restBranchHead,
1808
- `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/branches/${branch}`,
1809
- `remote branch ${branch}`,
1810
- )
1811
- return branchHead.commit.sha
1932
+ return this.memo(`branch:${branch}`, async () => {
1933
+ const branchHead = await this.revalidate(
1934
+ restBranchHead,
1935
+ `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/branches/${encodeURIComponent(branch)}`,
1936
+ `remote branch ${branch}`,
1937
+ )
1938
+ return branchHead.commit.sha
1939
+ })
1812
1940
  }
1813
1941
 
1814
1942
  /** Raw file bytes from the repository. Ref omitted → the repository's
@@ -34,6 +34,7 @@ export function isForgeFailure(error: unknown): error is ForgeFailure {
34
34
  }
35
35
 
36
36
  export interface ForgeRequestContext {
37
+ outcome?: 'restPrimary' | 'restNotModified' | 'graphql'
37
38
  build?: string
38
39
  }
39
40
  /** Called once for each actual provider request, including failed requests. */
@@ -1,6 +1,9 @@
1
1
  import { z } from 'zod'
2
2
  /** Bounded operational evidence, never lifecycle authority. */
3
3
  export const forgeRequestCountsSchema = z.strictObject({
4
+ restPrimary: z.number().int().nonnegative().optional(),
5
+ restNotModified: z.number().int().nonnegative().optional(),
6
+ graphql: z.number().int().nonnegative().optional(),
4
7
  total: z.number().int().nonnegative(),
5
8
  unattributed: z.number().int().nonnegative(),
6
9
  builds: z
@@ -25,6 +25,7 @@ export function sessionEnv(
25
25
  delete env.AB_TICKET_URL
26
26
  delete env.AB_TOKEN
27
27
  Object.assign(env, scoped)
28
+ delete env.AB_DISPATCH_GENERATION
28
29
 
29
30
  const inheritedPath = env.PATH
30
31
  const inheritedEntries =
@@ -526,6 +526,16 @@ export type {
526
526
  } from './forge-failure'
527
527
 
528
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
+
529
539
  /** Optional API 1.8 capability. Absence means unavailable counts. */
530
540
  observeRequests?(observer: import('./forge-failure').ForgeRequestObserver): () => void
531
541
 
@@ -1,6 +1,11 @@
1
+ import { cachedRuntime, resolveCachedGuestArchive } from '../../cli/dispatch-runtime-cache'
1
2
  /**
2
3
  * The Autobuild distribution archive installed into guests.
3
4
  *
5
+ * Source and registry caches retain distinct guest archive provenance. Registry
6
+ * caches lazily install the version-validated GitHub release asset; source caches use
7
+ * their exact packed code. Outside the cache, the sources below apply.
8
+ *
4
9
  * Two sources, one archive layout (`autobuild-<version>.tgz`, the same bytes
5
10
  * `bun pm pack` produces and the guest bootstrap extracts):
6
11
  *
@@ -35,25 +40,21 @@
35
40
  * bytes installed and resolution never adds a second pack per tick.
36
41
  */
37
42
  import { createHash } from 'node:crypto'
38
- import { access, cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
39
- import { tmpdir } from 'node:os'
40
- import { dirname, join, resolve } from 'node:path'
43
+ import { access, mkdir, readdir, readFile, writeFile } from 'node:fs/promises'
44
+ import { join, resolve } from 'node:path'
41
45
  import { distributionRoot, distributionPath } from '../../distribution'
42
46
  import { REMOTE_STORE_PROTOCOL_VERSION } from '../../store/remote/version'
43
47
  import { registryBaseUrl, registryVersionUrl } from '../../registry'
44
- import { parseRepoCoordinates } from '../forge/github'
45
- import {
46
- createGitHubFetchTransport,
47
- GitHubApiError,
48
- githubTokenFromEnv,
49
- type GitHubRequest,
50
- } from '../forge/github-transport'
48
+ import type { GitHubRequest } from '../forge/github-transport'
49
+ import { fetchDistributionReleaseAsset, distributionAssetName } from './distribution-release'
50
+ export {
51
+ fetchDistributionReleaseAsset,
52
+ distributionAssetName,
53
+ CANONICAL_REPOSITORY_URL,
54
+ } from './distribution-release'
55
+ import { packageDistribution } from '../../distribution-packaging'
51
56
  import { spawnExec } from './git-worktree'
52
57
 
53
- /** The canonical repository the release assets are published to. Shared with
54
- * `tools/release.ts`, which uploads them. */
55
- export const CANONICAL_REPOSITORY_URL = 'https://github.com/defrex/autobuild'
56
-
57
58
  /** The shipped manifest `readDistributionPackage()` reads. A bundled
58
59
  * deployment must carry this exact file into its function bundle; the hosted
59
60
  * service's post-build trace step appends it to the dispatch route's trace. */
@@ -157,11 +158,6 @@ export async function readDistributionIdentityStamp(): Promise<string> {
157
158
  return distributionStampFor(archive)
158
159
  }
159
160
 
160
- /** The release asset a version's distribution ships under. */
161
- export function distributionAssetName(version: string): string {
162
- return `autobuild-${version}.tgz`
163
- }
164
-
165
161
  /** Minimal fetch seam for registry reads: the global `fetch` in production. */
166
162
  export type RegistryFetch = (
167
163
  url: string,
@@ -234,54 +230,6 @@ async function fetchPublishedDistribution(
234
230
  }
235
231
  }
236
232
 
237
- /** Fetch the published `autobuild-<version>.tgz` release asset for the
238
- * running version. Uses the dispatcher's GitHub credentials when present
239
- * (required for a private canonical repository). */
240
- export async function fetchDistributionReleaseAsset(
241
- version: string,
242
- env: Readonly<Record<string, string | undefined>> = process.env,
243
- transport: GitHubRequest = createGitHubFetchTransport({
244
- token: githubTokenFromEnv(env),
245
- }),
246
- ): Promise<Uint8Array> {
247
- const coordinates = parseRepoCoordinates(CANONICAL_REPOSITORY_URL)
248
- if (coordinates === null) {
249
- throw new Error(`the canonical repository URL is not parseable: ${CANONICAL_REPOSITORY_URL}`)
250
- }
251
- const repo = `repos/${encodeURIComponent(coordinates.owner)}/${encodeURIComponent(coordinates.name)}`
252
- const tag = `v${version}`
253
- const release = await transport('GET', `${repo}/releases/tags/${tag}`).catch((error: unknown) => {
254
- if (error instanceof GitHubApiError && error.status === 404) {
255
- throw new Error(
256
- `Autobuild release ${tag} has no published GitHub release; origin-mode dispatch ` +
257
- 'installs the guest distribution from the release asset autobuild-' +
258
- `${version}.tgz — cut a release with tools/release.ts first`,
259
- { cause: error },
260
- )
261
- }
262
- throw error
263
- })
264
- const assets = (
265
- release.json as { assets?: { name?: unknown; browser_download_url?: unknown }[] } | undefined
266
- )?.assets
267
- const assetName = distributionAssetName(version)
268
- const asset = (assets ?? []).find((candidate) => candidate.name === assetName)
269
- if (asset === undefined || typeof asset.browser_download_url !== 'string') {
270
- throw new Error(
271
- `Autobuild release ${tag} does not carry the ${assetName} distribution asset; ` +
272
- 'origin-mode dispatch cannot install a guest distribution without it — ' +
273
- 'cut a release with tools/release.ts first',
274
- )
275
- }
276
- const download = await transport('GET', asset.browser_download_url, {
277
- headers: { Accept: 'application/octet-stream' },
278
- })
279
- if (download.bytes === undefined) {
280
- throw new Error(`the ${assetName} release asset downloaded no bytes`)
281
- }
282
- return download.bytes
283
- }
284
-
285
233
  /** Directory, relative to a distribution root, where a deployment ships the
286
234
  * archive it packed at build time (`ab-hosted-dispatcher pack-distribution`). A
287
235
  * bundled deployment — the hosted service on Vercel — has neither `bun` nor a
@@ -293,89 +241,8 @@ export const PREBUILT_DISTRIBUTION_DIR = '.autobuild-dist'
293
241
  * that place it somewhere other than `PREBUILT_DISTRIBUTION_DIR`. */
294
242
  export const DISTRIBUTION_ARCHIVE_ENV = 'AB_DISTRIBUTION_ARCHIVE'
295
243
 
296
- async function execOrThrow(cmd: string[], cwd: string): Promise<string> {
297
- const result = await spawnExec(cmd, { cwd })
298
- if (result.exitCode !== 0) {
299
- throw new Error(
300
- `${cmd.join(' ')} exited ${result.exitCode}: ${result.stderr.trim() || result.stdout.trim()}`,
301
- )
302
- }
303
- return result.stdout.trim()
304
- }
305
-
306
- /** Manifest fields that name repo-local packaging state and must never reach
307
- * the packed distribution manifest. `patchedDependencies` entries are resolved
308
- * by bun against the consuming project's root, and bun 1.4.0 panics
309
- * (`Option::unwrap`, exit 134) when a consumed manifest declares a patch for a
310
- * package the consumer tree contains — so a packed manifest carrying the
311
- * repo's better-auth patch declaration breaks any consumer that installs
312
- * autobuild next to better-auth. The packed artifact ships no patched
313
- * package, so the declaration is stripped from the packed manifest while the
314
- * repo manifest keeps it for workspace installs. The strip is an enforced
315
- * invariant, not a local detail: the `patchedDependencies` rule in
316
- * `tools/workspace-manifest-check.ts` rejects a root manifest whose packed
317
- * dependency set contains a patched package, and the negative control in
318
- * `packages/core/src/plugin-sdk/package.test.ts` (the packed-distribution
319
- * better-auth canary) pins the consumed-manifest failure shape this strip
320
- * guards, so removing the field from this list fails the suite loudly.
321
- *
322
- * `devDependencies` is stripped for two reasons. First, the workspace link
323
- * specifiers it may carry (for example the root's
324
- * `@defrex/autobuild-postgres-store: workspace:*`) cannot be resolved in the
325
- * staging tree — it stages only the manifest's `files` set, with no
326
- * `bun.lock`, no `node_modules`, and no workspace packages — so `bun pm pack`
327
- * fails there with "Failed to resolve workspace version". Second, the guest
328
- * installs the distribution with `bun install --production --ignore-scripts`,
329
- * which ignores devDependencies entirely; the packed artifact ships no
330
- * dev-only tooling, so the declaration is dead weight in the packed manifest
331
- * while the repo manifest keeps it for workspace installs. */
332
- const packedManifestOmittedFields = ['patchedDependencies', 'devDependencies'] as const
333
-
334
244
  export async function packageAutobuildDistribution(): Promise<Uint8Array> {
335
- const staging = await mkdtemp(join(tmpdir(), 'autobuild-pack-staging-'))
336
- const destination = await mkdtemp(join(tmpdir(), 'autobuild-pack-'))
337
- try {
338
- // Pack from a staging copy of the repo's `files` set rather than the repo
339
- // root: the packed manifest must differ from the repo manifest (above), and
340
- // rewriting the repo manifest in place would leave a window where tracked
341
- // files are dirty.
342
- const manifestPath = join(distributionRoot(), 'package.json')
343
- const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as Record<string, unknown>
344
- const files = manifest.files
345
- if (!Array.isArray(files) || files.some((entry) => typeof entry !== 'string')) {
346
- throw new Error(
347
- 'Autobuild packaging requires the root package.json to list its files as an array of paths',
348
- )
349
- }
350
- for (const entry of files as string[]) {
351
- // npm `files` entries may be negated globs (for example
352
- // `!packages/core/src/**/*.test.ts`, which keeps test files out of the
353
- // published package). Only positive entries name a path to stage: the
354
- // negations stay in the staged manifest and `bun pm pack` applies them,
355
- // so the packed set still excludes those paths.
356
- if (entry.startsWith('!')) continue
357
- const target = join(staging, entry)
358
- await mkdir(dirname(target), { recursive: true })
359
- await cp(join(distributionRoot(), entry), target, {
360
- recursive: true,
361
- errorOnExist: true,
362
- force: false,
363
- })
364
- }
365
- for (const field of packedManifestOmittedFields) delete manifest[field]
366
- await writeFile(join(staging, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`)
367
- await execOrThrow(
368
- ['bun', 'pm', 'pack', '--ignore-scripts', '--destination', destination],
369
- staging,
370
- )
371
- const archives = (await readdir(destination)).filter((name) => name.endsWith('.tgz'))
372
- if (archives.length !== 1)
373
- throw new Error('Autobuild packaging did not produce exactly one archive')
374
- return new Uint8Array(await readFile(join(destination, archives[0]!)))
375
- } finally {
376
- await rm(staging, { recursive: true, force: true })
377
- await rm(destination, { recursive: true, force: true })
378
- }
245
+ return packageDistribution(distributionRoot(), (cmd, options) => spawnExec(cmd, options))
379
246
  }
380
247
 
381
248
  /** Pack the running distribution into `<root>/.autobuild-dist/autobuild-<version>.tgz`
@@ -452,6 +319,12 @@ export async function defaultDistributionArchive(
452
319
  hasBun: () => boolean = hasBunExecutable,
453
320
  fetchImpl: RegistryFetch = registryFetch,
454
321
  ): Promise<Uint8Array> {
322
+ const runtime = await cachedRuntime(distributionRoot())
323
+ if (runtime) {
324
+ return resolveCachedGuestArchive(runtime, (version) =>
325
+ fetchDistributionReleaseAsset(version, env, transport),
326
+ )
327
+ }
455
328
  const prebuilt = await findPrebuiltDistributionArchive(env)
456
329
  if (prebuilt !== null) return new Uint8Array(await readFile(prebuilt))
457
330
  if (await fileExists(join(distributionRoot(), '.git'))) {