@defrex/autobuild 0.14.0 → 1.0.0-beta.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 (172) hide show
  1. package/README.md +4 -2
  2. package/SPEC.md +654 -98
  3. package/docs/architecture.md +226 -5
  4. package/docs/assets/headline-wide.png +0 -0
  5. package/docs/configuration.md +112 -12
  6. package/docs/hosted-service.md +18 -0
  7. package/docs/integration-tree.md +117 -0
  8. package/docs/landing-policy.md +150 -0
  9. package/docs/mcp.md +24 -0
  10. package/docs/migration-1.0.md +68 -0
  11. package/docs/operator-api.md +19 -8
  12. package/docs/remote-store-protocol.md +30 -7
  13. package/docs/remote-ticket-protocol.md +26 -5
  14. package/docs/restacking.md +79 -0
  15. package/docs/setup.md +49 -6
  16. package/docs/ticket-dependencies.md +69 -0
  17. package/docs/ticket-migration.md +8 -0
  18. package/package.json +3 -3
  19. package/packages/core/src/cli/attention.ts +25 -2
  20. package/packages/core/src/cli/build-control.ts +65 -41
  21. package/packages/core/src/cli/context.ts +54 -2
  22. package/packages/core/src/cli/dashboard/actions.ts +6 -3
  23. package/packages/core/src/cli/dashboard/landing-display.ts +6 -0
  24. package/packages/core/src/cli/dashboard/live.ts +5 -0
  25. package/packages/core/src/cli/dashboard/model.ts +142 -18
  26. package/packages/core/src/cli/dashboard/poll.ts +15 -9
  27. package/packages/core/src/cli/dashboard/refresh.ts +176 -0
  28. package/packages/core/src/cli/dashboard/render.ts +78 -28
  29. package/packages/core/src/cli/dashboard/repository-poll.ts +57 -0
  30. package/packages/core/src/cli/dashboard/selection.ts +7 -1
  31. package/packages/core/src/cli/dashboard/tree.ts +107 -0
  32. package/packages/core/src/cli/dispatch-frontend.ts +156 -109
  33. package/packages/core/src/cli/dispatch.ts +250 -136
  34. package/packages/core/src/cli/dispatcher-liveness.ts +15 -2
  35. package/packages/core/src/cli/help.ts +49 -32
  36. package/packages/core/src/cli/init-validation.ts +43 -2
  37. package/packages/core/src/cli/keyboard.ts +6 -0
  38. package/packages/core/src/cli/landings.ts +18 -0
  39. package/packages/core/src/cli/main.ts +49 -15
  40. package/packages/core/src/cli/mcp.ts +9 -0
  41. package/packages/core/src/cli/publication-settlement.ts +168 -2
  42. package/packages/core/src/cli/repository-status.ts +11 -0
  43. package/packages/core/src/cli/status.ts +72 -5
  44. package/packages/core/src/cli/terminal-restore.ts +54 -0
  45. package/packages/core/src/cli/terminal.ts +16 -2
  46. package/packages/core/src/cli/terminals.ts +98 -79
  47. package/packages/core/src/cli/ticket-editor.ts +10 -3
  48. package/packages/core/src/cli/ticket.ts +113 -18
  49. package/packages/core/src/cli/upgrade-commit.ts +4 -0
  50. package/packages/core/src/cli/upgrade-compatibility.ts +2 -2
  51. package/packages/core/src/cli/upgrade-landing.ts +69 -0
  52. package/packages/core/src/cli/upgrade.ts +16 -0
  53. package/packages/core/src/cli/wait.ts +115 -19
  54. package/packages/core/src/cli/watch.ts +51 -12
  55. package/packages/core/src/config/landing.ts +22 -0
  56. package/packages/core/src/config/live.ts +1 -0
  57. package/packages/core/src/config/schema.ts +3 -0
  58. package/packages/core/src/events/catalog.ts +48 -3
  59. package/packages/core/src/events/payloads.ts +295 -6
  60. package/packages/core/src/events/repository.ts +31 -0
  61. package/packages/core/src/integration/harness.ts +10 -0
  62. package/packages/core/src/kernel/__snapshots__/reducer-registry.test.ts.snap +1030 -239
  63. package/packages/core/src/kernel/auto-merge-default.ts +1 -0
  64. package/packages/core/src/kernel/auto-merge.ts +12 -3
  65. package/packages/core/src/kernel/build-identity.ts +94 -0
  66. package/packages/core/src/kernel/change-presence.ts +179 -0
  67. package/packages/core/src/kernel/dispatch-status.ts +17 -1
  68. package/packages/core/src/kernel/engine.ts +89 -2
  69. package/packages/core/src/kernel/generators/build-log.ts +23 -0
  70. package/packages/core/src/kernel/generators/leaf-restack-log.ts +110 -0
  71. package/packages/core/src/kernel/generators/node-restack-log.ts +94 -0
  72. package/packages/core/src/kernel/generators/repository-journals.ts +11 -0
  73. package/packages/core/src/kernel/integration-completeness.ts +81 -0
  74. package/packages/core/src/kernel/integration-landing.ts +263 -0
  75. package/packages/core/src/kernel/integration-stack.ts +36 -0
  76. package/packages/core/src/kernel/integration-state.ts +135 -0
  77. package/packages/core/src/kernel/landing-policy.ts +47 -0
  78. package/packages/core/src/kernel/landing-publication.ts +41 -0
  79. package/packages/core/src/kernel/landing-readiness.ts +67 -0
  80. package/packages/core/src/kernel/landing-state.ts +96 -0
  81. package/packages/core/src/kernel/leaf-restack-completion.ts +24 -0
  82. package/packages/core/src/kernel/leaf-restack-state.ts +73 -0
  83. package/packages/core/src/kernel/log-index.ts +35 -5
  84. package/packages/core/src/kernel/node-landing.ts +439 -0
  85. package/packages/core/src/kernel/node-parent.ts +184 -0
  86. package/packages/core/src/kernel/node-restack-state.ts +191 -0
  87. package/packages/core/src/kernel/node-restack-transaction.ts +210 -0
  88. package/packages/core/src/kernel/node-restack.ts +274 -0
  89. package/packages/core/src/kernel/read-facts.ts +70 -3
  90. package/packages/core/src/kernel/reconcile-head.ts +51 -0
  91. package/packages/core/src/kernel/reconcile-restack.ts +560 -0
  92. package/packages/core/src/kernel/reducer-registry.ts +16 -0
  93. package/packages/core/src/kernel/reducer.ts +121 -6
  94. package/packages/core/src/kernel/snapshot-parent.ts +33 -0
  95. package/packages/core/src/ontology.ts +9 -1
  96. package/packages/core/src/operator/annotations.ts +12 -0
  97. package/packages/core/src/operator/control.ts +6 -0
  98. package/packages/core/src/operator/index.ts +4 -0
  99. package/packages/core/src/operator/landings.ts +35 -0
  100. package/packages/core/src/operator/presentation.ts +1 -0
  101. package/packages/core/src/operator/protocol.ts +12 -3
  102. package/packages/core/src/operator/query.ts +3 -1
  103. package/packages/core/src/operator/registry.ts +48 -19
  104. package/packages/core/src/operator/requests.ts +1 -8
  105. package/packages/core/src/operator/tickets.ts +55 -9
  106. package/packages/core/src/ports/forge/contract.ts +91 -3
  107. package/packages/core/src/ports/forge/fake.ts +142 -4
  108. package/packages/core/src/ports/forge/git-rewrite.ts +232 -0
  109. package/packages/core/src/ports/forge/github-readiness.ts +421 -0
  110. package/packages/core/src/ports/forge/github.ts +631 -35
  111. package/packages/core/src/ports/forge/local-git.ts +119 -5
  112. package/packages/core/src/ports/forge/readiness.ts +99 -0
  113. package/packages/core/src/ports/tickets/contract.ts +41 -0
  114. package/packages/core/src/ports/tickets/create.ts +8 -1
  115. package/packages/core/src/ports/tickets/fake.ts +32 -1
  116. package/packages/core/src/ports/tickets/file-codec.ts +7 -0
  117. package/packages/core/src/ports/tickets/file.ts +18 -1
  118. package/packages/core/src/ports/tickets/hosted-index.ts +2 -0
  119. package/packages/core/src/ports/tickets/linear.ts +124 -4
  120. package/packages/core/src/ports/tickets/migration.ts +25 -1
  121. package/packages/core/src/ports/tickets/operations.ts +7 -2
  122. package/packages/core/src/ports/tickets/remote-protocol.ts +19 -0
  123. package/packages/core/src/ports/tickets/remote.ts +10 -1
  124. package/packages/core/src/ports/tickets/revision.ts +3 -1
  125. package/packages/core/src/ports/tickets/tree.ts +148 -0
  126. package/packages/core/src/ports/tickets/update.ts +15 -2
  127. package/packages/core/src/ports/types.ts +135 -5
  128. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  129. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -1
  130. package/packages/core/src/ports/workspace/vercel-sandbox.ts +60 -3
  131. package/packages/core/src/processes/build-runner.ts +530 -23
  132. package/packages/core/src/processes/dispatcher-selectors.ts +15 -9
  133. package/packages/core/src/processes/dispatcher.ts +2145 -203
  134. package/packages/core/src/processes/execution-no-progress.ts +46 -1
  135. package/packages/core/src/processes/publication-state.ts +30 -5
  136. package/packages/core/src/processes/repo-view.ts +21 -2
  137. package/packages/core/src/store/build-scope.ts +18 -0
  138. package/packages/core/src/store/contract.ts +658 -0
  139. package/packages/core/src/store/digest.ts +52 -4
  140. package/packages/core/src/store/local/schema.ts +25 -13
  141. package/packages/core/src/store/local/store.ts +117 -1
  142. package/packages/core/src/store/memory.ts +62 -1
  143. package/packages/core/src/store/phase-session.ts +17 -0
  144. package/packages/core/src/store/reduced-reads.ts +2 -1
  145. package/packages/core/src/store/reducer-value-shapes.json +10707 -6440
  146. package/packages/core/src/store/remote/client.ts +44 -0
  147. package/packages/core/src/store/remote/compatibility.ts +19 -9
  148. package/packages/core/src/store/remote/protocol.ts +11 -0
  149. package/packages/core/src/store/repo-state-events.ts +2 -0
  150. package/packages/core/src/store/session-handle.ts +15 -0
  151. package/packages/core/src/store/subscribe.ts +1 -1
  152. package/packages/core/src/store/types.ts +32 -4
  153. package/packages/core/src/testing/index.ts +2 -0
  154. package/packages/core/src/testing/reduced-read-budget.ts +48 -8
  155. package/packages/core/src/testing/refresh-scheduler.ts +32 -0
  156. package/skills/guide/SKILL.md +110 -61
  157. package/skills/guide/references/integration-tree.md +117 -0
  158. package/skills/guide/references/landing-policy.md +150 -0
  159. package/skills/guide/references/migration-1.0.md +68 -0
  160. package/skills/guide/references/operator-api.md +12 -5
  161. package/skills/guide/references/plugin-authoring.md +34 -0
  162. package/skills/guide/references/remote-store-protocol.md +30 -7
  163. package/skills/guide/references/remote-ticket-protocol.md +26 -5
  164. package/skills/guide/references/restacking.md +79 -0
  165. package/skills/guide/references/setup.md +49 -6
  166. package/skills/guide/references/ticket-dependencies.md +69 -0
  167. package/skills/guide/references/ticket-migration.md +8 -0
  168. package/skills/operate/SKILL.md +55 -5
  169. package/skills/reconcile/SKILL.md +55 -48
  170. package/skills/spec/SKILL.md +67 -1
  171. package/skills/tickets/SKILL.md +55 -2
  172. package/templates/autobuild.toml +3 -0
@@ -0,0 +1,232 @@
1
+ import type { ForgeRewrite, RewriteResult } from '../types'
2
+ import type { Exec } from '../workspace/git-worktree'
3
+ import { isValidGitBranchName } from '../../kernel/origin'
4
+
5
+ const oid = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/
6
+ function object(value: string): void {
7
+ if (!oid.test(value)) throw new Error(`rewrite requires an exact object id: ${value}`)
8
+ }
9
+ function branchRef(branch: string): string {
10
+ if (!isValidGitBranchName(branch) || !/^(?:ab|ab-node)\/[a-z0-9]+(?:-[a-z0-9]+)*$/.test(branch))
11
+ throw new Error(`rewrite requires a build branch: ${branch}`)
12
+ return `refs/heads/${branch}`
13
+ }
14
+
15
+ /** Git transport and shared-database implementations share validation, but local-git
16
+ * never consults a remote, even when the repository happens to have one. */
17
+ export function gitRewrite(exec: Exec, local: boolean): ForgeRewrite {
18
+ async function git(cwd: string, args: string[], allowFailure = false) {
19
+ const result = await exec(['git', ...args], { cwd })
20
+ if (!allowFailure && result.exitCode !== 0)
21
+ throw new Error(
22
+ `reconcile git ${args.join(' ')} failed: ${result.stderr || result.stdout}; enable refs/autobuild/archive/ publication and guarded build-branch rewrites`,
23
+ )
24
+ return result
25
+ }
26
+ async function read(cwd: string, ref: string): Promise<string | null> {
27
+ const result = await git(
28
+ cwd,
29
+ local ? ['rev-parse', '--verify', '--quiet', ref] : ['ls-remote', '--refs', 'origin', ref],
30
+ true,
31
+ )
32
+ if (local && result.exitCode === 1) return null
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
38
+ }
39
+ return {
40
+ async fastForward(input) {
41
+ object(input.expected)
42
+ object(input.sha)
43
+ if (!isValidGitBranchName(input.branch)) throw new Error('invalid fast-forward destination')
44
+ const ancestry = await git(
45
+ input.workspacePath,
46
+ ['merge-base', '--is-ancestor', input.expected, input.sha],
47
+ true,
48
+ )
49
+ 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
+ const result = await git(
54
+ input.workspacePath,
55
+ local
56
+ ? ['update-ref', ref, input.sha, input.expected]
57
+ : [
58
+ 'push',
59
+ '--porcelain',
60
+ `--force-with-lease=${ref}:${input.expected}`,
61
+ 'origin',
62
+ `${input.sha}:${ref}`,
63
+ ],
64
+ true,
65
+ )
66
+ if (result.exitCode !== 0)
67
+ return { kind: 'lease-mismatch', actual: await read(input.workspacePath, ref) }
68
+ return { kind: 'published' }
69
+ },
70
+ async snapshot(input) {
71
+ const ref = branchRef(input.branch)
72
+ if (!/^refs\/autobuild\/reconcile\/[a-z0-9-]+\/[a-z0-9/-]+$/.test(input.destinationRef))
73
+ throw new Error('snapshot requires a build-private reconcile ref')
74
+ if (local) {
75
+ const sha = await read(input.workspacePath, ref)
76
+ if (sha === null)
77
+ throw new Error(`build branch ${ref} was deleted; restore it before reconciling`)
78
+ await git(input.workspacePath, ['update-ref', input.destinationRef, sha])
79
+ return sha
80
+ }
81
+ await git(input.workspacePath, [
82
+ 'fetch',
83
+ '--no-tags',
84
+ '--no-write-fetch-head',
85
+ '--refmap=',
86
+ 'origin',
87
+ `+${ref}:${input.destinationRef}`,
88
+ ])
89
+ const result = await git(input.workspacePath, [
90
+ 'rev-parse',
91
+ '--verify',
92
+ `${input.destinationRef}^{commit}`,
93
+ ])
94
+ const sha = result.stdout.trim()
95
+ object(sha)
96
+ return sha
97
+ },
98
+ async archive(input) {
99
+ object(input.sha)
100
+ if (
101
+ !/^refs\/autobuild\/archive\/[a-z0-9]+(?:-[a-z0-9]+)*\/[0-9a-f]+$/.test(input.ref) ||
102
+ !input.ref.endsWith(`/${input.sha}`)
103
+ )
104
+ throw new Error(`invalid immutable archive ref: ${input.ref}`)
105
+ const existing = await read(input.workspacePath, input.ref)
106
+ if (existing !== null && existing !== input.sha)
107
+ throw new Error(`immutable archive ${input.ref} names ${existing}, expected ${input.sha}`)
108
+ if (existing === null) {
109
+ const result = await git(
110
+ input.workspacePath,
111
+ local
112
+ ? ['update-ref', input.ref, input.sha, '0'.repeat(input.sha.length)]
113
+ : ['push', `--force-with-lease=${input.ref}:`, 'origin', `${input.sha}:${input.ref}`],
114
+ true,
115
+ )
116
+ // An uncertain acknowledgement is adopted only after an exact readback.
117
+ if ((await read(input.workspacePath, input.ref)) !== input.sha)
118
+ throw new Error(
119
+ `archive publication rejected for ${input.ref}: ${result.stderr}; enable refs/autobuild/archive/ publication before branch rewrites`,
120
+ )
121
+ }
122
+ if (!local) {
123
+ // Fetch by the exact archive ref, never by an unadvertised object id.
124
+ await git(input.workspacePath, [
125
+ 'fetch',
126
+ '--no-tags',
127
+ '--no-write-fetch-head',
128
+ 'origin',
129
+ input.ref,
130
+ ])
131
+ }
132
+ await git(input.workspacePath, ['cat-file', '-e', `${input.sha}^{commit}`])
133
+ },
134
+ async replace(input): Promise<RewriteResult> {
135
+ object(input.expected)
136
+ object(input.sha)
137
+ const ref = branchRef(input.branch)
138
+ const actual = await read(input.workspacePath, ref)
139
+ async function acknowledge(): Promise<RewriteResult> {
140
+ 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
+ ])
153
+ }
154
+ // Replay stays detached until the guarded branch update is confirmed.
155
+ // Reattach only its exact workspace result; explicit-source callers may
156
+ // legitimately publish an object other than their checked-out HEAD.
157
+ const workspaceHead = await git(input.workspacePath, ['rev-parse', 'HEAD'])
158
+ if (!input.branch.startsWith('ab-node/') && workspaceHead.stdout.trim() === input.sha)
159
+ await git(input.workspacePath, ['checkout', '--no-guess', input.branch])
160
+ return { kind: 'published' }
161
+ }
162
+ 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
+ return { kind: 'lease-mismatch', actual: observed }
206
+ }
207
+ if (actual === input.sha) return acknowledge()
208
+ if (actual !== input.expected) return mismatch(actual)
209
+ const result = await git(
210
+ input.workspacePath,
211
+ local
212
+ ? ['update-ref', ref, input.sha, input.expected]
213
+ : [
214
+ 'push',
215
+ `--force-with-lease=${ref}:${input.expected}`,
216
+ 'origin',
217
+ `${input.sha}:${ref}`,
218
+ ],
219
+ true,
220
+ )
221
+ const after = await read(input.workspacePath, ref)
222
+ if (after === input.sha) return acknowledge()
223
+ // A successful CAS is a fact even if its candidate is overtaken before
224
+ // readback. Callers record that rewrite, then replay the observed head.
225
+ if (result.exitCode === 0) return { kind: 'lease-mismatch', actual: after, rewritten: true }
226
+ if (after !== input.expected) return mismatch(after)
227
+ throw new Error(
228
+ `guarded rewrite rejected for ${ref}: ${result.stderr}; enable guarded build-branch rewrites`,
229
+ )
230
+ },
231
+ }
232
+ }
@@ -0,0 +1,421 @@
1
+ import { z } from 'zod'
2
+ import type { GitHubRequest } from './github-transport'
3
+ import { readinessChecks, type ForgeReadinessCheck, type ForgeReadinessInput } from './readiness'
4
+
5
+ const access =
6
+ 'Grant Metadata:read and Administration:read for inspection (classic private repositories: repo scope); Contents:write is separately required for publication.'
7
+ const ruleSchema = z.object({
8
+ type: z.string().min(1),
9
+ ruleset_id: z.number().int().positive().optional(),
10
+ parameters: z.unknown().optional(),
11
+ })
12
+ const rulesetSchema = z.object({
13
+ id: z.number().int(),
14
+ target: z.enum(['branch', 'tag', 'push']),
15
+ enforcement: z.enum(['active', 'disabled', 'evaluate']),
16
+ bypass_actors: z
17
+ .array(
18
+ z.object({
19
+ actor_type: z.string(),
20
+ actor_id: z.number().nullable(),
21
+ bypass_mode: z.enum(['always', 'pull_request', 'exempt']),
22
+ }),
23
+ )
24
+ .optional(),
25
+ conditions: z
26
+ .object({ ref_name: z.object({ include: z.array(z.string()), exclude: z.array(z.string()) }) })
27
+ .optional(),
28
+ rules: z.array(ruleSchema),
29
+ })
30
+ type Ruleset = z.infer<typeof rulesetSchema>
31
+ const classicSchema = z.object({
32
+ pattern: z.string(),
33
+ allowsForcePushes: z.boolean(),
34
+ restrictsPushes: z.boolean(),
35
+ requiresLinearHistory: z.boolean(),
36
+ isAdminEnforced: z.boolean(),
37
+ lockBranch: z.boolean(),
38
+ blocksCreations: z.boolean(),
39
+ requiresApprovingReviews: z.boolean(),
40
+ requiresStatusChecks: z.boolean(),
41
+ requiresCommitSignatures: z.boolean(),
42
+ requiresDeployments: z.boolean(),
43
+ bypassForcePushAllowances: z.object({ totalCount: z.number().int().nonnegative() }),
44
+ })
45
+ type Classic = z.infer<typeof classicSchema>
46
+ type Applicability = 'yes' | 'no' | 'unknown'
47
+
48
+ /** Deliberately small subset of GitHub fnmatch: literals and trailing /**.
49
+ * Everything else stays uncertain; never use a regex approximation as proof. */
50
+ export function patternMatches(pattern: string, name: string, defaultRef: string): Applicability {
51
+ if (pattern === '~ALL') return 'yes'
52
+ if (pattern === '~DEFAULT_BRANCH') return name === defaultRef ? 'yes' : 'no'
53
+ if (!/[?*[\\]/.test(pattern)) return pattern === name ? 'yes' : 'no'
54
+ if (pattern.endsWith('/**') && !/[?*[\\]/.test(pattern.slice(0, -3)))
55
+ return name.startsWith(pattern.slice(0, -2)) ? 'yes' : 'no'
56
+ return 'unknown'
57
+ }
58
+ /** Whether some future name in a namespace can be selected. Literal exceptions
59
+ * inside the namespace count, even when no such ref exists yet. */
60
+ export function patternOverlaps(
61
+ pattern: string,
62
+ prefix: string,
63
+ defaultRef: string,
64
+ ): Applicability {
65
+ if (pattern === '~ALL') return 'yes'
66
+ if (pattern === '~DEFAULT_BRANCH') return defaultRef.startsWith(prefix) ? 'yes' : 'no'
67
+ if (!/[?*[\\]/.test(pattern)) return pattern.startsWith(prefix) ? 'yes' : 'no'
68
+ const literal = pattern.split(/[?*[\\]/)[0]!
69
+ if (!prefix.startsWith(literal) && !literal.startsWith(prefix)) return 'no'
70
+ if (pattern.endsWith('/**') && !/[?*[\\]/.test(pattern.slice(0, -3))) return 'yes'
71
+ return 'unknown'
72
+ }
73
+ function any(values: Applicability[]): Applicability {
74
+ return values.includes('yes') ? 'yes' : values.includes('unknown') ? 'unknown' : 'no'
75
+ }
76
+ function applies(
77
+ set: Ruleset,
78
+ value: string,
79
+ defaultRef: string,
80
+ namespace = false,
81
+ ): Applicability {
82
+ if (set.target === 'push') return 'yes'
83
+ if (set.target !== 'branch') return 'no'
84
+ if (!set.conditions) return 'unknown'
85
+ const conditions = set.conditions.ref_name
86
+ const match = namespace ? patternOverlaps : patternMatches
87
+ const include = any(conditions.include.map((pattern) => match(pattern, value, defaultRef)))
88
+ if (include === 'no') return 'no'
89
+ if (!namespace) {
90
+ const exclude = any(
91
+ conditions.exclude.map((pattern) => patternMatches(pattern, value, defaultRef)),
92
+ )
93
+ if (exclude === 'yes') return 'no'
94
+ return exclude === 'unknown' ? 'unknown' : include
95
+ }
96
+ // An exclusion of the entire prefix proves disjointness. Partial exclusions
97
+ // cannot prove that all future names are exempt.
98
+ if (conditions.exclude.some((pattern) => pattern === '~ALL' || pattern === `${value}**`))
99
+ return 'no'
100
+ if (conditions.exclude.every((pattern) => patternOverlaps(pattern, value, defaultRef) === 'no'))
101
+ return include
102
+ // Literal exclusions remove finitely many names. A supported recursive
103
+ // include still restricts infinitely many names in the owned namespace.
104
+ const literalExclusions = conditions.exclude.every((pattern) => !/[?*[\\~]/.test(pattern))
105
+ if (literalExclusions) {
106
+ for (const pattern of conditions.include) {
107
+ if (patternOverlaps(pattern, value, defaultRef) !== 'yes') continue
108
+ if (pattern === '~ALL' || pattern.endsWith('/**')) return 'yes'
109
+ const concrete = pattern === '~DEFAULT_BRANCH' ? defaultRef : pattern
110
+ if (
111
+ conditions.exclude.every(
112
+ (exclude) => patternMatches(exclude, concrete, defaultRef) === 'no',
113
+ )
114
+ )
115
+ return 'yes'
116
+ }
117
+ }
118
+ return 'unknown'
119
+ }
120
+
121
+ export async function inspectGitHubReadiness(opts: {
122
+ request: GitHubRequest
123
+ owner: string
124
+ name: string
125
+ input: ForgeReadinessInput
126
+ }): Promise<ForgeReadinessCheck[]> {
127
+ const { request } = opts
128
+ const root = `repos/${encodeURIComponent(opts.owner)}/${encodeURIComponent(opts.name)}`
129
+ const checks = readinessChecks('unknown', `Inspection incomplete. ${access}`)
130
+ const set = (
131
+ key: ForgeReadinessCheck['check'],
132
+ status: ForgeReadinessCheck['status'],
133
+ detail: string,
134
+ ) => {
135
+ const check = checks.find((item) => item.check === key)!
136
+ check.status = status
137
+ check.detail = detail
138
+ }
139
+ async function get<T>(
140
+ path: string,
141
+ schema: z.ZodType<T>,
142
+ query?: Record<string, string>,
143
+ ): Promise<T> {
144
+ const response = await request('GET', path, query ? { query } : undefined)
145
+ if (response.status < 200 || response.status >= 300) throw new Error('GitHub inspection failed')
146
+ return schema.parse(response.json)
147
+ }
148
+ async function pages<T>(
149
+ path: string,
150
+ schema: z.ZodType<T>,
151
+ query: Record<string, string> = {},
152
+ ): Promise<T[]> {
153
+ const result: T[] = []
154
+ for (let page = 1; ; page++) {
155
+ const batch = await get(path, z.array(schema), {
156
+ ...query,
157
+ per_page: '100',
158
+ page: String(page),
159
+ })
160
+ result.push(...batch)
161
+ if (batch.length < 100) return result
162
+ }
163
+ }
164
+ let write: boolean | undefined
165
+ let defaultRef: string | undefined
166
+ try {
167
+ const repo = await get(root, z.record(z.string(), z.unknown()))
168
+ for (const key of ['squash', 'rebase'] as const) {
169
+ const parsed = z.boolean().safeParse(repo[`allow_${key}_merge`])
170
+ if (parsed.success)
171
+ set(key, parsed.data ? 'pass' : 'fail', `GitHub allow_${key}_merge is ${parsed.data}.`)
172
+ }
173
+ const permissions = z.object({ push: z.boolean() }).safeParse(repo.permissions)
174
+ write = permissions.success ? permissions.data.push : undefined
175
+ const branch = z.string().min(1).safeParse(repo.default_branch)
176
+ defaultRef = branch.success ? `refs/heads/${branch.data}` : undefined
177
+ } catch {
178
+ /* Independent policy reads can still provide useful evidence. */
179
+ }
180
+ if (write === false)
181
+ for (const key of ['build-refs', 'node-refs', 'archive-refs'] as const)
182
+ set(
183
+ key,
184
+ 'fail',
185
+ 'The authenticated forge identity lacks repository push permission; grant Contents:write.',
186
+ )
187
+
188
+ let classic: Classic[] | undefined
189
+ try {
190
+ classic = []
191
+ let cursor: string | null = null
192
+ const seen = new Set<string>()
193
+ for (;;) {
194
+ const response = await request('POST', 'graphql', {
195
+ body: {
196
+ query: `query($owner: String!, $name: String!, $cursor: String) { repository(owner: $owner, name: $name) { branchProtectionRules(first: 100, after: $cursor) { nodes { pattern allowsForcePushes restrictsPushes requiresLinearHistory isAdminEnforced lockBranch blocksCreations requiresApprovingReviews requiresStatusChecks requiresCommitSignatures requiresDeployments bypassForcePushAllowances { totalCount } } pageInfo { hasNextPage endCursor } } } }`,
197
+ variables: { owner: opts.owner, name: opts.name, cursor },
198
+ },
199
+ })
200
+ if (response.status < 200 || response.status >= 300)
201
+ throw new Error('GraphQL inspection failed')
202
+ const envelope = z
203
+ .object({
204
+ errors: z.array(z.unknown()).optional(),
205
+ data: z
206
+ .object({
207
+ repository: z.object({
208
+ branchProtectionRules: z.object({
209
+ nodes: z.array(classicSchema),
210
+ pageInfo: z.object({
211
+ hasNextPage: z.boolean(),
212
+ endCursor: z.string().nullable(),
213
+ }),
214
+ }),
215
+ }),
216
+ })
217
+ .optional(),
218
+ })
219
+ .parse(response.json)
220
+ if (envelope.errors?.length || !envelope.data) throw new Error('Incomplete classic inventory')
221
+ const connection = envelope.data.repository.branchProtectionRules
222
+ classic.push(...connection.nodes)
223
+ if (!connection.pageInfo.hasNextPage) break
224
+ cursor = connection.pageInfo.endCursor
225
+ if (!cursor || seen.has(cursor)) throw new Error('Incomplete classic pagination')
226
+ seen.add(cursor)
227
+ }
228
+ } catch {
229
+ classic = undefined
230
+ }
231
+ let sets: Ruleset[] | undefined
232
+ try {
233
+ const inventory = await pages(
234
+ `${root}/rulesets`,
235
+ z.object({ id: z.number().int(), enforcement: z.enum(['active', 'disabled', 'evaluate']) }),
236
+ { includes_parents: 'true' },
237
+ )
238
+ sets = []
239
+ for (const item of inventory) {
240
+ if (item.enforcement !== 'active') continue
241
+ const detail = await get(`${root}/rulesets/${item.id}`, rulesetSchema, {
242
+ includes_parents: 'true',
243
+ })
244
+ if (detail.enforcement === 'active') sets.push(detail)
245
+ }
246
+ } catch {
247
+ sets = undefined
248
+ }
249
+
250
+ for (const [key, prefix] of [
251
+ ['build-refs', 'refs/heads/ab/'],
252
+ ['node-refs', 'refs/heads/ab-node/'],
253
+ ] as const) {
254
+ if (write === false) continue
255
+ let unknown = write !== true || !classic || !sets || !defaultRef
256
+ let blocked = false
257
+ const details: string[] = []
258
+ if (classic) {
259
+ const overlaps = classic.filter(
260
+ (rule) =>
261
+ patternOverlaps(rule.pattern, prefix.slice(11), defaultRef?.slice(11) ?? '') !== 'no',
262
+ )
263
+ for (const rule of overlaps) {
264
+ const overlap = patternOverlaps(rule.pattern, prefix.slice(11), defaultRef?.slice(11) ?? '')
265
+ if (overlap === 'unknown' || overlaps.length > 1 || rule.restrictsPushes) unknown = true
266
+ else if (!rule.isAdminEnforced || rule.bypassForcePushAllowances.totalCount > 0)
267
+ unknown = true
268
+ else if (!rule.allowsForcePushes || rule.lockBranch) {
269
+ blocked = true
270
+ details.push(
271
+ `Classic protection ${rule.pattern} forbids force pushes or locks publication.`,
272
+ )
273
+ } else if (
274
+ rule.blocksCreations ||
275
+ rule.requiresApprovingReviews ||
276
+ rule.requiresStatusChecks ||
277
+ rule.requiresCommitSignatures ||
278
+ rule.requiresDeployments
279
+ )
280
+ unknown = true
281
+ }
282
+ }
283
+ for (const rule of sets ?? []) {
284
+ const appliesTo = applies(rule, prefix, defaultRef ?? '', true)
285
+ if (appliesTo === 'no') continue
286
+ // Actor/team/app membership is not inferred from repository write access.
287
+ // PR-only bypasses never authorize a direct push.
288
+ const directBypass = rule.bypass_actors?.some((actor) => actor.bypass_mode !== 'pull_request')
289
+ const restrictions = rule.rules.filter(
290
+ (item) => item.type !== 'deletion' && item.type !== 'required_linear_history',
291
+ )
292
+ if (!restrictions.length) continue
293
+ if (appliesTo === 'unknown' || rule.bypass_actors === undefined || directBypass) {
294
+ unknown = true
295
+ continue
296
+ }
297
+ if (
298
+ restrictions.some((item) =>
299
+ ['non_fast_forward', 'update', 'creation', 'pull_request'].includes(item.type),
300
+ )
301
+ ) {
302
+ blocked = true
303
+ details.push(`Active ruleset ${rule.id} restricts direct publication or force pushes.`)
304
+ } else unknown = true // Content-dependent and future rule types cannot prove publication.
305
+ }
306
+ set(
307
+ key,
308
+ blocked ? 'fail' : unknown ? 'unknown' : 'pass',
309
+ blocked
310
+ ? details.join(' ')
311
+ : unknown
312
+ ? `Cannot prove publication and force-push permission throughout ${prefix}. ${access}`
313
+ : `Repository push permission and complete policy inventory permit rewrites throughout ${prefix}.`,
314
+ )
315
+ }
316
+ if (write !== false)
317
+ set(
318
+ 'archive-refs',
319
+ 'unknown',
320
+ `GitHub branch protection APIs do not establish publication permission for non-head refs/autobuild/archive/. ${access} Manually verify this ref domain without creating or overwriting probe archives.`,
321
+ )
322
+
323
+ try {
324
+ // Matching refs returns the complete array and has no pagination parameters.
325
+ // A full response can contain 100+ refs, so the paginated helper would loop.
326
+ const nodes = await get(
327
+ `${root}/git/matching-refs/heads/ab-node/`,
328
+ z.array(z.object({ ref: z.string() })),
329
+ )
330
+ const targets = [
331
+ opts.input.rootBranch,
332
+ ...nodes.map((node) => {
333
+ if (!node.ref.startsWith('refs/heads/ab-node/')) throw new Error('Unexpected target ref')
334
+ return node.ref.slice(11)
335
+ }),
336
+ ]
337
+ let uncertain = !classic || !sets || !defaultRef
338
+ const missing: string[] = []
339
+ let rootFence: boolean | undefined
340
+ for (const branch of new Set(targets)) {
341
+ const active = await pages(`${root}/rules/branches/${encodeURIComponent(branch)}`, ruleSchema)
342
+ const matches = (classic ?? []).filter(
343
+ (rule) => patternMatches(rule.pattern, branch, defaultRef?.slice(11) ?? '') !== 'no',
344
+ )
345
+ if (
346
+ matches.some(
347
+ (rule) => patternMatches(rule.pattern, branch, defaultRef?.slice(11) ?? '') === 'unknown',
348
+ )
349
+ )
350
+ uncertain = true
351
+ let linear = active.some((rule) => rule.type === 'required_linear_history')
352
+ let protection: z.infer<typeof protectionSchema> | undefined
353
+ if (matches.length) {
354
+ protection = await get(
355
+ `${root}/branches/${encodeURIComponent(branch)}/protection`,
356
+ protectionSchema,
357
+ )
358
+ linear ||= protection.required_linear_history.enabled
359
+ }
360
+ if ((matches.length || active.length) && !linear) missing.push(branch)
361
+ if (branch === opts.input.rootBranch && classic && sets && defaultRef) {
362
+ rootFence = !!(
363
+ protection?.enforce_admins.enabled &&
364
+ protection.required_status_checks?.strict &&
365
+ protection.required_status_checks.contexts.length +
366
+ protection.required_status_checks.checks.length >
367
+ 0
368
+ )
369
+ for (const check of active) {
370
+ if (check.type !== 'required_status_checks') continue
371
+ const parameters = z
372
+ .object({
373
+ strict_required_status_checks_policy: z.boolean(),
374
+ required_status_checks: z.array(z.object({ context: z.string() })),
375
+ })
376
+ .safeParse(check.parameters)
377
+ if (!parameters.success) {
378
+ if (rootFence !== true) rootFence = undefined
379
+ continue
380
+ }
381
+ if (
382
+ !parameters.data.strict_required_status_checks_policy ||
383
+ !parameters.data.required_status_checks.length
384
+ )
385
+ continue
386
+ const rule = sets.find((rule) => rule.id === check.ruleset_id)
387
+ if (!rule || rule.bypass_actors === undefined) {
388
+ if (rootFence !== true) rootFence = undefined
389
+ } else if (rule.bypass_actors.length === 0) rootFence = true
390
+ }
391
+ }
392
+ }
393
+ set(
394
+ 'linear-history',
395
+ missing.length ? 'fail' : uncertain ? 'unknown' : 'pass',
396
+ missing.length
397
+ ? `Protected targets missing Require linear history: ${missing.join(', ')}.`
398
+ : uncertain
399
+ ? `Protected target inventory incomplete. ${access}`
400
+ : 'All protected root/node targets require linear history; unprotected targets impose no recommendation.',
401
+ )
402
+ if (rootFence !== undefined)
403
+ set(
404
+ 'root-freshness',
405
+ rootFence ? 'pass' : 'fail',
406
+ rootFence
407
+ ? `Root ${opts.input.rootBranch} enforces strict nonempty checks for all actors: fenced landing.`
408
+ : `Root ${opts.input.rootBranch} does not enforce strict nonempty checks for all actors: best-effort landing.`,
409
+ )
410
+ } catch {
411
+ /* No vacuous success on incomplete target or policy reads. */
412
+ }
413
+ return checks
414
+ }
415
+ const protectionSchema = z.object({
416
+ required_linear_history: z.object({ enabled: z.boolean() }),
417
+ enforce_admins: z.object({ enabled: z.boolean() }),
418
+ required_status_checks: z
419
+ .object({ strict: z.boolean(), contexts: z.array(z.string()), checks: z.array(z.unknown()) })
420
+ .nullable(),
421
+ })