@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
@@ -1,3 +1,8 @@
1
+ import {
2
+ currentTicketRef,
3
+ readTicketMigrations,
4
+ resolveTicketRef,
5
+ } from '../kernel/ticket-migrations'
1
6
  import { updateTicketTarget } from '../kernel/node-parent'
2
7
  import { projectTicketTree, compatibleTicketSource } from '../ports/tickets/tree'
3
8
  import { readBuildFacts } from '../store/reduced-reads'
@@ -117,31 +122,31 @@ async function matchingBuild(
117
122
  source: TicketSource,
118
123
  configuredSource: string,
119
124
  ): Promise<OperatorTicketBuild | null> {
120
- // The service's database adapter implements the externally named hosted source.
121
- const hosted =
122
- source.name === 'hosted' || (configuredSource === 'hosted' && source.name === 'database')
123
- const candidates = (await store.listBuilds()).filter(
124
- (record) =>
125
- record.repo === repo &&
126
- (record.ticket?.source === source.name || (hosted && record.ticket?.source === 'hosted')),
127
- )
128
- const matches = candidates.filter((record) => record.ticket!.id === id)
129
- // The service database store always projects current ids, even when there is
130
- // no matching build. Only a hosted client over an unprojected legacy store
131
- // needs fallback lookups; failure must not undo a mutation.
132
- if (matches.length === 0 && source.name === 'hosted') {
133
- const identities = new Map<string, string>()
125
+ const candidates = await store.listBuildsForRepo(repo)
126
+ if (!candidates.length) return null
127
+ const migrations = await readTicketMigrations(store, repo)
128
+ const normalized = []
129
+ for (const record of candidates) {
130
+ if (!record.ticket) continue
134
131
  try {
135
- for (const record of candidates) {
136
- const raw = record.ticket!.id
137
- if (!identities.has(raw)) {
138
- const ticket = await source.get(raw)
139
- identities.set(raw, ticket?.ref.source === source.name ? ticket.ref.id : raw)
140
- }
141
- if (identities.get(raw) === id) matches.push(record)
142
- }
132
+ const ref = resolveTicketRef(
133
+ migrations,
134
+ record.ticket,
135
+ source.name === 'database' && configuredSource === 'hosted' ? 'hosted' : source.name,
136
+ record.slug,
137
+ )
138
+ normalized.push({ record, ref })
139
+ } catch {
140
+ /* unrelated historical source has no current ticket association */
141
+ }
142
+ }
143
+ const matches = normalized.filter(({ ref }) => ref.id === id).map(({ record }) => record)
144
+ if (!matches.length && source.name === 'hosted') {
145
+ try {
146
+ for (const { record, ref } of normalized)
147
+ if ((await source.get(ref.id))?.ref.id === id) matches.push(record)
143
148
  } catch {
144
- // Build association is optional presentation; keep the successful ticket result.
149
+ /* optional alias association must not undo a successful mutation */
145
150
  }
146
151
  }
147
152
  const projected = await Promise.all(
@@ -273,9 +278,8 @@ export async function prepareOperatorTicketAssets(opts: {
273
278
  throw new Error('ticket operator backend is not configured')
274
279
  }
275
280
  const { context, source } = await openOperatorTickets({ ...opts, backend: opts.backend })
276
- if (context.tickets.source !== opts.ref.source)
277
- throw new Error('build ticket source differs from configured source')
278
- return preparePinnedAssets(source, opts.store, opts.repo, opts.ref.id)
281
+ const ref = await currentTicketRef(opts.store, opts.repo, context.tickets.source, opts.ref)
282
+ return preparePinnedAssets(source, opts.store, opts.repo, ref.id)
279
283
  }
280
284
 
281
285
  export async function listOperatorTicketStates(opts: {
@@ -1,3 +1,4 @@
1
+ import { snapshotPlugin } from './runtime-snapshot'
1
2
  import { existsSync } from 'node:fs'
2
3
  import { dirname, isAbsolute, join, resolve } from 'node:path'
3
4
  import { pathToFileURL } from 'node:url'
@@ -241,7 +242,9 @@ export async function attemptPlugin(
241
242
  const located = { ...initial, resolved, ...(resolvedFrom !== undefined ? { resolvedFrom } : {}) }
242
243
  let namespace: Record<string, unknown>
243
244
  try {
244
- namespace = (await import(importUrl(resolved))) as Record<string, unknown>
245
+ namespace = (await import(
246
+ importUrl(await snapshotPlugin(resolved, resolutionKind === 'repo-path'))
247
+ )) as Record<string, unknown>
245
248
  } catch (error) {
246
249
  return failed(
247
250
  located,
@@ -0,0 +1,128 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { renameSync } from 'node:fs'
3
+ import { mkdir, mkdtemp, realpath, rm, writeFile, readFile, stat, copyFile } from 'node:fs/promises'
4
+ import { existsSync } from 'node:fs'
5
+ import { dirname, join, relative } from 'node:path'
6
+ import { distributionRoot } from '../distribution'
7
+ import {
8
+ cachedRuntime,
9
+ RUNTIME_CONFIG,
10
+ validateCoreConfigs,
11
+ withCacheLock,
12
+ } from '../cli/dispatch-runtime-cache'
13
+ import { claimRuntimeForProcess, pruneRuntimes } from '../cli/dispatch-runtime-use'
14
+ import {
15
+ copyDependencies,
16
+ copySnapshotTree,
17
+ excludedSnapshotNames,
18
+ readManifest,
19
+ scanDependencies,
20
+ standalonePluginManifest,
21
+ treeDigest,
22
+ } from '../cli/dispatch-runtime-dependencies'
23
+
24
+ const loaded = new Map<string, Promise<string>>()
25
+ /** Selection remains repository-first. Only evaluation relocates, giving native
26
+ * ESM and CommonJS one canonical SDK without loader hooks or source rewriting. */
27
+ export async function snapshotPlugin(resolved: string, local: boolean): Promise<string> {
28
+ const core = await cachedRuntime(distributionRoot())
29
+ if (!core) return resolved
30
+ claimRuntimeForProcess(core.root)
31
+ // Short-lived phase CLIs reclaim dead users during a resident generation.
32
+ pruneRuntimes(dirname(dirname(core.root)))
33
+ const key = `${core.root}:${resolved}`
34
+ let pending = loaded.get(key)
35
+ if (!pending) {
36
+ pending = prepare(resolved, local, core.root)
37
+ loaded.set(key, pending)
38
+ pending.catch(() => loaded.delete(key))
39
+ }
40
+ return pending
41
+ }
42
+ async function prepare(selected: string, local: boolean, core: string): Promise<string> {
43
+ selected = await realpath(selected)
44
+ let boundary = dirname(selected)
45
+ while (!existsSync(join(boundary, 'package.json'))) {
46
+ const parent = dirname(boundary)
47
+ if (parent === boundary) {
48
+ boundary = dirname(selected)
49
+ break
50
+ }
51
+ boundary = parent
52
+ }
53
+ // A standalone module has no declared edges; never invent a surrounding
54
+ // monorepo as its package boundary.
55
+ const standalone =
56
+ !existsSync(join(boundary, 'package.json')) ||
57
+ (local && (existsSync(join(boundary, 'autobuild.toml')) || existsSync(join(boundary, '.git'))))
58
+ const hasManifest = !standalone
59
+ const cache = dirname(dirname(core))
60
+ const extensions = join(cache, 'extensions')
61
+ await mkdir(extensions, { recursive: true })
62
+ const stage = await mkdtemp(join(extensions, '.preparing-'))
63
+ try {
64
+ const tree = join(stage, 'distribution')
65
+ const root = join(tree, 'package')
66
+ const files = new Set<string>()
67
+ const manifest = hasManifest
68
+ ? undefined
69
+ : await standalonePluginManifest(selected, boundary, files)
70
+ const fingerprint = async () => {
71
+ if (!manifest) return treeDigest(boundary, excludedSnapshotNames)
72
+ const hash = createHash('sha256')
73
+ const current = new Set<string>()
74
+ await standalonePluginManifest(selected, boundary, current)
75
+ for (const file of [...current].sort()) {
76
+ hash.update(JSON.stringify([relative(boundary, file), (await stat(file)).mode & 0o111]))
77
+ hash.update(await readFile(file))
78
+ }
79
+ return hash.digest('hex')
80
+ }
81
+ const before = await fingerprint()
82
+ const scan = () =>
83
+ scanDependencies(boundary, {
84
+ dev: local && !manifest,
85
+ coreRoot: core,
86
+ ...(manifest ? { manifest } : {}),
87
+ })
88
+ const graph = await scan()
89
+ if (manifest) {
90
+ await mkdir(root, { recursive: true })
91
+ for (const file of files) {
92
+ const target = join(root, relative(boundary, file))
93
+ await mkdir(dirname(target), { recursive: true })
94
+ await copyFile(file, target)
95
+ }
96
+ } else await copySnapshotTree(boundary, root)
97
+ await writeFile(join(tree, 'tsconfig.json'), RUNTIME_CONFIG)
98
+ await writeFile(join(root, 'tsconfig.json'), RUNTIME_CONFIG)
99
+ if (manifest) await writeFile(join(root, 'package.json'), JSON.stringify(manifest))
100
+ if (hasManifest) {
101
+ const manifest = await readManifest(root)
102
+ if (manifest.name === '@defrex/autobuild') {
103
+ manifest.name = 'autobuild-local-plugin-snapshot'
104
+ delete manifest.exports
105
+ await writeFile(join(root, 'package.json'), JSON.stringify(manifest))
106
+ }
107
+ }
108
+ await validateCoreConfigs(root, ['.'])
109
+ await copyDependencies(graph, root, core)
110
+ if (before !== (await fingerprint()) || graph.fingerprint !== (await scan()).fingerprint)
111
+ throw new Error(`plugin changed while preparing snapshot: ${selected}`)
112
+ const digest = await treeDigest(tree, new Set(), core)
113
+ const destination = join(extensions, digest)
114
+ await writeFile(join(stage, 'extension.json'), JSON.stringify({ version: 1, core, digest }))
115
+ claimRuntimeForProcess(core, destination)
116
+ if (
117
+ existsSync(destination) &&
118
+ (await treeDigest(join(destination, 'distribution'), new Set(), core)) !== digest
119
+ )
120
+ throw new Error(`corrupt plugin snapshot: ${destination}`)
121
+ withCacheLock(cache, () => {
122
+ if (!existsSync(destination)) renameSync(stage, destination)
123
+ })
124
+ return join(destination, 'distribution', 'package', relative(boundary, selected))
125
+ } finally {
126
+ await rm(stage, { recursive: true, force: true })
127
+ }
128
+ }
@@ -90,6 +90,35 @@ async function pushAndOpen(harness: ForgeContractHarness): Promise<{
90
90
  */
91
91
  export function describeForgeContract(name: string, factory: ForgeContractFactory): void {
92
92
  describe(`Forge contract: ${name}`, () => {
93
+ test('optional observation scope preserves concurrent reads and fresh mutation readback', async () => {
94
+ await withForge(
95
+ factory,
96
+ undefined,
97
+ async ({ forge, workspacePath, head, base, title, body }) => {
98
+ if (!forge.withReadScope || !forge.closePr) return
99
+ const pr = await forge.openPr({ workspacePath, head, base, title, body })
100
+ await forge.withReadScope(async () => {
101
+ const states = await Promise.all([
102
+ forge.getPrState(workspacePath, pr.number),
103
+ forge.getPrState(workspacePath, pr.number),
104
+ ])
105
+ expect(states[0]).toEqual(states[1])
106
+ await forge.closePr!(workspacePath, pr.number)
107
+ expect((await forge.getPrState(workspacePath, pr.number)).state).toBe('closed')
108
+ })
109
+ await forge.withReadScope(async () => {
110
+ expect((await forge.getPrState(workspacePath, pr.number)).state).toBe('closed')
111
+ })
112
+ await expect(
113
+ forge.withReadScope(async () => {
114
+ throw new Error('scope teardown')
115
+ }),
116
+ ).rejects.toThrow('scope teardown')
117
+ expect((await forge.getPrState(workspacePath, pr.number)).state).toBe('closed')
118
+ },
119
+ )
120
+ })
121
+
93
122
  test('optional request observation registers and disposes without requiring legacy adapters', async () => {
94
123
  await withForge(factory, undefined, async ({ forge }) => {
95
124
  if (!forge.observeRequests) return
@@ -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 =