@defrex/autobuild 1.8.0 → 1.9.0

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 (67) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +92 -11
  3. package/docs/architecture.md +38 -14
  4. package/docs/configuration.md +247 -4
  5. package/docs/dispatcher-hosting.md +4 -0
  6. package/docs/merge-policy.md +45 -5
  7. package/docs/operating.md +21 -0
  8. package/docs/operator-api.md +11 -2
  9. package/docs/plugin-authoring.md +4 -1
  10. package/docs/restacking.md +4 -0
  11. package/docs/setup.md +3 -1
  12. package/docs/verification.md +7 -6
  13. package/package.json +4 -3
  14. package/packages/core/src/cli/attention.ts +3 -0
  15. package/packages/core/src/cli/dashboard/landing-display.ts +9 -1
  16. package/packages/core/src/cli/dashboard/model.ts +25 -6
  17. package/packages/core/src/cli/dashboard/render.ts +2 -2
  18. package/packages/core/src/cli/dispatch.ts +120 -1
  19. package/packages/core/src/cli/help.ts +6 -2
  20. package/packages/core/src/cli/repository-status.ts +66 -1
  21. package/packages/core/src/cli/status.ts +2 -2
  22. package/packages/core/src/cli/watch.ts +1074 -627
  23. package/packages/core/src/config/live.ts +1 -0
  24. package/packages/core/src/config/load.ts +19 -0
  25. package/packages/core/src/config/schema.ts +114 -0
  26. package/packages/core/src/events/catalog.ts +2 -0
  27. package/packages/core/src/events/payloads.ts +22 -0
  28. package/packages/core/src/events/policy.ts +9 -0
  29. package/packages/core/src/events/repository.ts +43 -0
  30. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +31 -0
  31. package/packages/core/src/kernel/auto-merge.ts +33 -0
  32. package/packages/core/src/kernel/generators/repository-journals.ts +18 -0
  33. package/packages/core/src/kernel/landing-state.ts +56 -0
  34. package/packages/core/src/kernel/leaf-restack-base.ts +34 -0
  35. package/packages/core/src/kernel/leaf-restack-state.ts +1 -29
  36. package/packages/core/src/kernel/reducer.ts +1 -1
  37. package/packages/core/src/kernel/ticket-wait.ts +1 -1
  38. package/packages/core/src/plugin-sdk/index.ts +7 -1
  39. package/packages/core/src/ports/forge/fake.ts +128 -8
  40. package/packages/core/src/ports/forge/git-rewrite.ts +34 -3
  41. package/packages/core/src/ports/forge/github-squash-message.ts +89 -0
  42. package/packages/core/src/ports/forge/github-transport.ts +30 -0
  43. package/packages/core/src/ports/forge/github.ts +565 -164
  44. package/packages/core/src/ports/types.ts +47 -3
  45. package/packages/core/src/processes/build-execution-state.ts +4 -3
  46. package/packages/core/src/processes/dispatcher.ts +73 -4
  47. package/packages/core/src/processes/execution-no-progress.ts +2 -0
  48. package/packages/core/src/processes/hook-command.ts +125 -0
  49. package/packages/core/src/processes/hook-webhook.ts +144 -0
  50. package/packages/core/src/processes/hooks.ts +740 -0
  51. package/packages/core/src/store/contract.ts +28 -0
  52. package/packages/core/src/store/reducer-value-shapes.json +3729 -3297
  53. package/packages/core/src/store/remote/released-clients.json +22 -0
  54. package/packages/core/src/store/remote/released-reducer-values/1.9.0.json +29475 -0
  55. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  56. package/packages/core/src/store/repo-state-events.ts +3 -0
  57. package/packages/core/src/store/retention.ts +16 -2
  58. package/packages/core/src/testing/index.ts +1 -0
  59. package/packages/core/src/testing/reduced-read-budget.ts +476 -1
  60. package/skills/guide/SKILL.md +81 -6
  61. package/skills/guide/references/merge-policy.md +45 -5
  62. package/skills/guide/references/operator-api.md +11 -2
  63. package/skills/guide/references/plugin-authoring.md +4 -1
  64. package/skills/guide/references/restacking.md +4 -0
  65. package/skills/guide/references/setup.md +3 -1
  66. package/skills/operate/SKILL.md +24 -4
  67. package/templates/hosted-service/package.json +2 -2
@@ -20,8 +20,20 @@ import {
20
20
  neutralizeClosingReferences,
21
21
  withIssueKeywords,
22
22
  } from '../../kernel/issue-keywords'
23
- import { ForgeRejection, NoCommitsBetweenBranchesError, type BuildLandingOptions } from '../types'
23
+ import {
24
+ ForgeMergeQueueRejection,
25
+ ForgeRejection,
26
+ NoCommitsBetweenBranchesError,
27
+ type BuildLandingOptions,
28
+ } from '../types'
24
29
  import { findSummaryMarker } from './summary-marker'
30
+ import {
31
+ GitHubSquashMessageSetting,
32
+ GitHubSquashTitleSetting,
33
+ githubSquashDefaults,
34
+ needsCommitMessages,
35
+ sameArmedMessage,
36
+ } from './github-squash-message'
25
37
  /**
26
38
  * GitHubForge (SPEC §3.2): the Forge adapter for GitHub, speaking the GitHub
27
39
  * REST API through an injectable transport seam. All remote access is
@@ -41,7 +53,9 @@ import { findSummaryMarker } from './summary-marker'
41
53
  *
42
54
  * Native auto-merge is the one operation GitHub exposes only through its
43
55
  * GraphQL schema (no REST route exists), so its enable/disable mutations
44
- * travel over the same transport to `POST /graphql`.
56
+ * travel over the same transport to `POST /graphql`. Those mutations are the
57
+ * landing path's only GraphQL: every landing read, including the squash
58
+ * message derivation and the armed request's identity check, is REST.
45
59
  *
46
60
  * Repository coordinates (owner/name) resolve lazily and memoized: explicit
47
61
  * constructor option → `AB_REPOSITORY` (normalized) → `git remote get-url
@@ -54,7 +68,9 @@ import type { Exec } from '../workspace/git-worktree'
54
68
  import {
55
69
  GitHubApiError,
56
70
  classifyGitHubFailure,
71
+ classifyGitHubGraphQLRefusal,
57
72
  createGitHubFetchTransport,
73
+ isGitHubGraphQLUnavailable,
58
74
  githubCredentialRequirement,
59
75
  githubTokenSource,
60
76
  restPlanLimitation,
@@ -65,6 +81,7 @@ import {
65
81
  } from './github-transport'
66
82
  import {
67
83
  classifyAutoMergeEnable,
84
+ MERGE_CLEAR_STATES,
68
85
  mergeStateStatuses,
69
86
  type MergeGatePresence,
70
87
  type MergeStateStatus,
@@ -191,12 +208,70 @@ const restAutoMergeView = z
191
208
  node_id: z.string().min(1),
192
209
  auto_merge: z.object({}).passthrough().nullable(),
193
210
  mergeable_state: z.string().min(1),
211
+ mergeable: z.boolean().nullable().optional(),
194
212
  head: z.object({ ref: z.string().min(1), sha: z.string().min(1) }).passthrough(),
195
213
  base: z.object({ ref: z.string().min(1) }).passthrough(),
196
214
  })
197
215
  .passthrough()
198
216
 
199
- const restRepositoryAutoMerge = z.object({ allow_auto_merge: z.boolean() }).passthrough()
217
+ /** The polling route's clearance from one REST PR representation. Only the
218
+ * explicit clear states with `mergeable === true` count; anything else,
219
+ * including an unrecognised state (which throws), never merges. */
220
+ function restMergeClear(view: { mergeable_state: string; mergeable?: boolean | null }): {
221
+ mergeState: MergeStateStatus
222
+ clear: boolean
223
+ } {
224
+ const mergeState = restMergeState(view.mergeable_state)
225
+ return { mergeState, clear: MERGE_CLEAR_STATES.has(mergeState) && view.mergeable === true }
226
+ }
227
+
228
+ /** One page of the repository activity feed (`GET /repos/{o}/{r}/activity`). */
229
+ const restActivity = z.array(z.object({ activity_type: z.string() }).passthrough())
230
+
231
+ /** The landing path's PR facts, re-parsed from the same representation the
232
+ * `getPrState` poll fetched. `auto_merge` carries the armed request's
233
+ * method and message overrides (null when GitHub left them unset). */
234
+ const restLandingPr = z
235
+ .object({
236
+ state: z.enum(['open', 'closed']),
237
+ merged: z.boolean(),
238
+ node_id: z.string().min(1),
239
+ title: z.string(),
240
+ body: z.string().nullable(),
241
+ commits: z.number().int().nonnegative(),
242
+ head: z.object({ sha: z.string().min(1), ref: z.string().min(1) }).passthrough(),
243
+ base: z.object({ ref: z.string().min(1), sha: z.string().min(1) }).passthrough(),
244
+ auto_merge: z
245
+ .object({
246
+ merge_method: z.string(),
247
+ commit_title: z.string().nullable(),
248
+ commit_message: z.string().nullable(),
249
+ })
250
+ .passthrough()
251
+ .nullable(),
252
+ })
253
+ .passthrough()
254
+ type LandingView = z.infer<typeof restLandingPr>
255
+ const landingOpen = (view: LandingView): boolean => view.state === 'open' && !view.merged
256
+
257
+ /** One shared repository read: auto-merge permission and the squash
258
+ * settings the landing message derives from. Fields are validated where used. */
259
+ const restRepository = z
260
+ .object({
261
+ allow_auto_merge: z.boolean().optional(),
262
+ squash_merge_commit_title: z.string().optional(),
263
+ squash_merge_commit_message: z.string().optional(),
264
+ })
265
+ .passthrough()
266
+
267
+ const restCommitMessages = z.array(
268
+ z
269
+ .object({ sha: z.string().min(1), commit: z.object({ message: z.string() }).passthrough() })
270
+ .passthrough(),
271
+ )
272
+ const restCompareCommits = z
273
+ .object({ total_commits: z.number().int().nonnegative(), commits: restCommitMessages })
274
+ .passthrough()
200
275
 
201
276
  const nodeComparison = z.object({
202
277
  base_commit: z.object({ sha: z.string().min(1) }),
@@ -387,42 +462,6 @@ const ENABLE_AUTO_MERGE_MUTATION = `
387
462
  }
388
463
  `
389
464
 
390
- const SQUASH_MESSAGE_QUERY = `
391
- query ($owner: String!, $name: String!, $number: Int!, $branch: String) {
392
- repository(owner: $owner, name: $name) {
393
- defaultBranchRef { name }
394
- mergeQueue(branch: $branch) { id }
395
- pullRequest(number: $number) {
396
- id headRefOid state baseRefName
397
- viewerMergeHeadlineText(mergeType: SQUASH)
398
- viewerMergeBodyText(mergeType: SQUASH)
399
- autoMergeRequest { commitHeadline commitBody mergeMethod }
400
- }
401
- }
402
- }
403
- `
404
- const squashMessageData = z.object({
405
- repository: z.object({
406
- defaultBranchRef: z.object({ name: z.string().min(1) }).nullable(),
407
- mergeQueue: z.object({ id: z.string().min(1) }).nullable(),
408
- pullRequest: z.object({
409
- baseRefName: z.string().min(1),
410
- id: z.string().min(1),
411
- headRefOid: z.string().min(1),
412
- state: z.enum(['OPEN', 'MERGED', 'CLOSED']),
413
- viewerMergeHeadlineText: z.string(),
414
- viewerMergeBodyText: z.string(),
415
- autoMergeRequest: z
416
- .object({
417
- // Legacy native requests leave overrides unset; GitHub returns null.
418
- commitHeadline: z.string().nullable(),
419
- commitBody: z.string().nullable(),
420
- mergeMethod: z.string(),
421
- })
422
- .nullable(),
423
- }),
424
- }),
425
- })
426
465
  const ENABLE_IDENTITY_AUTO_MERGE_MUTATION = `
427
466
  mutation ($pullRequestId: ID!, $mergeMethod: PullRequestMergeMethod!,
428
467
  $expectedHeadOid: GitObjectID!, $commitHeadline: String!, $commitBody: String!) {
@@ -449,6 +488,14 @@ const autoMergeMutationPayload = z.object({
449
488
  const enableAutoMergeData = z.object({ enablePullRequestAutoMerge: autoMergeMutationPayload })
450
489
  const disableAutoMergeData = z.object({ disablePullRequestAutoMerge: autoMergeMutationPayload })
451
490
 
491
+ /** The read-only availability probe: the cheapest query GitHub answers. */
492
+ const GRAPHQL_PROBE_QUERY = 'query { rateLimit { cost } }'
493
+ const graphqlProbeData = z.object({ rateLimit: z.object({}).passthrough().nullable() })
494
+
495
+ /** How long one GraphQL refusal suppresses further GraphQL from a forge
496
+ * instance before availability is probed again. */
497
+ export const GITHUB_GRAPHQL_RECHECK_MS = 30 * 60_000
498
+
452
499
  // ── Classic branch protection (REST) ─────────────────────────────────────────
453
500
  //
454
501
  // The documented Branch-protection `protection` object (GET
@@ -571,6 +618,11 @@ function restMergeState(raw: string): MergeStateStatus {
571
618
  return mapped
572
619
  }
573
620
 
621
+ /** The shared polling detail: why this landing is not armed natively. */
622
+ function pollingDetail(number: number, mergeState: MergeStateStatus): string {
623
+ return `GitHub GraphQL is unavailable; PR #${number} reports mergeable_state '${mergeState}'`
624
+ }
625
+
574
626
  // ── Forge adapter ────────────────────────────────────────────────────────────
575
627
 
576
628
  const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))
@@ -597,10 +649,16 @@ export class GitHubForge implements Forge {
597
649
  },
598
650
  false,
599
651
  (ref, sha) => this.createArchive(ref, sha),
652
+ (ref, sha) => this.createArchiveAfterRefusal(ref, sha),
600
653
  )
601
654
  }
602
655
  get kernelRewrite() {
603
- return gitRewrite(this.kernelExec, false, (ref, sha) => this.createArchive(ref, sha))
656
+ return gitRewrite(
657
+ this.kernelExec,
658
+ false,
659
+ (ref, sha) => this.createArchive(ref, sha),
660
+ (ref, sha) => this.createArchiveAfterRefusal(ref, sha),
661
+ )
604
662
  }
605
663
  /** Credentials exist only in the trusted subprocess environment, never in
606
664
  * argv, repository config, remote URLs, or the resolving agent's environment. */
@@ -747,6 +805,47 @@ export class GitHubForge implements Forge {
747
805
  /** Bounded waits between mergeability re-queries on the UNKNOWN path. */
748
806
  private readonly mergeabilityRetryDelaysMs: number[]
749
807
 
808
+ /** Per-instance GraphQL availability. Liveness of this environment, never
809
+ * a durable fact: another dispatcher may reach GraphQL. A refusal holds for
810
+ * {@link GITHUB_GRAPHQL_RECHECK_MS}; any successful GraphQL call proves it
811
+ * available. */
812
+ private graphqlState:
813
+ | { kind: 'unknown' }
814
+ | { kind: 'available' }
815
+ | {
816
+ kind: 'unavailable'
817
+ until: number
818
+ } = { kind: 'unknown' }
819
+ private graphqlProbe?: Promise<boolean>
820
+
821
+ /** Whether GraphQL is reachable, probing at most once per recheck window
822
+ * with a read-only query. Single-flight: the window is armed before the
823
+ * probe is sent, and a probe that fails for any other reason restores the
824
+ * previous state and re-throws. */
825
+ private async graphqlAvailable(): Promise<boolean> {
826
+ const state = this.graphqlState
827
+ if (state.kind === 'available') return true
828
+ if (state.kind === 'unavailable' && this.now() < state.until) return false
829
+ if (this.graphqlProbe !== undefined) return this.graphqlProbe
830
+ this.graphqlState = { kind: 'unavailable', until: this.now() + GITHUB_GRAPHQL_RECHECK_MS }
831
+ const probe = (async () => {
832
+ try {
833
+ await this.graphql('rateLimit', graphqlProbeData, GRAPHQL_PROBE_QUERY, {})
834
+ return true
835
+ } catch (error) {
836
+ if (isGitHubGraphQLUnavailable(error)) return false
837
+ this.graphqlState = state
838
+ throw error
839
+ }
840
+ })()
841
+ this.graphqlProbe = probe
842
+ try {
843
+ return await probe
844
+ } finally {
845
+ this.graphqlProbe = undefined
846
+ }
847
+ }
848
+
750
849
  private readonly now: () => number
751
850
 
752
851
  constructor(
@@ -798,7 +897,16 @@ export class GitHubForge implements Forge {
798
897
  return response
799
898
  } catch (error) {
800
899
  if (error instanceof GitHubApiError) outcome ??= 'restPrimary'
801
- throw classifyGitHubFailure(error, this.now())
900
+ let classified = classifyGitHubFailure(error, this.now())
901
+ if (args[1] === 'graphql') {
902
+ classified = classifyGitHubGraphQLRefusal(classified)
903
+ if (isGitHubGraphQLUnavailable(classified))
904
+ this.graphqlState = {
905
+ kind: 'unavailable',
906
+ until: this.now() + GITHUB_GRAPHQL_RECHECK_MS,
907
+ }
908
+ }
909
+ throw classified
802
910
  } finally {
803
911
  for (const observer of this.requestObservers)
804
912
  observer({ ...context, ...(outcome ? { outcome } : {}) })
@@ -923,6 +1031,8 @@ export class GitHubForge implements Forge {
923
1031
  this.now(),
924
1032
  )
925
1033
  }
1034
+ // Any answered operation proves the endpoint reachable from here.
1035
+ this.graphqlState = { kind: 'available' }
926
1036
  if (envelope.data.data === undefined || envelope.data.data === null) {
927
1037
  throw new Error(`GitHub GraphQL ${operation} returned no data`)
928
1038
  }
@@ -1442,7 +1552,7 @@ export class GitHubForge implements Forge {
1442
1552
  controlledLanding = false,
1443
1553
  ): Promise<
1444
1554
  | { kind: 'proved'; presence: MergeGatePresence }
1445
- | { kind: 'deferred'; reason: AutoMergeDeferralReason }
1555
+ | { kind: 'deferred'; reason: AutoMergeDeferralReason; mergeQueue?: true }
1446
1556
  > {
1447
1557
  const unproven = (detail: string) =>
1448
1558
  ({
@@ -1465,7 +1575,11 @@ export class GitHubForge implements Forge {
1465
1575
  let classicGate: boolean | undefined
1466
1576
  let classicError: string | undefined
1467
1577
  try {
1468
- const branch = await this.request('GET', branchPath)
1578
+ // Scope-local only: a direct squash re-checks the gate the same tick's
1579
+ // enable inspection just read, without repeating the requests.
1580
+ const branch = await this.memo(`gate-branch:${baseRefName}`, () =>
1581
+ this.request('GET', branchPath),
1582
+ )
1469
1583
  const view = branch.json as Record<string, unknown> | undefined
1470
1584
  if (view?.protected === false) {
1471
1585
  // The branch view's own flag proves classic protection absent even
@@ -1495,28 +1609,44 @@ export class GitHubForge implements Forge {
1495
1609
  let planLimited = false
1496
1610
  let rulesPagesRead = 0
1497
1611
  try {
1498
- const parsed: import('zod').infer<typeof restRulesetRules> = []
1499
1612
  // Exhaust effective rules, including organization rules. A truncated
1500
1613
  // first page cannot prove absence, even for a bypass-capable token.
1501
- for (let page = 1; ; page++) {
1502
- if (page > 1000) throw new Error('ruleset pagination did not terminate')
1503
- const rules = await this.request(
1504
- 'GET',
1505
- `${repoPath}/rules/branches/${encodeURIComponent(baseRefName)}`,
1506
- { query: { per_page: '100', page: String(page) } },
1507
- )
1508
- if (rules.status !== 200) throw new Error('incomplete ruleset response')
1509
- const batch = this.parse(restRulesetRules, rules, 'ruleset probe')
1510
- rulesPagesRead++
1511
- parsed.push(...batch)
1512
- const more = rules.headers.link?.includes('rel="next"') === true
1513
- if (batch.length < 100 && !more) break
1514
- if (batch.length === 0) throw new Error('incomplete ruleset pagination')
1515
- }
1614
+ // Scope-local like the branch read above; the outcome carries how many
1615
+ // pages succeeded so a memoized failure classifies identically.
1616
+ const outcome = await this.memo(`rules:${baseRefName}`, async () => {
1617
+ const rules: import('zod').infer<typeof restRulesetRules> = []
1618
+ let pagesRead = 0
1619
+ try {
1620
+ for (let page = 1; ; page++) {
1621
+ if (page > 1000) throw new Error('ruleset pagination did not terminate')
1622
+ const response = await this.request(
1623
+ 'GET',
1624
+ `${repoPath}/rules/branches/${encodeURIComponent(baseRefName)}`,
1625
+ { query: { per_page: '100', page: String(page) } },
1626
+ )
1627
+ if (response.status !== 200) throw new Error('incomplete ruleset response')
1628
+ const batch = this.parse(restRulesetRules, response, 'ruleset probe')
1629
+ pagesRead++
1630
+ rules.push(...batch)
1631
+ const more = response.headers.link?.includes('rel="next"') === true
1632
+ if (batch.length < 100 && !more) break
1633
+ if (batch.length === 0) throw new Error('incomplete ruleset pagination')
1634
+ }
1635
+ return { rules, pagesRead }
1636
+ } catch (error) {
1637
+ return { error, pagesRead }
1638
+ }
1639
+ })
1640
+ rulesPagesRead = outcome.pagesRead
1641
+ if ('error' in outcome) throw outcome.error
1642
+ const parsed = outcome.rules
1516
1643
  if (requireIdentity && parsed.some((rule) => rule.type === 'merge_queue')) {
1517
- return unproven(
1518
- 'GitHub merge queues ignore squash message overrides; merge through a human or change the queue policy to preserve Autobuild-Build identity',
1519
- )
1644
+ return {
1645
+ ...unproven(
1646
+ 'GitHub merge queues ignore squash message overrides; merge through a human or change the queue policy to preserve Autobuild-Build identity',
1647
+ ),
1648
+ mergeQueue: true,
1649
+ }
1520
1650
  }
1521
1651
  rulesetGate =
1522
1652
  rulesetsHaveMergeGate(parsed) ||
@@ -1584,17 +1714,26 @@ export class GitHubForge implements Forge {
1584
1714
  private async inspectAutoMergeView(
1585
1715
  repoPath: string,
1586
1716
  number: number,
1717
+ initial?: LandingView,
1587
1718
  ): Promise<{
1588
1719
  view: z.infer<typeof restAutoMergeView>
1589
1720
  mergeState: MergeStateStatus
1590
1721
  requeries: number
1591
1722
  waitedMs: number
1592
1723
  }> {
1593
- const view = await this.getJson(
1594
- restAutoMergeView,
1595
- `${repoPath}/pulls/${number}`,
1596
- `PR #${number} auto-merge inspection`,
1597
- )
1724
+ const parsedInitial = initial === undefined ? undefined : restAutoMergeView.safeParse(initial)
1725
+ if (parsedInitial?.success === false) {
1726
+ throw new Error(
1727
+ `unexpected GitHub response for PR #${number} auto-merge inspection: ${parsedInitial.error.message}`,
1728
+ )
1729
+ }
1730
+ const view =
1731
+ parsedInitial?.data ??
1732
+ (await this.getJson(
1733
+ restAutoMergeView,
1734
+ `${repoPath}/pulls/${number}`,
1735
+ `PR #${number} auto-merge inspection`,
1736
+ ))
1598
1737
  let current = view
1599
1738
  let requeries = 0
1600
1739
  let waitedMs = 0
@@ -1658,38 +1797,96 @@ export class GitHubForge implements Forge {
1658
1797
  try {
1659
1798
  const { owner, name } = await this.requireCoordinates()
1660
1799
  const repoPath = `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
1661
- // A matching native request needs only this authoritative read, even
1662
- // after a dispatcher restart. Consent is refreshed only before mutations.
1663
- const message =
1664
- options === undefined ? undefined : await this.squashMessage(number, options.baseBranch)
1665
- if (message !== undefined && options !== undefined) {
1666
- if (message.state !== 'OPEN') return { kind: 'deferred' }
1667
- if (await this.identityMessageMatches(message, options)) return { kind: 'applied' }
1800
+ // A matching native request needs only the PR representation the poll
1801
+ // already read and the shared repository settings, even after a
1802
+ // dispatcher restart. Consent is refreshed only before mutations. Merge
1803
+ // queues are re-checked by every mutating path, not on this quiet poll.
1804
+ const landing = options === undefined ? undefined : await this.landingView(number)
1805
+ if (landing !== undefined && options !== undefined) {
1806
+ if (!landingOpen(landing)) return { kind: 'deferred' }
1807
+ if (options.baseBranch !== undefined && landing.base.ref !== options.baseBranch)
1808
+ return {
1809
+ kind: 'deferred',
1810
+ reason: {
1811
+ code: 'unproven-gate-state',
1812
+ detail: `GitHub PR #${number} base ${landing.base.ref} differs from the build's base ${options.baseBranch}`,
1813
+ },
1814
+ }
1815
+ if (await this.identityMessageMatches(number, landing, options)) return { kind: 'applied' }
1816
+ if (options.polling === true) {
1817
+ // Quiet polling tick: the poll's own PR read answers it. No gate,
1818
+ // queue or GraphQL request until GitHub reports the PR clear.
1819
+ const quiet = restAutoMergeView.safeParse(landing)
1820
+ if (!quiet.success)
1821
+ throw new Error(
1822
+ `unexpected GitHub response for PR #${number} polling inspection: ${quiet.error.message}`,
1823
+ )
1824
+ const { mergeState, clear } = restMergeClear(quiet.data)
1825
+ if (!clear)
1826
+ return {
1827
+ kind: 'polling',
1828
+ headSha: landing.head.sha,
1829
+ clear: false,
1830
+ detail: pollingDetail(number, mergeState),
1831
+ }
1832
+ }
1668
1833
  }
1669
1834
  const { view, mergeState, requeries, waitedMs } = await this.inspectAutoMergeView(
1670
1835
  repoPath,
1671
1836
  number,
1837
+ landing,
1672
1838
  )
1673
1839
  if (view.auto_merge !== null && options === undefined) return { kind: 'applied' }
1674
1840
  if (
1675
- message !== undefined &&
1676
- (message.headRefOid !== view.head.sha || message.baseRefName !== view.base.ref)
1841
+ landing !== undefined &&
1842
+ (landing.head.sha !== view.head.sha || landing.base.ref !== view.base.ref)
1677
1843
  )
1678
1844
  return { kind: 'deferred' }
1679
1845
 
1680
1846
  const gate = await this.mergeGatePresence(view.base.ref, options !== undefined)
1681
- if (gate.kind === 'deferred') return gate
1847
+ if (gate.kind === 'deferred') {
1848
+ if (gate.mergeQueue && options !== undefined && !(await this.graphqlAvailable()))
1849
+ return {
1850
+ kind: 'human-merge',
1851
+ cause: 'merge-queue-rule',
1852
+ detail: `GitHub GraphQL is unavailable and ${view.base.ref} requires its merge queue (ruleset)`,
1853
+ }
1854
+ return { kind: 'deferred', reason: gate.reason }
1855
+ }
1682
1856
  const disposition =
1683
1857
  view.auto_merge !== null && options !== undefined && mergeState !== 'DIRTY'
1684
1858
  ? { kind: 'native' as const }
1685
1859
  : classifyAutoMergeEnable(mergeState, gate.presence)
1860
+ // Queue activity is checked on every full-path evaluation with GraphQL
1861
+ // unavailable, whatever the merge state or disposition, so a blocked,
1862
+ // draft or conflicted PR on a queued base settles on its first
1863
+ // evaluation. Only a proved ungated direct candidate skips it.
1864
+ if (
1865
+ options !== undefined &&
1866
+ disposition.kind !== 'direct' &&
1867
+ !(await this.graphqlAvailable()) &&
1868
+ (await this.baseMergeQueueActivity(view.base.ref))
1869
+ )
1870
+ return {
1871
+ kind: 'human-merge',
1872
+ cause: 'merge-queue-activity',
1873
+ detail: `GitHub GraphQL is unavailable and GitHub reports merge-queue merges on ${view.base.ref}`,
1874
+ }
1686
1875
  switch (disposition.kind) {
1687
1876
  case 'native': {
1688
- const repository = await this.getJson(
1689
- restRepositoryAutoMerge,
1690
- repoPath,
1691
- 'repository auto-merge read',
1692
- )
1877
+ if (options !== undefined && !(await this.graphqlAvailable())) {
1878
+ // Repository auto-merge permission is irrelevant to a REST squash.
1879
+ const { clear } = restMergeClear(view)
1880
+ return {
1881
+ kind: 'polling',
1882
+ headSha: view.head.sha,
1883
+ clear,
1884
+ detail: pollingDetail(number, mergeState),
1885
+ }
1886
+ }
1887
+ const repository = await this.repositorySettings()
1888
+ if (typeof repository.allow_auto_merge !== 'boolean')
1889
+ throw new Error('unexpected GitHub response for repository auto-merge read')
1693
1890
  if (!repository.allow_auto_merge) {
1694
1891
  return {
1695
1892
  kind: 'deferred',
@@ -1700,7 +1897,7 @@ export class GitHubForge implements Forge {
1700
1897
  }
1701
1898
  }
1702
1899
  if (options !== undefined)
1703
- return await this.applyIdentityAutoMerge(number, view.head.sha, options, message!)
1900
+ return await this.applyIdentityAutoMerge(number, view.head.sha, options, landing!)
1704
1901
  await this.graphql(
1705
1902
  'enablePullRequestAutoMerge',
1706
1903
  enableAutoMergeData,
@@ -1768,6 +1965,9 @@ export class GitHubForge implements Forge {
1768
1965
  }
1769
1966
  } catch (error) {
1770
1967
  if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
1968
+ // The refusal set the availability memo: the next tick routes to
1969
+ // polling. Nothing for an operator to act on, so no reason.
1970
+ if (isGitHubGraphQLUnavailable(error)) return { kind: 'deferred' }
1771
1971
  return {
1772
1972
  kind: 'deferred',
1773
1973
  reason: {
@@ -1780,69 +1980,197 @@ export class GitHubForge implements Forge {
1780
1980
  }
1781
1981
  }
1782
1982
 
1783
- private async squashMessage(number: number, branch?: string) {
1983
+ /** Whether GitHub reports merge-queue merges on `base`: REST-visible
1984
+ * evidence of a merge queue that classic branch protection does not
1985
+ * expose. One page of one item is enough. Memoized per tick scope; a
1986
+ * response the token cannot read counts as no evidence, because the
1987
+ * guarded squash's refusal still catches a queue at merge time. */
1988
+ private async baseMergeQueueActivity(base: string): Promise<boolean> {
1784
1989
  const { owner, name } = await this.requireCoordinates()
1785
- // The default branch is the usual base. A supplied hint covers other bases
1786
- // in one query; always verify it against the PR, including after retargeting.
1787
- for (let attempt = 0; attempt < 2; attempt++) {
1788
- const data = await this.graphql('squashMessage', squashMessageData, SQUASH_MESSAGE_QUERY, {
1789
- owner,
1790
- name,
1791
- number,
1792
- branch: branch ?? null,
1793
- })
1794
- const message = data.repository.pullRequest
1795
- const inspectedBranch = branch ?? data.repository.defaultBranchRef?.name
1796
- if (inspectedBranch !== message.baseRefName) {
1797
- branch = message.baseRefName
1798
- continue
1990
+ const repoPath = `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
1991
+ return this.memo(`activity:${base}`, async () => {
1992
+ try {
1993
+ const response = await this.request('GET', `${repoPath}/activity`, {
1994
+ query: {
1995
+ ref: `refs/heads/${base}`,
1996
+ activity_type: 'merge_queue_merge',
1997
+ per_page: '1',
1998
+ },
1999
+ })
2000
+ return this.parse(restActivity, response, 'merge-queue activity read').some(
2001
+ (entry) => entry.activity_type === 'merge_queue_merge',
2002
+ )
2003
+ } catch (error) {
2004
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
2005
+ if (error instanceof GitHubApiError && [403, 404, 422].includes(error.status)) return false
2006
+ throw error
1799
2007
  }
1800
- if (data.repository.mergeQueue !== null) {
1801
- throw new Error(
1802
- 'GitHub merge queues ignore squash message overrides; merge through a human or change the queue policy to preserve Autobuild-Build identity',
2008
+ })
2009
+ }
2010
+
2011
+ /** The PR as the landing path sees it. By default this is the
2012
+ * representation the same tick's `getPrState` poll already fetched (shared
2013
+ * memo and ETag). `fresh` bypasses the tick memo with its own conditional
2014
+ * read, for post-mutation readback and the direct squash; mutations clear
2015
+ * validators, so a readback after one is an unconditional 200. */
2016
+ private async landingView(number: number, fresh = false): Promise<LandingView> {
2017
+ const { owner, name } = await this.requireCoordinates()
2018
+ const path = `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${number}`
2019
+ const raw = fresh
2020
+ ? await this.revalidateResource(restPrState, path, `PR #${number} landing read`)
2021
+ : await this.prView(number, path)
2022
+ const parsed = restLandingPr.safeParse(raw)
2023
+ if (!parsed.success) {
2024
+ throw new Error(
2025
+ `unexpected GitHub response for PR #${number} landing read: ${parsed.error.message}`,
2026
+ )
2027
+ }
2028
+ return parsed.data
2029
+ }
2030
+
2031
+ /** Conditional, and shared by every build in a tick scope. */
2032
+ private async repositorySettings(): Promise<z.infer<typeof restRepository>> {
2033
+ const { owner, name } = await this.requireCoordinates()
2034
+ return this.revalidate(
2035
+ restRepository,
2036
+ `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`,
2037
+ 'repository settings read',
2038
+ )
2039
+ }
2040
+
2041
+ /** The PR's commit messages in chronological order, cached under the PR's
2042
+ * commit-set identity. A PR's commit list is BASE..HEAD, so a fixed head
2043
+ * is not enough: a base advance that absorbs head commits changes the
2044
+ * PR's `commits` count (and `base.sha`), which misses the cache. A
2045
+ * same-count base rewrite with an unchanged `base.sha` is an accepted
2046
+ * residual risk; guarding it would need a base read on every poll. */
2047
+ private readonly commitMessageCache = new Map<string, string[]>()
2048
+
2049
+ private async prCommitMessages(number: number, view: LandingView): Promise<string[]> {
2050
+ const count = view.commits
2051
+ const key = `${number}:${view.head.sha}:${view.base.ref}:${view.base.sha}:${count}`
2052
+ const cached = this.commitMessageCache.get(key)
2053
+ if (cached !== undefined && cached.length === count) return cached
2054
+ const { owner, name } = await this.requireCoordinates()
2055
+ const repoPath = `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
2056
+ const raced = (detail: string) =>
2057
+ new Error(`GitHub PR #${number} head or base changed during commit read (${detail}); retry`)
2058
+ const listed: { sha: string; message: string }[] = []
2059
+ const pages = Math.ceil(count / 100)
2060
+ if (count <= 250) {
2061
+ // GitHub caps this listing at 250 commits.
2062
+ for (let page = 1; page <= pages; page++) {
2063
+ const response = await this.request('GET', `${repoPath}/pulls/${number}/commits`, {
2064
+ query: { per_page: '100', page: String(page) },
2065
+ })
2066
+ const batch = this.parse(restCommitMessages, response, `PR #${number} commit list`)
2067
+ listed.push(...batch.map((entry) => ({ sha: entry.sha, message: entry.commit.message })))
2068
+ }
2069
+ if (listed.length !== count || listed.at(-1)?.sha !== view.head.sha)
2070
+ throw raced(`listed ${listed.length} of ${count} commits ending at ${listed.at(-1)?.sha}`)
2071
+ } else {
2072
+ // Past the listing cap, the paginated compare returns every commit.
2073
+ const comparePath = `${repoPath}/compare/${encodeURIComponent(view.base.ref)}...${view.head.sha}`
2074
+ let total: number | undefined
2075
+ for (let page = 1; total === undefined || listed.length < total; page++) {
2076
+ if (page > pages + 1) throw raced('compare pagination did not terminate')
2077
+ const response = await this.request('GET', comparePath, {
2078
+ query: { per_page: '100', page: String(page) },
2079
+ })
2080
+ const batch = this.parse(restCompareCommits, response, `PR #${number} commit compare`)
2081
+ if (total !== undefined && batch.total_commits !== total)
2082
+ throw raced(`compare total changed from ${total} to ${batch.total_commits}`)
2083
+ total = batch.total_commits
2084
+ if (total !== count)
2085
+ throw raced(`compare reports ${total} commits where the PR reports ${count}`)
2086
+ if (batch.commits.length === 0 && listed.length < total)
2087
+ throw raced(`compare page ${page} was empty after ${listed.length} of ${total}`)
2088
+ listed.push(
2089
+ ...batch.commits.map((entry) => ({ sha: entry.sha, message: entry.commit.message })),
1803
2090
  )
2091
+ if (batch.commits.length < 100 && listed.length < total)
2092
+ throw raced(`compare page ${page} was short after ${listed.length} of ${total}`)
1804
2093
  }
1805
- return message
2094
+ if (listed.length !== total || !listed.some((entry) => entry.sha === view.head.sha))
2095
+ throw raced(`compare listed ${listed.length} of ${total} commits without the PR head`)
1806
2096
  }
1807
- throw new Error(
1808
- 'GitHub PR base changed during squash-message and merge-queue inspection; retry',
2097
+ const messages = listed.map((entry) => entry.message)
2098
+ this.commitMessageCache.delete(key)
2099
+ this.commitMessageCache.set(key, messages)
2100
+ while (this.commitMessageCache.size > REPRESENTATION_CACHE_CAP) {
2101
+ this.commitMessageCache.delete(this.commitMessageCache.keys().next().value!)
2102
+ }
2103
+ return messages
2104
+ }
2105
+
2106
+ /** The squash headline and body this build lands with: GitHub's squash
2107
+ * settings applied to the PR, then the shared identity composition. */
2108
+ private async expectedLanding(
2109
+ number: number,
2110
+ view: LandingView,
2111
+ options: BuildLandingOptions,
2112
+ ): Promise<{ headline: string; body: string }> {
2113
+ const repository = await this.repositorySettings()
2114
+ const titleSetting = repository.squash_merge_commit_title
2115
+ const messageSetting = repository.squash_merge_commit_message
2116
+ if (titleSetting === undefined || messageSetting === undefined) {
2117
+ throw new Error(
2118
+ `GitHub repository response omits ${titleSetting === undefined ? 'squash_merge_commit_title' : 'squash_merge_commit_message'}; ` +
2119
+ 'GitHub shows merge settings only to tokens with contents:write',
2120
+ )
2121
+ }
2122
+ const title = GitHubSquashTitleSetting.safeParse(titleSetting)
2123
+ const message = GitHubSquashMessageSetting.safeParse(messageSetting)
2124
+ const commits =
2125
+ title.success &&
2126
+ message.success &&
2127
+ needsCommitMessages(title.data, message.data, view.commits)
2128
+ ? await this.prCommitMessages(number, view)
2129
+ : []
2130
+ return this.landingSquashMessage(
2131
+ githubSquashDefaults({
2132
+ titleSetting,
2133
+ messageSetting,
2134
+ number,
2135
+ title: view.title,
2136
+ body: view.body,
2137
+ commits,
2138
+ }),
2139
+ options,
1809
2140
  )
1810
2141
  }
1811
2142
 
1812
2143
  /** The landed squash headline and body. Writers and the identity
1813
2144
  * comparison share this one composition, so they cannot diverge. */
1814
2145
  private async landingSquashMessage(
1815
- view: z.infer<typeof squashMessageData>['repository']['pullRequest'],
2146
+ defaults: { headline: string; body: string },
1816
2147
  options: BuildLandingOptions,
1817
2148
  ): Promise<{ headline: string; body: string }> {
1818
2149
  const links = options.issueLinks ?? []
1819
2150
  if (links.length === 0)
1820
2151
  return {
1821
- headline: view.viewerMergeHeadlineText,
1822
- body: landingMessage(view.viewerMergeBodyText, options.buildSlug, links),
2152
+ headline: defaults.headline,
2153
+ body: landingMessage(defaults.body, options.buildSlug, links),
1823
2154
  }
1824
2155
  const { owner, name } = await this.requireCoordinates()
1825
2156
  const repository = `${owner}/${name}`
1826
2157
  return {
1827
- headline: neutralizeClosingReferences(view.viewerMergeHeadlineText, links, { repository }),
1828
- body: landingMessage(view.viewerMergeBodyText, options.buildSlug, links, { repository }),
2158
+ headline: neutralizeClosingReferences(defaults.headline, links, { repository }),
2159
+ body: landingMessage(defaults.body, options.buildSlug, links, { repository }),
1829
2160
  }
1830
2161
  }
1831
2162
 
1832
2163
  private async identityMessageMatches(
1833
- view: z.infer<typeof squashMessageData>['repository']['pullRequest'],
2164
+ number: number,
2165
+ view: LandingView,
1834
2166
  options: BuildLandingOptions,
1835
2167
  ): Promise<boolean> {
1836
- if (
1837
- view.autoMergeRequest === null ||
1838
- view.autoMergeRequest.mergeMethod !== 'SQUASH' ||
1839
- view.autoMergeRequest.commitBody === null
1840
- )
1841
- return false
1842
- const expected = await this.landingSquashMessage(view, options)
1843
- return (
1844
- view.autoMergeRequest.commitHeadline === expected.headline &&
1845
- view.autoMergeRequest.commitBody.trimEnd() === expected.body.trimEnd()
2168
+ const armed = view.auto_merge
2169
+ if (armed === null || armed.merge_method !== 'squash') return false
2170
+ if (armed.commit_title === null || armed.commit_message === null) return false
2171
+ return sameArmedMessage(
2172
+ { title: armed.commit_title, message: armed.commit_message },
2173
+ await this.expectedLanding(number, view, options),
1846
2174
  )
1847
2175
  }
1848
2176
 
@@ -1850,48 +2178,48 @@ export class GitHubForge implements Forge {
1850
2178
  number: number,
1851
2179
  expectedHead: string,
1852
2180
  options: BuildLandingOptions,
1853
- message: z.infer<typeof squashMessageData>['repository']['pullRequest'],
2181
+ view: LandingView,
1854
2182
  ): Promise<AutoMergeResult> {
1855
- const expectedBase = message.baseRefName
1856
- const matches = (view: typeof message): Promise<boolean> =>
1857
- this.identityMessageMatches(view, options)
1858
- if (message.state !== 'OPEN' || message.headRefOid !== expectedHead) return { kind: 'deferred' }
1859
- if (await matches(message)) return { kind: 'applied' }
2183
+ const expectedBase = view.base.ref
2184
+ const matches = (current: LandingView): Promise<boolean> =>
2185
+ this.identityMessageMatches(number, current, options)
2186
+ if (!landingOpen(view) || view.head.sha !== expectedHead) return { kind: 'deferred' }
2187
+ if (await matches(view)) return { kind: 'applied' }
1860
2188
  if (options.canApply !== undefined && !(await options.canApply())) return { kind: 'deferred' }
1861
- if (message.autoMergeRequest !== null) {
2189
+ if (view.auto_merge !== null) {
1862
2190
  await this.graphql(
1863
2191
  'disablePullRequestAutoMerge',
1864
2192
  disableAutoMergeData,
1865
2193
  DISABLE_AUTO_MERGE_MUTATION,
1866
- { pullRequestId: message.id },
2194
+ { pullRequestId: view.node_id },
1867
2195
  )
1868
- message = await this.squashMessage(number, message.baseRefName)
2196
+ view = await this.landingView(number, true)
1869
2197
  if (
1870
- message.state !== 'OPEN' ||
1871
- message.headRefOid !== expectedHead ||
1872
- message.baseRefName !== expectedBase ||
1873
- message.autoMergeRequest !== null
2198
+ !landingOpen(view) ||
2199
+ view.head.sha !== expectedHead ||
2200
+ view.base.ref !== expectedBase ||
2201
+ view.auto_merge !== null
1874
2202
  )
1875
2203
  return { kind: 'deferred' }
1876
2204
  }
1877
2205
  if (options.canApply !== undefined && !(await options.canApply())) return { kind: 'deferred' }
1878
- const landing = await this.landingSquashMessage(message, options)
2206
+ const landing = await this.expectedLanding(number, view, options)
1879
2207
  await this.graphql(
1880
2208
  'enablePullRequestAutoMerge',
1881
2209
  enableAutoMergeData,
1882
2210
  ENABLE_IDENTITY_AUTO_MERGE_MUTATION,
1883
2211
  {
1884
- pullRequestId: message.id,
2212
+ pullRequestId: view.node_id,
1885
2213
  mergeMethod: 'SQUASH',
1886
- expectedHeadOid: message.headRefOid,
2214
+ expectedHeadOid: view.head.sha,
1887
2215
  commitHeadline: landing.headline,
1888
2216
  commitBody: landing.body,
1889
2217
  },
1890
2218
  )
1891
- const after = await this.squashMessage(number, message.baseRefName)
1892
- return after.state === 'OPEN' &&
1893
- after.headRefOid === message.headRefOid &&
1894
- after.baseRefName === expectedBase &&
2219
+ const after = await this.landingView(number, true)
2220
+ return landingOpen(after) &&
2221
+ after.head.sha === view.head.sha &&
2222
+ after.base.ref === expectedBase &&
1895
2223
  (await matches(after))
1896
2224
  ? { kind: 'applied' }
1897
2225
  : {
@@ -1938,7 +2266,10 @@ export class GitHubForge implements Forge {
1938
2266
 
1939
2267
  /** Normal guarded squash — no admin, force, rebase, or native-auto flag.
1940
2268
  * A 409 (head moved) surfaces as a hard error, preserving the contract's
1941
- * moved-head rejection. */
2269
+ * moved-head rejection. With `requireClearState` (the polling route), a
2270
+ * fresh read must report the PR clear at the expected head, consent is
2271
+ * rechecked last, and GitHub's refusal of the merge itself is raised as a
2272
+ * `ForgeRejection`; nothing relies on GitHub refusing a premature merge. */
1942
2273
  async squashMerge(
1943
2274
  _workspacePath: string,
1944
2275
  number: number,
@@ -1946,31 +2277,73 @@ export class GitHubForge implements Forge {
1946
2277
  options?: BuildLandingOptions,
1947
2278
  ): Promise<void> {
1948
2279
  const { owner, name } = await this.requireCoordinates()
1949
- const message =
1950
- options === undefined ? undefined : await this.squashMessage(number, options.baseBranch)
1951
- if (
1952
- message !== undefined &&
1953
- (message.state !== 'OPEN' || message.headRefOid !== expectedHeadSha)
1954
- ) {
1955
- throw new Error('GitHub squash message head changed; retry inspection')
2280
+ let landing: { headline: string; body: string } | undefined
2281
+ if (options !== undefined) {
2282
+ const view = await this.landingView(number, true)
2283
+ if (!landingOpen(view) || view.head.sha !== expectedHeadSha) {
2284
+ throw new Error('GitHub squash message head changed; retry inspection')
2285
+ }
2286
+ if (options.baseBranch !== undefined && view.base.ref !== options.baseBranch) {
2287
+ throw new Error(
2288
+ `GitHub PR #${number} base ${view.base.ref} differs from the build's base ${options.baseBranch}; retry inspection`,
2289
+ )
2290
+ }
2291
+ if (options.requireClearState === true) {
2292
+ const current = restAutoMergeView.safeParse(view)
2293
+ if (!current.success || !restMergeClear(current.data).clear)
2294
+ throw new Error(`GitHub no longer reports PR #${number} clear to merge; retry inspection`)
2295
+ }
2296
+ // The dispatcher squashes only after inspection returned `ungated` or a
2297
+ // clear `polling`; this re-checks merge queues, which ignore message
2298
+ // overrides.
2299
+ const gate = await this.mergeGatePresence(view.base.ref, true)
2300
+ if (gate.kind === 'deferred') throw new Error(gate.reason.detail)
2301
+ if (options.requireClearState === true && (await this.baseMergeQueueActivity(view.base.ref)))
2302
+ throw new ForgeMergeQueueRejection(
2303
+ `GitHub reports merge-queue merges on ${view.base.ref}; PR #${number} was not merged`,
2304
+ {
2305
+ forge: 'GitHub',
2306
+ forgeMessage: `GitHub reports merge-queue merges on ${view.base.ref}`,
2307
+ },
2308
+ )
2309
+ landing = await this.expectedLanding(number, view, options)
2310
+ if (
2311
+ options.requireClearState === true &&
2312
+ options.canApply !== undefined &&
2313
+ !(await options.canApply())
2314
+ )
2315
+ return
1956
2316
  }
1957
- const landing =
1958
- message !== undefined && options !== undefined
1959
- ? await this.landingSquashMessage(message, options)
1960
- : undefined
1961
- await this.request(
1962
- 'PUT',
1963
- `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${number}/merge`,
1964
- {
1965
- body: {
1966
- merge_method: 'squash',
1967
- sha: expectedHeadSha,
1968
- ...(landing !== undefined
1969
- ? { commit_title: landing.headline, commit_message: landing.body }
1970
- : {}),
2317
+ try {
2318
+ await this.request(
2319
+ 'PUT',
2320
+ `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/pulls/${number}/merge`,
2321
+ {
2322
+ body: {
2323
+ merge_method: 'squash',
2324
+ sha: expectedHeadSha,
2325
+ ...(landing !== undefined
2326
+ ? { commit_title: landing.headline, commit_message: landing.body }
2327
+ : {}),
2328
+ },
1971
2329
  },
1972
- },
1973
- )
2330
+ )
2331
+ } catch (error) {
2332
+ // Only the polling route settles on a refusal: GitHub declined a PR it
2333
+ // had just reported clear at this exact head. 409 (head moved) and 404
2334
+ // stay hard errors.
2335
+ if (
2336
+ options?.requireClearState === true &&
2337
+ error instanceof GitHubApiError &&
2338
+ [403, 405, 422].includes(error.status)
2339
+ )
2340
+ throw new ForgeRejection(`GitHub refused to merge PR #${number}: ${error.message}`, {
2341
+ forge: 'GitHub',
2342
+ status: error.status,
2343
+ forgeMessage: error.message,
2344
+ })
2345
+ throw error
2346
+ }
1974
2347
  }
1975
2348
 
1976
2349
  /** The build's summary comment (SPEC §7.5) — links into the store. */
@@ -2063,6 +2436,34 @@ export class GitHubForge implements Forge {
2063
2436
  )
2064
2437
  }
2065
2438
 
2439
+ /** Environments such as Claude Code on the web refuse non-branch git pushes but
2440
+ * allow REST, so the identical create-only ref goes through the API instead. A
2441
+ * 422 means the ref exists or GitHub lacks the commit; only a 404 commit probe
2442
+ * proves the latter, and the caller's readback judges every other outcome. */
2443
+ private async createArchiveAfterRefusal(ref: string, sha: string): Promise<void> {
2444
+ try {
2445
+ await this.createArchive(ref, sha)
2446
+ } catch (error) {
2447
+ if (isForgeFailure(error) || error instanceof ForgeRequestDeferred) throw error
2448
+ if (!(error instanceof GitHubApiError && error.status === 422)) throw error
2449
+ const { owner, name } = await this.requireCoordinates()
2450
+ try {
2451
+ await this.request(
2452
+ 'GET',
2453
+ `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/git/commits/${sha}`,
2454
+ )
2455
+ } catch (probe) {
2456
+ if (isForgeFailure(probe) || probe instanceof ForgeRequestDeferred) throw probe
2457
+ if (probe instanceof GitHubApiError && probe.status === 404)
2458
+ throw new Error(
2459
+ `commit ${sha} exists only in the local workspace; this environment refuses non-branch git pushes, and GitHub REST can create ${ref} only for a commit already on GitHub. Publish the commit on a build branch from an environment that permits archive pushes, or allow refs/autobuild/archive/ pushes`,
2460
+ { cause: error },
2461
+ )
2462
+ }
2463
+ throw error
2464
+ }
2465
+ }
2466
+
2066
2467
  async createNodeBranch(branch: string, sha: string): Promise<string> {
2067
2468
  if (!isValidGitBranchName(branch)) throw new Error('invalid node branch')
2068
2469
  const { owner, name } = await this.requireCoordinates()