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

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 (162) hide show
  1. package/README.md +9 -4
  2. package/SPEC.md +295 -62
  3. package/bin/ab-build-runner.ts +10 -8
  4. package/docs/architecture.md +179 -25
  5. package/docs/configuration.md +41 -6
  6. package/docs/hosted-service.md +35 -0
  7. package/docs/integration-tree.md +81 -4
  8. package/docs/landing-policy.md +11 -0
  9. package/docs/migration-1.0.md +9 -0
  10. package/docs/operator-api.md +18 -0
  11. package/docs/remote-store-protocol.md +11 -0
  12. package/docs/restacking.md +42 -7
  13. package/docs/setup.md +25 -0
  14. package/docs/ticket-dependencies.md +6 -45
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/attention.ts +4 -1
  17. package/packages/core/src/cli/binary.ts +17 -1
  18. package/packages/core/src/cli/context.ts +53 -1
  19. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  20. package/packages/core/src/cli/dashboard/detail.ts +45 -1
  21. package/packages/core/src/cli/dashboard/facts.ts +7 -2
  22. package/packages/core/src/cli/dashboard/integration-detail.ts +142 -0
  23. package/packages/core/src/cli/dashboard/integration-row.ts +248 -0
  24. package/packages/core/src/cli/dashboard/landing-display.ts +64 -0
  25. package/packages/core/src/cli/dashboard/model.ts +140 -16
  26. package/packages/core/src/cli/dashboard/poll.ts +40 -4
  27. package/packages/core/src/cli/dashboard/refresh.ts +20 -13
  28. package/packages/core/src/cli/dashboard/render.ts +106 -5
  29. package/packages/core/src/cli/dashboard/transcript.ts +2 -1
  30. package/packages/core/src/cli/dispatch-frontend.ts +22 -12
  31. package/packages/core/src/cli/dispatch.ts +59 -25
  32. package/packages/core/src/cli/help.ts +19 -2
  33. package/packages/core/src/cli/main.ts +37 -0
  34. package/packages/core/src/cli/publication-settlement.ts +49 -5
  35. package/packages/core/src/cli/repository-status.ts +97 -2
  36. package/packages/core/src/cli/status.ts +24 -1
  37. package/packages/core/src/cli/terminals.ts +94 -93
  38. package/packages/core/src/cli/wait.ts +11 -2
  39. package/packages/core/src/cli/watch.ts +12 -0
  40. package/packages/core/src/config/schema.ts +3 -0
  41. package/packages/core/src/events/catalog.ts +38 -0
  42. package/packages/core/src/events/compatibility.ts +183 -0
  43. package/packages/core/src/events/native-session.ts +13 -0
  44. package/packages/core/src/events/payloads.ts +148 -2
  45. package/packages/core/src/events/policy.ts +209 -0
  46. package/packages/core/src/events/repository.ts +48 -0
  47. package/packages/core/src/integration/harness.ts +4 -4
  48. package/packages/core/src/kernel/__snapshots__/{reducer-registry.test.ts.snap → reducer-accumulator-shapes.json} +771 -538
  49. package/packages/core/src/kernel/change-presence.ts +4 -2
  50. package/packages/core/src/kernel/dispatch-capacity.ts +119 -0
  51. package/packages/core/src/kernel/dispatcher-liveness.ts +5 -1
  52. package/packages/core/src/kernel/engine.ts +25 -5
  53. package/packages/core/src/kernel/forge-health.ts +19 -0
  54. package/packages/core/src/kernel/generators/build-log.ts +18 -0
  55. package/packages/core/src/kernel/generators/node-restack-log.ts +1 -1
  56. package/packages/core/src/kernel/generators/repository-journals.ts +10 -0
  57. package/packages/core/src/kernel/guarded-forge.ts +159 -0
  58. package/packages/core/src/kernel/incremental.ts +4 -2
  59. package/packages/core/src/kernel/integration-completeness.ts +61 -0
  60. package/packages/core/src/kernel/integration-landing.ts +5 -4
  61. package/packages/core/src/kernel/janitor-failure.ts +36 -0
  62. package/packages/core/src/kernel/landing-publication.ts +35 -15
  63. package/packages/core/src/kernel/landing-state.ts +7 -0
  64. package/packages/core/src/kernel/leaf-restack-state.ts +1 -1
  65. package/packages/core/src/kernel/log-index.ts +12 -1
  66. package/packages/core/src/kernel/mixed-version.ts +52 -0
  67. package/packages/core/src/kernel/node-landing.ts +14 -11
  68. package/packages/core/src/kernel/node-restack-demand.ts +29 -0
  69. package/packages/core/src/kernel/node-restack-state.ts +46 -16
  70. package/packages/core/src/kernel/node-restack-transaction.ts +151 -8
  71. package/packages/core/src/kernel/node-restack.ts +34 -10
  72. package/packages/core/src/kernel/publication.ts +22 -0
  73. package/packages/core/src/kernel/read-deferrals.ts +111 -0
  74. package/packages/core/src/kernel/read-facts.ts +27 -6
  75. package/packages/core/src/kernel/reconcile-restack.ts +23 -2
  76. package/packages/core/src/kernel/reducer-registry.ts +15 -2
  77. package/packages/core/src/kernel/reducer.ts +196 -10
  78. package/packages/core/src/kernel/repository-attention.ts +38 -1
  79. package/packages/core/src/kernel/terminal-guard.ts +11 -4
  80. package/packages/core/src/operator/annotations.ts +6 -0
  81. package/packages/core/src/operator/index.ts +2 -0
  82. package/packages/core/src/operator/presentation.ts +5 -0
  83. package/packages/core/src/operator/query.ts +45 -11
  84. package/packages/core/src/operator/registry.ts +17 -1
  85. package/packages/core/src/operator/restack.ts +51 -0
  86. package/packages/core/src/plugin-sdk/index.ts +10 -0
  87. package/packages/core/src/plugins/load.ts +3 -4
  88. package/packages/core/src/plugins/manifest.ts +1 -1
  89. package/packages/core/src/ports/forge/contract.ts +23 -0
  90. package/packages/core/src/ports/forge/fake.ts +6 -2
  91. package/packages/core/src/ports/forge/git-rewrite.ts +92 -64
  92. package/packages/core/src/ports/forge/github-transport.ts +45 -2
  93. package/packages/core/src/ports/forge/github.ts +56 -17
  94. package/packages/core/src/ports/forge/local-git.ts +7 -2
  95. package/packages/core/src/ports/forge-failure.ts +40 -0
  96. package/packages/core/src/ports/forge-request-context.ts +35 -0
  97. package/packages/core/src/ports/forge-telemetry.ts +16 -0
  98. package/packages/core/src/ports/runner/claude.ts +136 -9
  99. package/packages/core/src/ports/runner/codex.ts +112 -7
  100. package/packages/core/src/ports/runner/contract.ts +78 -0
  101. package/packages/core/src/ports/runner/fake.ts +59 -1
  102. package/packages/core/src/ports/runner/native-cli-fixture.ts +86 -0
  103. package/packages/core/src/ports/runner/native-process-fixture.ts +38 -0
  104. package/packages/core/src/ports/runner/native-session.ts +110 -0
  105. package/packages/core/src/ports/runner/pi-rpc.ts +7 -1
  106. package/packages/core/src/ports/runner/pi.ts +162 -2
  107. package/packages/core/src/ports/types.ts +53 -5
  108. package/packages/core/src/ports/workspace/git-worktree.ts +45 -51
  109. package/packages/core/src/ports/workspace/vercel-sandbox.ts +28 -12
  110. package/packages/core/src/processes/build-child-exit.ts +50 -2
  111. package/packages/core/src/processes/build-child.ts +15 -7
  112. package/packages/core/src/processes/build-runner.ts +909 -213
  113. package/packages/core/src/processes/dispatcher.ts +652 -334
  114. package/packages/core/src/processes/execution-no-progress.ts +15 -0
  115. package/packages/core/src/processes/pause-execution-fixture.ts +37 -0
  116. package/packages/core/src/processes/phase-failure-budget.ts +2 -1
  117. package/packages/core/src/processes/publication-loss.ts +7 -3
  118. package/packages/core/src/processes/repo-view.ts +53 -6
  119. package/packages/core/src/processes/tick-publication.ts +6 -2
  120. package/packages/core/src/runtime-identity.ts +37 -0
  121. package/packages/core/src/store/adapter.ts +4 -2
  122. package/packages/core/src/store/build-scope.ts +9 -0
  123. package/packages/core/src/store/contract.ts +203 -16
  124. package/packages/core/src/store/digest.ts +20 -2
  125. package/packages/core/src/store/local/schema.ts +6 -0
  126. package/packages/core/src/store/local/store.ts +57 -4
  127. package/packages/core/src/store/memory.ts +83 -2
  128. package/packages/core/src/store/new-build.ts +2 -2
  129. package/packages/core/src/store/phase-session.ts +13 -0
  130. package/packages/core/src/store/reduced-reads.ts +43 -4
  131. package/packages/core/src/store/reducer-value-shapes.json +8238 -5764
  132. package/packages/core/src/store/reducer-value-validation.ts +103 -3
  133. package/packages/core/src/store/reducer-values.ts +21 -6
  134. package/packages/core/src/store/remote/client.ts +146 -20
  135. package/packages/core/src/store/remote/compatibility.ts +6 -0
  136. package/packages/core/src/store/remote/index.ts +2 -0
  137. package/packages/core/src/store/remote/protocol.ts +19 -0
  138. package/packages/core/src/store/remote/version.ts +2 -0
  139. package/packages/core/src/store/repo-state-events.ts +3 -1
  140. package/packages/core/src/store/repo-tick.ts +6 -1
  141. package/packages/core/src/store/session-handle.ts +8 -0
  142. package/packages/core/src/store/snapshots.ts +21 -5
  143. package/packages/core/src/store/types.ts +19 -1
  144. package/packages/core/src/testing/dispatch-read-budget.ts +17 -2
  145. package/packages/core/src/testing/index.ts +7 -0
  146. package/packages/core/src/testing/newer-writer.ts +37 -0
  147. package/packages/core/src/testing/reduced-read-budget.ts +3 -0
  148. package/skills/guide/SKILL.md +144 -27
  149. package/skills/guide/references/integration-tree.md +81 -4
  150. package/skills/guide/references/landing-policy.md +11 -0
  151. package/skills/guide/references/migration-1.0.md +9 -0
  152. package/skills/guide/references/operator-api.md +18 -0
  153. package/skills/guide/references/plugin-authoring.md +55 -7
  154. package/skills/guide/references/remote-store-protocol.md +11 -0
  155. package/skills/guide/references/restacking.md +42 -7
  156. package/skills/guide/references/setup.md +25 -0
  157. package/skills/guide/references/ticket-dependencies.md +6 -45
  158. package/skills/implement/SKILL.md +4 -2
  159. package/skills/operate/SKILL.md +63 -6
  160. package/skills/reconcile/SKILL.md +3 -1
  161. package/skills/spec/SKILL.md +49 -39
  162. package/skills/tickets/SKILL.md +15 -43
@@ -0,0 +1,51 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { humanActor, type Via } from '../events/envelope'
3
+ import { readBuildFacts } from '../store/reduced-reads'
4
+ import type { BuildStore } from '../store/types'
5
+ import { requireRouteBuild, RouteRefusalError } from './requests'
6
+
7
+ /** Request only: ordinary dispatcher safety gates own execution. */
8
+ export async function requestNodeRestack(input: {
9
+ store: BuildStore
10
+ repo: string
11
+ slug: string
12
+ user: string
13
+ via?: Via
14
+ }) {
15
+ const { store, repo, slug } = input
16
+ await requireRouteBuild(store, repo, slug)
17
+ for (;;) {
18
+ const state = (await readBuildFacts(store, slug)).value.state
19
+ const refuse = (error: string): never => {
20
+ throw new RouteRefusalError({ kind: 'conflict', error })
21
+ }
22
+ if (state.kind !== 'node') refuse(`build "${slug}" is not a node; leaves restack automatically`)
23
+ if (
24
+ state.status === 'done' ||
25
+ state.status === 'aborted' ||
26
+ state.prState === 'merged' ||
27
+ state.prState === 'closed'
28
+ )
29
+ refuse(`node "${slug}" is terminal; restack requires an open node`)
30
+ if (!state.nodeOpened || !state.baseBranch) refuse(`node "${slug}" has no open branch yet`)
31
+ const branch = state.baseBranch!
32
+ const parent =
33
+ state.nodeRestack?.observedParent?.sha ??
34
+ state.nodeComparison?.parentSha ??
35
+ state.nodeRestack?.contributionBase ??
36
+ state.nodeOpened!.sha
37
+ const existing = Object.values(state.nodeRestack?.requests ?? {}).find(
38
+ (request) =>
39
+ request.reason === 'operator' && request.branch === branch && request.parent === parent,
40
+ )
41
+ const waiting = state.status === 'paused' || state.status === 'blocked'
42
+ if (existing) return { slug, request: existing, coalesced: true, waiting }
43
+ const request = { id: randomUUID(), reason: 'operator' as const, branch, parent }
44
+ const event = await store.appendIfCurrent(slug, state.lastSeq, {
45
+ actor: humanActor(input.user, input.via),
46
+ type: 'node.restack-requested',
47
+ payload: request,
48
+ })
49
+ if (event) return { slug, request, coalesced: false, waiting }
50
+ }
51
+ }
@@ -48,8 +48,10 @@ export {
48
48
  CONTRACT_RETRYABLE_FAILURE,
49
49
  CONTRACT_SKILL,
50
50
  describeAgentRunnerContract,
51
+ describeNativeResumeContract,
51
52
  } from '../ports/runner/contract'
52
53
  export type {
54
+ NativeResumeContractFixture,
53
55
  AgentRunnerContractFactory,
54
56
  AgentRunnerContractHarness,
55
57
  AgentRunnerContractOneShotHarness,
@@ -159,6 +161,12 @@ export {
159
161
  checkTicketRevision,
160
162
  } from '../ports/tickets/revision'
161
163
  export { FakeWorkspaceProvider } from '../ports/workspace/fake'
164
+ export { ForgeFailure, isForgeFailure } from '../ports/forge-failure'
165
+ export type {
166
+ ForgeFailureDetails,
167
+ ForgeRequestContext,
168
+ ForgeRequestObserver,
169
+ } from '../ports/forge-failure'
162
170
  export { FakeForge } from '../ports/forge/fake'
163
171
  // ScriptContext + defaultTurnResult are the scripted fake's own API: the
164
172
  // script callback's context type and its default turn result (needed by the
@@ -242,3 +250,5 @@ export type {
242
250
  ReducerValueStorage,
243
251
  ValueCacheRow,
244
252
  } from '../store/reducer-values'
253
+
254
+ export { resumeAgent } from '../ports/runner/native-session'
@@ -95,10 +95,9 @@ export interface PluginDiagnosis {
95
95
  export interface PluginLoadOptions {
96
96
  /** Root whose installed dependencies satisfy bare package specifiers first. */
97
97
  packageRoot?: string
98
- /** Autobuild installation root tried after `packageRoot`, so an extension
99
- * installed next to the CLI (`bun add -g @defrex/autobuild-<extension>`)
100
- * loads without being added to the repository. Defaults to the running
101
- * distribution's root. */
98
+ /** Autobuild installation root tried as a fallback after `packageRoot`.
99
+ * Extensions normally live in the repository's development dependencies.
100
+ * Defaults to the running distribution's root. */
102
101
  installationRoot?: string
103
102
  /** Guest context (AUT-517): a package-kind specifier that cannot be
104
103
  * resolved from either candidate is skipped with a notice instead of
@@ -15,7 +15,7 @@ import type {
15
15
  } from '../ports/workspace/provider-capabilities'
16
16
 
17
17
  /** Version of the in-process plugin contract exposed by `@defrex/autobuild/plugin-sdk`. */
18
- export const PLUGIN_API_VERSION = '1.7.0' as const
18
+ export const PLUGIN_API_VERSION = '1.8.0' as const
19
19
 
20
20
  /** Context supplied when a registered adapter or contract fixture is selected. */
21
21
  export interface PluginFactoryContext<Config = Record<string, unknown>> {
@@ -90,6 +90,17 @@ 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 request observation registers and disposes without requiring legacy adapters', async () => {
94
+ await withForge(factory, undefined, async ({ forge }) => {
95
+ if (!forge.observeRequests) return
96
+ const stop = forge.observeRequests((context) => {
97
+ expect(context.build === undefined || typeof context.build === 'string').toBe(true)
98
+ })
99
+ expect(typeof stop).toBe('function')
100
+ stop()
101
+ })
102
+ })
103
+
93
104
  test('optional node refs open empty without a PR and retries preserve their head', async () => {
94
105
  await withForge(factory, undefined, async (h) => {
95
106
  const forge = h.forge
@@ -168,6 +179,18 @@ export function describeForgeContract(name: string, factory: ForgeContractFactor
168
179
  expect(pr.number).toBeGreaterThan(0)
169
180
  expect(pr.url.trim()).not.toBe('')
170
181
  expect(pr.headSha).toBe(remoteHead)
182
+ expect(harness.forge.confirmPublication).toBeDefined()
183
+ expect(
184
+ await harness.forge.confirmPublication!(harness.workspacePath, harness.head, remoteHead),
185
+ ).toBe(true)
186
+ expect(
187
+ await harness.forge.confirmPublication!(
188
+ harness.workspacePath,
189
+ harness.head,
190
+ '0'.repeat(40),
191
+ ),
192
+ ).toBe(false)
193
+ expect(await harness.controls.remoteHead(harness.head)).toBe(remoteHead)
171
194
 
172
195
  const retry = await harness.forge.openPr({
173
196
  workspacePath: harness.workspacePath,
@@ -464,12 +464,16 @@ export class FakeForge implements Forge {
464
464
  return content
465
465
  }
466
466
 
467
- async pushBranch(workspacePath: string, branch: string): Promise<void> {
467
+ async confirmPublication(_workspacePath: string, branch: string, sha: string): Promise<boolean> {
468
+ return this.remoteBranches.get(branch) === sha
469
+ }
470
+
471
+ async pushBranch(workspacePath: string, branch: string, sha?: string): Promise<void> {
468
472
  this.pushes.push({ workspacePath, branch })
469
473
  this.publishedBranches.add(branch)
470
474
  this.remoteBranches.set(
471
475
  branch,
472
- typeof this.headSha === 'string' ? this.headSha : this.headSha(this.nextNumber),
476
+ sha ?? (typeof this.headSha === 'string' ? this.headSha : this.headSha(this.nextNumber)),
473
477
  )
474
478
  }
475
479
 
@@ -31,25 +31,31 @@ export function gitRewrite(exec: Exec, local: boolean): ForgeRewrite {
31
31
  )
32
32
  if (local && result.exitCode === 1) return null
33
33
  if (result.exitCode !== 0) throw new Error(`cannot read ${ref}: ${result.stderr}`)
34
- const sha = result.stdout.trim().split(/\s+/)[0]
35
- if (!sha) return null
36
- object(sha)
37
- return sha
34
+ if (local) {
35
+ const sha = result.stdout.trim()
36
+ object(sha)
37
+ return sha
38
+ }
39
+ return parseRemoteHead(result.stdout, ref)
38
40
  }
39
41
  return {
40
42
  async fastForward(input) {
41
43
  object(input.expected)
42
44
  object(input.sha)
43
45
  if (!isValidGitBranchName(input.branch)) throw new Error('invalid fast-forward destination')
46
+ const ref = `refs/heads/${input.branch}`
47
+ const actual = await read(input.workspacePath, ref)
48
+ if (actual === input.sha) {
49
+ if (!local) await refreshBranchCache(exec, input.workspacePath, input.branch, input.sha)
50
+ return { kind: 'published' }
51
+ }
52
+ if (actual !== input.expected) return { kind: 'lease-mismatch', actual }
44
53
  const ancestry = await git(
45
54
  input.workspacePath,
46
55
  ['merge-base', '--is-ancestor', input.expected, input.sha],
47
56
  true,
48
57
  )
49
58
  if (ancestry.exitCode !== 0) throw new Error('publication is not a fast-forward')
50
- const ref = `refs/heads/${input.branch}`
51
- const actual = await read(input.workspacePath, ref)
52
- if (actual !== input.expected) return { kind: 'lease-mismatch', actual }
53
59
  const result = await git(
54
60
  input.workspacePath,
55
61
  local
@@ -63,9 +69,16 @@ export function gitRewrite(exec: Exec, local: boolean): ForgeRewrite {
63
69
  ],
64
70
  true,
65
71
  )
66
- if (result.exitCode !== 0)
67
- return { kind: 'lease-mismatch', actual: await read(input.workspacePath, ref) }
68
- return { kind: 'published' }
72
+ const after = await read(input.workspacePath, ref)
73
+ if (after === input.sha) {
74
+ if (!local) await refreshBranchCache(exec, input.workspacePath, input.branch, input.sha)
75
+ return { kind: 'published' }
76
+ }
77
+ return {
78
+ kind: 'lease-mismatch',
79
+ actual: after,
80
+ ...(result.exitCode === 0 ? { rewritten: true } : {}),
81
+ }
69
82
  },
70
83
  async snapshot(input) {
71
84
  const ref = branchRef(input.branch)
@@ -138,18 +151,7 @@ export function gitRewrite(exec: Exec, local: boolean): ForgeRewrite {
138
151
  const actual = await read(input.workspacePath, ref)
139
152
  async function acknowledge(): Promise<RewriteResult> {
140
153
  if (!local) {
141
- const localHead = await git(
142
- input.workspacePath,
143
- ['rev-parse', '--verify', '--quiet', ref],
144
- true,
145
- )
146
- if (localHead.exitCode === 0 && localHead.stdout.trim() !== input.sha)
147
- await git(input.workspacePath, [
148
- 'update-ref',
149
- ref,
150
- input.sha,
151
- input.localExpected ?? input.expected,
152
- ])
154
+ await refreshBranchCache(exec, input.workspacePath, input.branch, input.sha)
153
155
  }
154
156
  // Replay stays detached until the guarded branch update is confirmed.
155
157
  // Reattach only its exact workspace result; explicit-source callers may
@@ -160,48 +162,6 @@ export function gitRewrite(exec: Exec, local: boolean): ForgeRewrite {
160
162
  return { kind: 'published' }
161
163
  }
162
164
  async function mismatch(observed: string | null): Promise<RewriteResult> {
163
- // Recover the effect-before-receipt window from immutable intent inputs
164
- // and branch ancestry. The candidate must be newly introduced, not an
165
- // ancestor already present in the expected old history.
166
- if (
167
- observed !== null &&
168
- input.sha !== input.expected &&
169
- (await git(input.workspacePath, ['cat-file', '-e', `${input.sha}^{commit}`], true))
170
- .exitCode === 0 &&
171
- (await git(input.workspacePath, ['cat-file', '-e', `${input.expected}^{commit}`], true))
172
- .exitCode === 0
173
- ) {
174
- if (
175
- !local &&
176
- (await git(input.workspacePath, ['cat-file', '-e', `${observed}^{commit}`], true))
177
- .exitCode !== 0
178
- ) {
179
- const fetchedRef = `refs/autobuild/reconcile/${input.branch.replace(/^(?:ab|ab-node)\//, '')}/rewrite-observed`
180
- await git(input.workspacePath, [
181
- 'fetch',
182
- '--no-tags',
183
- '--no-write-fetch-head',
184
- 'origin',
185
- `+${ref}:${fetchedRef}`,
186
- ])
187
- observed = (
188
- await git(input.workspacePath, ['rev-parse', '--verify', `${fetchedRef}^{commit}`])
189
- ).stdout.trim()
190
- object(observed)
191
- }
192
- const introduced = await git(
193
- input.workspacePath,
194
- ['merge-base', '--is-ancestor', input.sha, input.expected],
195
- true,
196
- )
197
- const retained = await git(
198
- input.workspacePath,
199
- ['merge-base', '--is-ancestor', input.sha, observed],
200
- true,
201
- )
202
- if (introduced.exitCode === 1 && retained.exitCode === 0)
203
- return { kind: 'lease-mismatch', actual: observed, rewritten: true }
204
- }
205
165
  return { kind: 'lease-mismatch', actual: observed }
206
166
  }
207
167
  if (actual === input.sha) return acknowledge()
@@ -230,3 +190,71 @@ export function gitRewrite(exec: Exec, local: boolean): ForgeRewrite {
230
190
  },
231
191
  }
232
192
  }
193
+
194
+ /** A successful transport read is either an exact advertised ref or absence. */
195
+ export function parseRemoteHead(stdout: string, ref: string): string | null {
196
+ const lines = stdout.trim() === '' ? [] : stdout.trim().split('\n')
197
+ if (lines.length === 0) return null
198
+ if (lines.length !== 1) throw new Error(`ambiguous remote head for ${ref}`)
199
+ const fields = lines[0]!.split(/\s+/)
200
+ if (fields.length !== 2 || fields[1] !== ref || !oid.test(fields[0]!))
201
+ throw new Error(`invalid remote head for ${ref}`)
202
+ return fields[0]!
203
+ }
204
+
205
+ export async function remoteBranchHead(
206
+ exec: Exec,
207
+ cwd: string,
208
+ branch: string,
209
+ ): Promise<string | null> {
210
+ if (!isValidGitBranchName(branch)) throw new Error('invalid publication branch')
211
+ const ref = `refs/heads/${branch}`
212
+ const result = await exec(['git', 'ls-remote', '--refs', 'origin', ref], { cwd })
213
+ if (result.exitCode !== 0) throw new Error(`cannot read ${ref}: ${result.stderr}`)
214
+ return parseRemoteHead(result.stdout, ref)
215
+ }
216
+
217
+ /** Confirmed remote-backed refs are caches; never touch checkout contents. */
218
+ export async function refreshBranchCache(
219
+ exec: Exec,
220
+ cwd: string,
221
+ branch: string,
222
+ sha: string,
223
+ ): Promise<void> {
224
+ object(sha)
225
+ if (!isValidGitBranchName(branch)) throw new Error('invalid publication branch')
226
+ const run = async (args: string[]) => {
227
+ const result = await exec(['git', ...args], { cwd })
228
+ if (result.exitCode !== 0)
229
+ throw new Error(`publication cache ${args.join(' ')} failed: ${result.stderr}`)
230
+ }
231
+ if ((await exec(['git', 'cat-file', '-e', `${sha}^{commit}`], { cwd })).exitCode !== 0)
232
+ await run([
233
+ 'fetch',
234
+ '--no-tags',
235
+ '--no-write-fetch-head',
236
+ '--refmap=',
237
+ 'origin',
238
+ `refs/heads/${branch}`,
239
+ ])
240
+ await run(['update-ref', `refs/heads/${branch}`, sha])
241
+ }
242
+
243
+ /** Ordinary publication is fast-forward only, with exact frozen input and readback. */
244
+ export async function publishBranch(
245
+ exec: Exec,
246
+ cwd: string,
247
+ branch: string,
248
+ intended?: string,
249
+ ): Promise<void> {
250
+ const sha =
251
+ intended ??
252
+ (await exec(['git', 'rev-parse', '--verify', 'HEAD^{commit}'], { cwd })).stdout.trim()
253
+ object(sha)
254
+ if ((await remoteBranchHead(exec, cwd, branch)) !== sha) {
255
+ const result = await exec(['git', 'push', 'origin', `${sha}:refs/heads/${branch}`], { cwd })
256
+ if ((await remoteBranchHead(exec, cwd, branch)) !== sha)
257
+ throw new Error(`publication did not confirm ${sha}: ${result.stderr}`)
258
+ }
259
+ await refreshBranchCache(exec, cwd, branch, sha)
260
+ }
@@ -7,6 +7,7 @@
7
7
  * shelling `gh`.
8
8
  */
9
9
  import { z } from 'zod'
10
+ import { ForgeFailure, isForgeFailure } from '../forge-failure'
10
11
  import { spawnExec } from '../workspace/git-worktree'
11
12
 
12
13
  export interface GitHubRequestOpts {
@@ -370,12 +371,31 @@ export function githubTokenSource(
370
371
 
371
372
  /** Documented primary and secondary limits; permission failures are ordinary errors. */
372
373
  export function githubRateLimitUntil(error: unknown, now: number): string | undefined {
374
+ if (isForgeFailure(error) && error.details.kind === 'rate-limited') return error.details.resetAt
373
375
  if (!(error instanceof GitHubApiError)) return undefined
376
+ const limitedEnvelope = z
377
+ .object({
378
+ errors: z.array(
379
+ z
380
+ .object({
381
+ type: z.string().optional(),
382
+ extensions: z.object({ code: z.string().optional() }).passthrough().optional(),
383
+ })
384
+ .passthrough(),
385
+ ),
386
+ })
387
+ .safeParse(error.body)
388
+ const rateLimited =
389
+ limitedEnvelope.success &&
390
+ limitedEnvelope.data.errors.some(
391
+ (e) => e.type === 'RATE_LIMITED' || e.extensions?.code === 'RATE_LIMITED',
392
+ )
374
393
  if (
375
394
  error.status !== 429 &&
376
395
  !(
377
- error.status === 403 &&
378
- (error.headers['x-ratelimit-remaining'] === '0' ||
396
+ (error.status === 403 || error.status === 200) &&
397
+ (rateLimited ||
398
+ error.headers['x-ratelimit-remaining'] === '0' ||
379
399
  /rate limit|secondary.*limit|content.creation.*limit/i.test(error.message))
380
400
  )
381
401
  )
@@ -396,3 +416,26 @@ export function githubRateLimitUntil(error: unknown, now: number): string | unde
396
416
  ),
397
417
  ).toISOString()
398
418
  }
419
+
420
+ /** Preserve ordinary errors; only documented limits and retryable transport failures opt in. */
421
+ export function classifyGitHubFailure(error: unknown, now = Date.now()): unknown {
422
+ if (isForgeFailure(error)) return error
423
+ const resetAt = githubRateLimitUntil(error, now)
424
+ const message = error instanceof Error ? error.message : String(error)
425
+ if (resetAt) return new ForgeFailure(message, { kind: 'rate-limited', resetAt })
426
+ const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined
427
+ if (
428
+ (error instanceof GitHubApiError && error.status >= 500) ||
429
+ (error instanceof TypeError && /fetch|network|socket|connection/i.test(message)) ||
430
+ [
431
+ 'ECONNRESET',
432
+ 'ECONNREFUSED',
433
+ 'ETIMEDOUT',
434
+ 'ENOTFOUND',
435
+ 'EAI_AGAIN',
436
+ 'UND_ERR_CONNECT_TIMEOUT',
437
+ ].includes(String(code))
438
+ )
439
+ return new ForgeFailure(message, { kind: 'transient', retry: 'retryable' })
440
+ return error
441
+ }
@@ -1,6 +1,12 @@
1
+ import { isForgeFailure, type ForgeRequestObserver } from '../forge-failure'
2
+ import {
3
+ forgeRequestContext,
4
+ guardedForgeRequest,
5
+ ForgeRequestDeferred,
6
+ } from '../forge-request-context'
1
7
  import { inspectGitHubReadiness } from './github-readiness'
2
8
  import type { ForgeReadinessInput } from './readiness'
3
- import { gitRewrite } from './git-rewrite'
9
+ import { gitRewrite, publishBranch, remoteBranchHead, refreshBranchCache } from './git-rewrite'
4
10
  import { historyContainsBuild, withBuildTrailer } from '../../kernel/build-identity'
5
11
  import { NoCommitsBetweenBranchesError, type BuildLandingOptions } from '../types'
6
12
  import { findSummaryMarker } from './summary-marker'
@@ -35,6 +41,7 @@ import { isValidGitBranchName, normalizeGitRemoteUrl } from '../../kernel/origin
35
41
  import type { Exec } from '../workspace/git-worktree'
36
42
  import {
37
43
  GitHubApiError,
44
+ classifyGitHubFailure,
38
45
  createGitHubFetchTransport,
39
46
  githubTokenSource,
40
47
  restPlanLimitation,
@@ -598,6 +605,7 @@ export class GitHubForge implements Forge {
598
605
  })
599
606
  return { ...result, stdout: redact(result.stdout), stderr: redact(result.stderr) }
600
607
  } catch (error) {
608
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
601
609
  throw new Error(redact(error instanceof Error ? error.message : String(error)))
602
610
  }
603
611
  }
@@ -627,8 +635,11 @@ export class GitHubForge implements Forge {
627
635
  /** Bounded waits between mergeability re-queries on the UNKNOWN path. */
628
636
  private readonly mergeabilityRetryDelaysMs: number[]
629
637
 
638
+ private readonly now: () => number
639
+
630
640
  constructor(
631
641
  opts: {
642
+ now?: () => number
632
643
  transport?: GitHubRequest
633
644
  exec?: Exec
634
645
  /** Literal token, or a resolver. Absent: the adapter resolves
@@ -645,6 +656,7 @@ export class GitHubForge implements Forge {
645
656
  mergeabilityRetryDelaysMs?: number[]
646
657
  } = {},
647
658
  ) {
659
+ this.now = opts.now ?? Date.now
648
660
  this.exec = opts.exec ?? bunExec
649
661
  this.env = opts.env ?? {}
650
662
  this.token = opts.token !== undefined ? opts.token : githubTokenSource(this.env, this.exec)
@@ -652,10 +664,15 @@ export class GitHubForge implements Forge {
652
664
  // stored login, probed lazily through this adapter's exec seam on the
653
665
  // first request. A request that still goes out anonymously carries the
654
666
  // miss reason in its error, so nothing is probed at construction time.
655
- this.transport =
656
- opts.transport ??
657
- createGitHubFetchTransport({
658
- token: this.token,
667
+ const transport = opts.transport ?? createGitHubFetchTransport({ token: this.token })
668
+ this.transport = async (...args) =>
669
+ guardedForgeRequest(async () => {
670
+ for (const observer of this.requestObservers) observer(forgeRequestContext())
671
+ try {
672
+ return await transport(...args)
673
+ } catch (error) {
674
+ throw classifyGitHubFailure(error, this.now())
675
+ }
659
676
  })
660
677
  if (opts.repository !== undefined && opts.repository !== '') {
661
678
  this.explicitRepository = opts.repository
@@ -708,6 +725,14 @@ export class GitHubForge implements Forge {
708
725
  })
709
726
  }
710
727
 
728
+ private readonly requestObservers = new Set<ForgeRequestObserver>()
729
+ observeRequests(observer: ForgeRequestObserver): () => void {
730
+ this.requestObservers.add(observer)
731
+ return () => {
732
+ this.requestObservers.delete(observer)
733
+ }
734
+ }
735
+
711
736
  private async request(
712
737
  method: string,
713
738
  path: string,
@@ -756,8 +781,14 @@ export class GitHubForge implements Forge {
756
781
  }
757
782
  const errors = envelope.data.errors
758
783
  if (errors !== undefined && errors.length > 0) {
759
- throw new Error(
760
- `GitHub GraphQL ${operation} failed: ${errors.map((e) => e.message).join('; ')}`,
784
+ throw classifyGitHubFailure(
785
+ new GitHubApiError(
786
+ response.status,
787
+ `GitHub GraphQL ${operation} failed: ${errors.map((e) => e.message).join('; ')}`,
788
+ response.json,
789
+ response.headers,
790
+ ),
791
+ this.now(),
761
792
  )
762
793
  }
763
794
  if (envelope.data.data === undefined || envelope.data.data === null) {
@@ -774,16 +805,14 @@ export class GitHubForge implements Forge {
774
805
 
775
806
  /** Ordinary phase publication extends history; reconcile uses the separate guarded rewrite capability.
776
807
  * Only ever called from worktree-side terminals and contract fixtures. */
777
- async pushBranch(workspacePath: string, branch: string): Promise<void> {
778
- const result = await this.exec(['git', 'push', '-u', 'origin', `HEAD:refs/heads/${branch}`], {
779
- cwd: workspacePath,
780
- signal: undefined,
781
- })
782
- if (result.exitCode !== 0) {
783
- throw new Error(
784
- `forge command failed (exit ${result.exitCode}): git push -u origin HEAD:refs/heads/${branch}\n${result.stderr.trim()}`,
785
- )
786
- }
808
+ async confirmPublication(workspacePath: string, branch: string, sha: string): Promise<boolean> {
809
+ if ((await remoteBranchHead(this.exec, workspacePath, branch)) !== sha) return false
810
+ await refreshBranchCache(this.exec, workspacePath, branch, sha)
811
+ return true
812
+ }
813
+
814
+ async pushBranch(workspacePath: string, branch: string, sha?: string): Promise<void> {
815
+ await publishBranch(this.exec, workspacePath, branch, sha)
787
816
  }
788
817
 
789
818
  async openPr(opts: {
@@ -829,6 +858,7 @@ export class GitHubForge implements Forge {
829
858
  )
830
859
  return { number: created.number, url: created.html_url, headSha: created.head.sha }
831
860
  } catch (error) {
861
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
832
862
  if (error instanceof GitHubApiError && error.status === 422) {
833
863
  const raced = await probe()
834
864
  if (raced) return raced
@@ -1094,6 +1124,7 @@ export class GitHubForge implements Forge {
1094
1124
  try {
1095
1125
  await this.request('PATCH', prPath, { body: { state: 'closed' } })
1096
1126
  } catch (error) {
1127
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
1097
1128
  closeError = error
1098
1129
  }
1099
1130
  // Re-read even after a mutation failure: GitHub may have merged the PR in
@@ -1114,12 +1145,14 @@ export class GitHubForge implements Forge {
1114
1145
  try {
1115
1146
  await this.request('GET', `${repoPath}/git/ref/heads/${branch}`)
1116
1147
  } catch (error) {
1148
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
1117
1149
  if (error instanceof GitHubApiError && error.status === 404) return // idempotent
1118
1150
  throw error
1119
1151
  }
1120
1152
  try {
1121
1153
  await this.request('DELETE', `${repoPath}/git/refs/heads/${branch}`)
1122
1154
  } catch (error) {
1155
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
1123
1156
  // A probe/delete race (branch deleted elsewhere) is still a success.
1124
1157
  if (error instanceof GitHubApiError && error.status === 404) return
1125
1158
  throw error
@@ -1204,6 +1237,7 @@ export class GitHubForge implements Forge {
1204
1237
  protection.required_pull_request_reviews !== null)
1205
1238
  }
1206
1239
  } catch (error) {
1240
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
1207
1241
  classicError = errorMessage(error)
1208
1242
  }
1209
1243
 
@@ -1241,6 +1275,7 @@ export class GitHubForge implements Forge {
1241
1275
  (rule) => rule.type === 'pull_request' || CONTROLLED_WRITE_RULE_TYPES.has(rule.type),
1242
1276
  ))
1243
1277
  } catch (error) {
1278
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
1244
1279
  if (
1245
1280
  rulesPagesRead === 0 &&
1246
1281
  error instanceof GitHubApiError &&
@@ -1482,6 +1517,7 @@ export class GitHubForge implements Forge {
1482
1517
  throw new Error(disposition.reason)
1483
1518
  }
1484
1519
  } catch (error) {
1520
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
1485
1521
  return {
1486
1522
  kind: 'deferred',
1487
1523
  reason: {
@@ -1688,6 +1724,7 @@ export class GitHubForge implements Forge {
1688
1724
  await this.request('PATCH', `${root}/issues/comments/${match.id}`, { body: { body } })
1689
1725
  return
1690
1726
  } catch (error) {
1727
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
1691
1728
  if (!(error instanceof GitHubApiError) || error.status !== 404 || scan !== 0) throw error
1692
1729
  }
1693
1730
  }
@@ -1734,6 +1771,7 @@ export class GitHubForge implements Forge {
1734
1771
  try {
1735
1772
  return await adopt()
1736
1773
  } catch (error) {
1774
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
1737
1775
  if (!(error instanceof GitHubApiError && error.status === 404)) throw error
1738
1776
  }
1739
1777
  try {
@@ -1751,6 +1789,7 @@ export class GitHubForge implements Forge {
1751
1789
  )
1752
1790
  return result.object.sha
1753
1791
  } catch (error) {
1792
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
1754
1793
  if (!(error instanceof GitHubApiError && error.status === 422)) throw error
1755
1794
  return adopt()
1756
1795
  }
@@ -246,7 +246,12 @@ export class LocalGitForge implements Forge {
246
246
  return records.sort((a, b) => a.number - b.number)
247
247
  }
248
248
 
249
- async pushBranch(workspacePath: string, branch: string): Promise<void> {
249
+ async confirmPublication(workspacePath: string, branch: string, sha: string): Promise<boolean> {
250
+ await this.assertRef(`refs/heads/${branch}`, workspacePath)
251
+ return (await this.sha(`refs/heads/${branch}`, workspacePath)) === sha
252
+ }
253
+
254
+ async pushBranch(workspacePath: string, branch: string, intended?: string): Promise<void> {
250
255
  const ref = `refs/heads/${branch}`
251
256
  await this.assertRef(ref, workspacePath)
252
257
  const symbolic = await this.command(
@@ -262,7 +267,7 @@ export class LocalGitForge implements Forge {
262
267
  this.sha('HEAD', workspacePath),
263
268
  this.sha(ref, workspacePath),
264
269
  ])
265
- if (head !== published) {
270
+ if (head !== published || (intended !== undefined && published !== intended)) {
266
271
  throw new Error(`local-git branch ${ref} does not resolve to workspace HEAD ${head}`)
267
272
  }
268
273
  }