omp-superagent 0.1.7 → 0.1.9

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 (122) hide show
  1. package/DESIGN.md +27 -16
  2. package/README.ko.md +40 -19
  3. package/README.md +43 -18
  4. package/THIRD_PARTY_NOTICES.md +11 -11
  5. package/config.example.json +2 -1
  6. package/docs/OPERATIONS.md +285 -85
  7. package/docs/design/execution.md +133 -24
  8. package/docs/design/messaging.md +235 -50
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.8.md +21 -0
  11. package/docs/releases/0.1.9.md +18 -0
  12. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  13. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  16. package/host-owner/bin/notices/darwin-arm64/Cargo-LICENSES.txt +2 -0
  17. package/host-owner/bin/notices/darwin-arm64/Cargo-SOURCES.txt +2 -0
  18. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  19. package/host-owner/bin/notices/darwin-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  20. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  21. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  22. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  23. package/host-owner/bin/notices/darwin-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  24. package/host-owner/bin/notices/darwin-x64/Cargo-LICENSES.txt +2 -0
  25. package/host-owner/bin/notices/darwin-x64/Cargo-SOURCES.txt +2 -0
  26. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  27. package/host-owner/bin/notices/darwin-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  28. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  29. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  30. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  31. package/host-owner/bin/notices/darwin-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  32. package/host-owner/bin/notices/linux-arm64/Cargo-LICENSES.txt +3 -0
  33. package/host-owner/bin/notices/linux-arm64/Cargo-SOURCES.txt +3 -0
  34. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  35. package/host-owner/bin/notices/linux-arm64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  36. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  37. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  38. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  39. package/host-owner/bin/notices/linux-arm64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  40. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  41. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  42. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  43. package/host-owner/bin/notices/linux-arm64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  44. package/host-owner/bin/notices/linux-x64/Cargo-LICENSES.txt +3 -0
  45. package/host-owner/bin/notices/linux-x64/Cargo-SOURCES.txt +3 -0
  46. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-APACHE +201 -0
  47. package/host-owner/bin/notices/linux-x64/crates/bitflags-2.13.2/LICENSE-MIT +25 -0
  48. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/COPYRIGHT +29 -0
  49. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-APACHE +201 -0
  50. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  51. package/host-owner/bin/notices/linux-x64/crates/linux-raw-sys-0.12.1/LICENSE-MIT +23 -0
  52. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/COPYRIGHT +29 -0
  53. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-APACHE +201 -0
  54. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
  55. package/host-owner/bin/notices/linux-x64/crates/rustix-1.1.6/LICENSE-MIT +23 -0
  56. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  57. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  58. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  59. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  60. package/package.json +17 -15
  61. package/skills/head/SKILL.md +3 -11
  62. package/skills/head/references/routing.md +23 -17
  63. package/skills/head/references/supervision.md +13 -1
  64. package/skills/lane/references/workflow.md +8 -8
  65. package/src/cli.ts +6 -3
  66. package/src/config.ts +5 -0
  67. package/src/contracts.ts +95 -10
  68. package/src/cron-jobs.ts +443 -19
  69. package/src/cron-pr-intake.ts +257 -0
  70. package/src/discord-command-registration.ts +34 -186
  71. package/src/extension.ts +31 -3
  72. package/src/gateway-client.ts +11 -59
  73. package/src/gateway-protocol.ts +35 -1
  74. package/src/head-quota.ts +80 -0
  75. package/src/head-recovery.ts +249 -1
  76. package/src/host-extension.ts +194 -5
  77. package/src/host-protocol.ts +16 -9
  78. package/src/host-sdk-helper.ts +105 -10
  79. package/src/host.ts +111 -29
  80. package/src/installed-omp.ts +116 -4
  81. package/src/lane-models.ts +8 -0
  82. package/src/managed-ulw-probe.ts +22 -20
  83. package/src/managed-ulw.ts +137 -24
  84. package/src/messenger-command-catalog.json +6 -3
  85. package/src/messenger-commands.ts +9 -2
  86. package/src/native-presets.ts +32 -5
  87. package/src/omp-usage.ts +254 -36
  88. package/src/operator.ts +77 -0
  89. package/src/pr-github-schema.ts +2 -0
  90. package/src/pr-github.ts +4 -2
  91. package/src/pr-intake-automation.ts +315 -0
  92. package/src/pr-intake-comment.ts +225 -0
  93. package/src/pr-intake-fix.ts +232 -0
  94. package/src/pr-intake-github.ts +479 -0
  95. package/src/pr-intake-material.ts +229 -0
  96. package/src/pr-intake-mode.ts +59 -0
  97. package/src/pr-intake-review.ts +397 -0
  98. package/src/pr-intake-tree.ts +68 -0
  99. package/src/pr-intake-work.ts +29 -0
  100. package/src/pr-review-models.ts +28 -0
  101. package/src/result-attachment.ts +60 -79
  102. package/src/runtime.ts +2968 -449
  103. package/src/setup-profiles.ts +26 -65
  104. package/src/slack-command-registration.ts +48 -197
  105. package/src/store.ts +507 -87
  106. package/src/superkit-skills.ts +22 -0
  107. package/src/telegram-command-languages.json +17 -0
  108. package/src/telegram-command-registration.ts +32 -134
  109. package/src/topic-history.ts +30 -17
  110. package/src/worker-bridge.ts +21 -0
  111. package/src/worker-enrollment.ts +2 -1
  112. package/src/worker-host.ts +0 -24
  113. package/src/worker-serve-prepare.ts +19 -0
  114. package/src/worker-service.ts +51 -47
  115. package/scripts/ci.ts +0 -44
  116. package/scripts/release.ts +0 -112
  117. package/scripts/test-omp.sh +0 -43
  118. package/src/discord-commands.ts +0 -29
  119. package/src/discord-markdown.ts +0 -172
  120. package/src/slack-commands.ts +0 -18
  121. package/src/telegram-signal.ts +0 -14
  122. package/src/worker-stdio.ts +0 -61
@@ -0,0 +1,479 @@
1
+ import { execFile } from "node:child_process";
2
+ import { Type, type Static, type TSchema } from "@sinclair/typebox/type";
3
+ import { parsePrRef, readGitHubApi } from "./pr-github";
4
+ import { PrReadError, checkPageSchema, loginSchema, pages, parseWire, sha40 as sha, statusSchema } from "./pr-github-schema";
5
+
6
+ // allow: SIZE_OK — One wire adapter; preflight and the single mutation share the authenticated session.
7
+ const id = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });
8
+ const nodeId = Type.String({ pattern: "^[A-Za-z0-9_+/=-]{1,256}$" });
9
+ const utcTimestamp = Type.String({ pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{3})?Z$" });
10
+ const actor = Type.Object({ id, login: loginSchema.properties.login, type: Type.Literal("User") });
11
+ const repoIdentity = Type.Object({ id, full_name: Type.String(), owner: actor });
12
+ const repositorySchema = Type.Composite([repoIdentity, Type.Object({
13
+ archived: Type.Boolean(), disabled: Type.Boolean(), allow_merge_commit: Type.Optional(Type.Boolean()),
14
+ default_branch: Type.String({ minLength: 1 }), permissions: Type.Optional(Type.Object({ push: Type.Boolean() })),
15
+ })]);
16
+ const pullIdentity = Type.Object({
17
+ number: id, head: Type.Object({ sha }),
18
+ base: Type.Object({ repo: repoIdentity, ref: Type.String({ minLength: 1 }), sha }),
19
+ user: Type.Union([Type.Object({
20
+ id, login: Type.String({ pattern: "^[a-zA-Z0-9][a-zA-Z0-9-]*(\\[bot\\])?$", maxLength: 100 }),
21
+ }), Type.Null()]),
22
+ });
23
+ const pullSchema = Type.Composite([pullIdentity, Type.Object({
24
+ state: Type.Union([Type.Literal("open"), Type.Literal("closed")]), created_at: utcTimestamp,
25
+ })]);
26
+ const sourceRepo = Type.Object({ id, full_name: Type.String(), owner: Type.Omit(actor, ["type"]) });
27
+ const detailSchema = Type.Composite([Type.Omit(pullSchema, ["head"]), Type.Object({
28
+ head: Type.Object({
29
+ sha, ref: Type.Optional(Type.String({ minLength: 1 })),
30
+ repo: Type.Optional(Type.Union([sourceRepo, Type.Null()])),
31
+ }),
32
+ node_id: nodeId,
33
+ merged: Type.Boolean(), merge_commit_sha: Type.Union([sha, Type.Null()]), draft: Type.Boolean(),
34
+ mergeable: Type.Union([Type.Boolean(), Type.Null()]), mergeable_state: Type.String(),
35
+ })]);
36
+ const rulesetSummary = Type.Object({
37
+ id, target: Type.Optional(Type.String()), source: Type.String(), source_type: Type.String(), enforcement: Type.String(),
38
+ });
39
+ const ruleSchema = Type.Object({ type: Type.String(), parameters: Type.Optional(Type.Unknown()) });
40
+ const rulesetSchema = Type.Composite([rulesetSummary, Type.Object({
41
+ bypass_actors: Type.Optional(Type.Array(Type.Unknown())),
42
+ conditions: Type.Optional(Type.Object({ ref_name: Type.Optional(Type.Object({
43
+ include: Type.Array(Type.String()), exclude: Type.Array(Type.String()),
44
+ }, { additionalProperties: false })) }, { additionalProperties: false })),
45
+ rules: Type.Array(ruleSchema),
46
+ })]);
47
+ const effectiveRuleSchema = Type.Composite([ruleSchema, Type.Object({
48
+ ruleset_id: id, ruleset_source: Type.String({ minLength: 1 }),
49
+ ruleset_source_type: Type.Union([Type.Literal("Repository"), Type.Literal("Organization"), Type.Literal("Enterprise")]),
50
+ })]);
51
+ const branchSchema = Type.Object({
52
+ name: Type.String(), commit: Type.Object({ sha }), protected: Type.Boolean(),
53
+ protection: Type.Object({
54
+ enabled: Type.Boolean(),
55
+ required_status_checks: Type.Object({ enforcement_level: Type.String(), contexts: Type.Array(Type.String()) }),
56
+ }),
57
+ });
58
+ const reviewRule = Type.Object({
59
+ required_approving_review_count: Type.Integer({ minimum: 1, maximum: 10 }),
60
+ dismiss_stale_reviews_on_push: Type.Literal(true), require_last_push_approval: Type.Literal(true),
61
+ allowed_merge_methods: Type.Optional(Type.Array(Type.String())),
62
+ });
63
+ const statusRule = Type.Object({
64
+ strict_required_status_checks_policy: Type.Boolean(),
65
+ required_status_checks: Type.Array(Type.Object({ context: Type.String({ minLength: 1 }), integration_id: id }), { minItems: 1 }),
66
+ });
67
+ const reviewSchema = Type.Object({
68
+ id, user: Type.Union([Type.Object({ id }), Type.Null()]), submitted_at: Type.Union([Type.String(), Type.Null()]),
69
+ commit_id: Type.Union([sha, Type.Null()]), state: Type.Union(
70
+ (["APPROVED", "CHANGES_REQUESTED", "COMMENTED", "DISMISSED", "PENDING"] as const).map(value => Type.Literal(value))),
71
+ });
72
+ const checksSchema = Type.Object({
73
+ total_count: checkPageSchema.properties.total_count,
74
+ check_runs: Type.Array(Type.Intersect([checkPageSchema.properties.check_runs.items, Type.Object({
75
+ app: Type.Union([Type.Object({ id }), Type.Null()]),
76
+ })])),
77
+ });
78
+ const statusesSchema = Type.Object({
79
+ sha, state: statusSchema.properties.state, total_count: Type.Integer({ minimum: 0 }),
80
+ statuses: Type.Array(statusSchema),
81
+ });
82
+ const receiptSchema = Type.Object({
83
+ errors: Type.Optional(Type.Array(Type.Unknown(), { maxItems: 0 })),
84
+ data: Type.Object({ mergePullRequest: Type.Object({ pullRequest: Type.Object({
85
+ id: nodeId, headRefOid: sha, baseRefName: Type.String(), merged: Type.Literal(true), state: Type.Literal("MERGED"),
86
+ headRefName: Type.Optional(Type.String()),
87
+ headRepository: Type.Optional(Type.Union([Type.Object({ databaseId: id }), Type.Null()])),
88
+ mergeCommit: Type.Object({ oid: sha, parents: Type.Object({
89
+ totalCount: Type.Literal(2), nodes: Type.Array(Type.Object({ oid: sha }), { minItems: 2, maxItems: 2 }),
90
+ }) }),
91
+ }) }) }),
92
+ });
93
+ const commitSchema = Type.Object({ sha, parents: Type.Array(Type.Object({ sha })) });
94
+ const mergeMutation = `mutation MergeIntakePull($input: MergePullRequestInput!) {
95
+ mergePullRequest(input: $input) {
96
+ pullRequest {
97
+ id headRefOid headRefName headRepository { databaseId } baseRefName merged state
98
+ mergeCommit { oid parents(first: 2) { totalCount nodes { oid } } }
99
+ }
100
+ }
101
+ }`;
102
+
103
+ export type IntakeRepositoryIdentity = { readonly repositoryId: number; readonly ownerId: number };
104
+ type ReviewedBase = { readonly baseRef: string; readonly baseSha: string };
105
+ export type IntakeMergeIdentity = IntakeRepositoryIdentity & ReviewedBase;
106
+ export type IntakePull = {
107
+ readonly number: number; readonly head: string; readonly author: string; readonly createdAt: number;
108
+ };
109
+ type Blocked = { readonly status: "blocked"; readonly reason: string };
110
+ type Merged = { readonly status: "merged"; readonly sha: string };
111
+ type MergeTarget = { readonly status: "ready"; readonly nodeId: string; readonly excludedHead: string | null };
112
+ export type IntakeMergeStatus = Blocked | Merged | { readonly status: "ready" };
113
+ export type IntakeMergeResult = Blocked | Merged | { readonly status: "unknown"; readonly reason: string };
114
+
115
+ type Session = {
116
+ readonly repository: string; readonly root: string; readonly owner: string;
117
+ readonly env: NodeJS.ProcessEnv;
118
+ readonly get: <T extends TSchema>(endpoint: string, schema: T) => Promise<Static<T>>;
119
+ };
120
+ type IntakeTarget = {
121
+ readonly number: number; readonly head: string; readonly identity: IntakeRepositoryIdentity;
122
+ readonly base?: ReviewedBase;
123
+ };
124
+ type WireRepo = Static<typeof repositorySchema>;
125
+ type Pull = Static<typeof detailSchema>;
126
+ type RequiredCheck = { readonly context: string; readonly app: number };
127
+ type GatePolicy = {
128
+ readonly rulesetId: number; readonly approvals: number; readonly required: readonly RequiredCheck[];
129
+ readonly excludedHead: string | null;
130
+ };
131
+ const blocked = (reason: string): Blocked => ({ status: "blocked", reason });
132
+
133
+ async function openSession(repository: string, signal: AbortSignal): Promise<Session> {
134
+ const { owner, repo } = parsePrRef(`${repository}#1`);
135
+ if (signal.aborted) throw new PrReadError("aborted");
136
+ const env = { ...process.env, GH_PROMPT_DISABLED: "1", GH_PAGER: "cat", GH_DEBUG: "" };
137
+ const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN || await new Promise<string>((resolve, reject) => {
138
+ execFile("gh", ["auth", "token", "--hostname", "github.com"],
139
+ { env, signal, encoding: "utf8", timeout: 30_000, maxBuffer: 4096 }, (error, stdout) => {
140
+ if (error) reject(new PrReadError(signal.aborted ? "aborted" : "request"));
141
+ else resolve(stdout.trimEnd());
142
+ });
143
+ });
144
+ if (!/^[\x21-\x7e]+$/.test(token)) throw new PrReadError("response");
145
+ const pinned = { ...env, GH_TOKEN: token };
146
+ return {
147
+ repository: `${owner}/${repo}`, owner, root: `repos/${owner}/${repo}`, env: pinned,
148
+ get: (endpoint, schema) => readGitHubApi(endpoint, schema, signal, pinned),
149
+ };
150
+ }
151
+
152
+ export { openSession as openIntakeGitHubSession };
153
+
154
+ export function queryIntakeGitHub<T extends TSchema>(
155
+ session: Session, signal: AbortSignal, request: { readonly query: string; readonly variables: object; readonly schema: T },
156
+ ): Promise<Static<T>> {
157
+ if (signal.aborted) return Promise.reject(new PrReadError("aborted"));
158
+ return new Promise<string>((resolve, reject) => {
159
+ const child = execFile("gh", ["api", "--hostname", "github.com", "--method", "POST",
160
+ "--header", "Accept: application/vnd.github+json", "--header", "Content-Type: application/json",
161
+ "--input", "-", "graphql"],
162
+ { env: session.env, signal, encoding: "utf8", timeout: 30_000, maxBuffer: 1024 * 1024 }, (error, stdout) => {
163
+ if (error || signal.aborted) reject(new PrReadError(signal.aborted ? "aborted" : "request"));
164
+ else resolve(stdout);
165
+ });
166
+ child.stdin?.once("error", () => reject(new PrReadError("request")));
167
+ child.stdin?.end(JSON.stringify({ query: request.query, variables: request.variables }));
168
+ }).then(text => parseWire(request.schema, text));
169
+ }
170
+
171
+ async function one<T extends TSchema>(session: Session, endpoint: string, schema: T): Promise<Static<T>> {
172
+ const result = await session.get(endpoint, Type.Array(schema, { minItems: 1, maxItems: 1 }));
173
+ return result[0];
174
+ }
175
+
176
+ async function readOwnedRepo(session: Session): Promise<WireRepo> {
177
+ const self = await one(session, "user", actor);
178
+ if (self.login.toLowerCase() !== session.owner) throw new PrReadError("reference");
179
+ const repo = await one(session, session.root, repositorySchema);
180
+ if (repo.full_name.toLowerCase() !== session.repository || repo.owner.login.toLowerCase() !== session.owner
181
+ || repo.owner.id !== self.id) throw new PrReadError("response");
182
+ return repo;
183
+ }
184
+
185
+ function sameRepo(repo: Static<typeof sourceRepo>, expected: WireRepo): boolean {
186
+ return repo.id === expected.id && repo.full_name.toLowerCase() === expected.full_name.toLowerCase()
187
+ && repo.owner.id === expected.owner.id && repo.owner.login.toLowerCase() === expected.owner.login.toLowerCase();
188
+ }
189
+
190
+ function ownedAuthor(user: NonNullable<Pull["user"]>, repo: WireRepo): boolean {
191
+ return user.id === repo.owner.id || user.login.toLowerCase() === repo.owner.login.toLowerCase();
192
+ }
193
+
194
+ export async function readIntakePulls(repository: string, signal: AbortSignal): Promise<IntakeRepositoryIdentity & {
195
+ readonly self: string; readonly pulls: readonly IntakePull[];
196
+ }> {
197
+ const session = await openSession(repository, signal);
198
+ const repo = await readOwnedRepo(session);
199
+ const rows = (await session.get(`${session.root}/pulls?state=open&per_page=100`, pages(Type.Array(pullSchema)))).flat();
200
+ const numbers = new Set<number>();
201
+ const pulls: IntakePull[] = [];
202
+ for (const row of rows) {
203
+ const createdAt = Date.parse(row.created_at);
204
+ const timestamp = row.created_at.includes(".") ? row.created_at : row.created_at.replace(/Z$/, ".000Z");
205
+ if (row.state !== "open" || !sameRepo(row.base.repo, repo) || numbers.has(row.number)
206
+ || !Number.isFinite(createdAt) || new Date(createdAt).toISOString() !== timestamp)
207
+ throw new PrReadError("response");
208
+ numbers.add(row.number);
209
+ if (row.user && !ownedAuthor(row.user, repo))
210
+ pulls.push({ number: row.number, head: row.head.sha, author: row.user.login.toLowerCase(), createdAt });
211
+ }
212
+ if (!sameRepo(await readOwnedRepo(session), repo)) throw new PrReadError("changed");
213
+ return { repositoryId: repo.id, ownerId: repo.owner.id, self: session.owner, pulls };
214
+ }
215
+
216
+ const applicableRuleset = (row: Static<typeof rulesetSummary>, session: Session): boolean =>
217
+ row.target === "branch" && row.enforcement === "active" && row.source_type === "Repository"
218
+ && row.source.toLowerCase() === session.repository;
219
+
220
+ function requiredChecks(ci: Static<typeof statusRule>): RequiredCheck[] {
221
+ return ci.required_status_checks.map(check => ({ context: check.context, app: check.integration_id }))
222
+ .sort((a, b) => a.context.localeCompare(b.context) || a.app - b.app);
223
+ }
224
+
225
+ async function readPolicy(session: Session, rulesetId: number, sourceRef: string | null): Promise<GatePolicy | null> {
226
+ const policy = await one(session, `${session.root}/rulesets/${rulesetId}`, rulesetSchema);
227
+ const refs = policy.conditions?.ref_name;
228
+ // mergePullRequest compares the head OID, not the base ref/OID. A base-scoped
229
+ // rule leaves a retarget race to an unprotected branch. The only safe exclusion
230
+ // is the same-repo PR's immutable source ref: it cannot merge into itself.
231
+ if (policy.id !== rulesetId || !applicableRuleset(policy, session) || policy.bypass_actors?.length !== 0
232
+ || refs?.include.length !== 1 || refs.include[0] !== "~ALL") return null;
233
+ const excludedHead = refs.exclude.length === 1 && sourceRef && refs.exclude[0] === `refs/heads/${sourceRef}` ? sourceRef : null;
234
+ if (refs.exclude.length !== 0 && excludedHead === null) return null;
235
+ const reviews = policy.rules.filter(rule => rule.type === "pull_request");
236
+ const statuses = policy.rules.filter(rule => rule.type === "required_status_checks");
237
+ if (reviews.length !== 1 || statuses.length !== 1) return null;
238
+ const review = parseWire(reviewRule, JSON.stringify(reviews[0].parameters ?? null));
239
+ const ci = parseWire(statusRule, JSON.stringify(statuses[0].parameters ?? null));
240
+ if (!ci.strict_required_status_checks_policy || (review.allowed_merge_methods && !review.allowed_merge_methods.includes("merge")))
241
+ return null;
242
+ const required = requiredChecks(ci);
243
+ if (new Set(required.map(check => check.context)).size !== required.length) return null;
244
+ return { rulesetId, approvals: review.required_approving_review_count, required, excludedHead };
245
+ }
246
+
247
+ const nonCiRules = new Set([
248
+ "creation", "update", "deletion", "required_linear_history", "required_signatures", "pull_request",
249
+ "non_fast_forward", "commit_message_pattern", "commit_author_email_pattern", "committer_email_pattern", "branch_name_pattern",
250
+ ]);
251
+
252
+ async function readEffectiveChecks(session: Session, base: Pull["base"], gate: GatePolicy): Promise<RequiredCheck[] | null> {
253
+ const branchName = encodeURIComponent(base.ref);
254
+ const branch = await one(session, `${session.root}/branches/${branchName}`, branchSchema);
255
+ const classic = branch.protection.required_status_checks;
256
+ // The effective rules endpoint returns rulesets, not independent classic status-check requirements.
257
+ if (branch.name !== base.ref || branch.commit.sha !== base.sha || !branch.protected
258
+ || classic.enforcement_level !== "off" || classic.contexts.length !== 0) return null;
259
+ const effective = (await session.get(`${session.root}/rules/branches/${branchName}?per_page=100`, pages(Type.Array(effectiveRuleSchema)))).flat();
260
+ const statusRules = new Set<number>();
261
+ const required = new Map<string, RequiredCheck>();
262
+ let gateReview: boolean | null = null;
263
+ let gateCi = false;
264
+ for (const rule of effective) {
265
+ const isGate = rule.ruleset_id === gate.rulesetId;
266
+ if (isGate && (rule.ruleset_source_type !== "Repository" || rule.ruleset_source.toLowerCase() !== session.repository))
267
+ return null;
268
+ if (rule.type === "required_status_checks") {
269
+ if (statusRules.has(rule.ruleset_id)) return null;
270
+ statusRules.add(rule.ruleset_id);
271
+ const ci = parseWire(statusRule, JSON.stringify(rule.parameters ?? null));
272
+ const checks = requiredChecks(ci);
273
+ if (isGate) gateCi = ci.strict_required_status_checks_policy && JSON.stringify(checks) === JSON.stringify(gate.required);
274
+ for (const check of checks) required.set(JSON.stringify([check.context, check.app]), check);
275
+ } else if (!nonCiRules.has(rule.type)) return null;
276
+ else if (isGate && rule.type === "pull_request") {
277
+ if (gateReview !== null) return null;
278
+ const review = parseWire(reviewRule, JSON.stringify(rule.parameters ?? null));
279
+ gateReview = review.required_approving_review_count === gate.approvals
280
+ && (!review.allowed_merge_methods || review.allowed_merge_methods.includes("merge"));
281
+ }
282
+ }
283
+ if (!gateReview || !gateCi) return null;
284
+ return [...required.values()].sort((a, b) => a.context.localeCompare(b.context) || a.app - b.app);
285
+ }
286
+
287
+ async function hasReviews(session: Session, item: { readonly endpoint: string; readonly pull: Pull }, count: number) {
288
+ const { endpoint, pull } = item;
289
+ const reviews = (await session.get(`${endpoint}/reviews?per_page=100`, pages(Type.Array(reviewSchema)))).flat();
290
+ if (new Set(reviews.map(review => review.id)).size !== reviews.length) throw new PrReadError("response");
291
+ const latest = new Map<number, { review: (typeof reviews)[number]; at: number }>();
292
+ for (const review of reviews) {
293
+ if (review.state === "PENDING" || review.state === "COMMENTED") continue;
294
+ if (!review.user || !review.submitted_at) return false;
295
+ const at = Date.parse(review.submitted_at);
296
+ if (!Number.isFinite(at)) return false;
297
+ const previous = latest.get(review.user.id);
298
+ // REST lists reviews in chronological order; a later dismissal must never count as an approval.
299
+ if (previous && at < previous.at) return false;
300
+ latest.set(review.user.id, { review, at });
301
+ }
302
+ const votes = [...latest.values()].map(vote => vote.review);
303
+ return !votes.some(review => review.state === "CHANGES_REQUESTED")
304
+ && votes.filter(review => review.state === "APPROVED" && review.commit_id === pull.head.sha
305
+ && review.user?.id !== pull.user?.id).length >= count;
306
+ }
307
+
308
+ async function hasCurrentCi(session: Session, head: string, required: readonly RequiredCheck[]): Promise<boolean> {
309
+ const commit = `${session.root}/commits/${head}`;
310
+ const checks = await session.get(`${commit}/check-runs?per_page=100&filter=latest`, pages(checksSchema));
311
+ const statuses = await session.get(`${commit}/status?per_page=100`, pages(statusesSchema));
312
+ const runs = checks.flatMap(page => page.check_runs);
313
+ const contexts = statuses.flatMap(page => page.statuses);
314
+ if (checks.some(page => page.total_count !== runs.length)
315
+ || new Set(runs.map(run => run.id)).size !== runs.length || runs.some(run => run.head_sha !== head)
316
+ || statuses.some(page => page.sha !== head || page.total_count !== contexts.length
317
+ || (contexts.length > 0 && page.state !== "success"))
318
+ || new Set(contexts.map(status => status.context)).size !== contexts.length
319
+ || contexts.some(status => status.state !== "success")) return false;
320
+ if (runs.some(run => run.status !== "completed" || run.conclusion !== "success")) return false;
321
+ const now = Date.now();
322
+ return required.every(check => {
323
+ const matches = runs.filter(run => run.name === check.context && run.app?.id === check.app);
324
+ const run = matches[0];
325
+ if (matches.length !== 1 || run?.conclusion !== "success" || run.completed_at === null) return false;
326
+ const finished = Date.parse(run.completed_at);
327
+ return finished <= now && now - finished <= 7 * 24 * 60 * 60 * 1000;
328
+ });
329
+ }
330
+
331
+ function readyPull(pull: Pull, repo: WireRepo): boolean {
332
+ return pull.state === "open" && !pull.merged && !pull.draft && !!pull.user && !ownedAuthor(pull.user, repo)
333
+ && pull.base.ref === repo.default_branch
334
+ && pull.mergeable === true && pull.mergeable_state === "clean";
335
+ }
336
+
337
+ function allowsMerge(repo: WireRepo): boolean {
338
+ return !repo.archived && !repo.disabled && repo.permissions?.push === true && repo.allow_merge_commit === true;
339
+ }
340
+
341
+ function literalSameRepoHead(pull: Pull, repo: WireRepo): string | null {
342
+ const { ref, repo: headRepo } = pull.head;
343
+ // No fnmatch syntax, escaping, special tokens, or a fork's like-named branch.
344
+ return ref && headRepo && ref !== pull.base.ref && /^[A-Za-z0-9][A-Za-z0-9/_.-]{0,149}$/.test(ref)
345
+ && sameRepo(headRepo, repo) ? ref : null;
346
+ }
347
+
348
+ async function preflight(session: Session, ref: IntakeTarget): Promise<MergeTarget | Blocked | Merged> {
349
+ const endpoint = `${session.root}/pulls/${ref.number}`;
350
+ const repo = await readOwnedRepo(session);
351
+ if (repo.id !== ref.identity.repositoryId || repo.owner.id !== ref.identity.ownerId)
352
+ return blocked("GitHub repository or owner does not match enrollment.");
353
+ const start = await one(session, endpoint, detailSchema);
354
+ if (start.number !== ref.number || !sameRepo(start.base.repo, repo) || start.head.sha !== ref.head)
355
+ return blocked("GitHub PR identity or reviewed head does not match.");
356
+ if (!start.user || ownedAuthor(start.user, repo)) return blocked("GitHub does not establish independent PR authorship.");
357
+ if (start.merged && start.state === "closed" && start.merge_commit_sha) {
358
+ if (start.base.ref !== (ref.base?.baseRef ?? repo.default_branch))
359
+ return blocked("GitHub merged PR does not match the expected base branch.");
360
+ const commit = await one(session, `${session.root}/git/commits/${start.merge_commit_sha}`, commitSchema);
361
+ return commit.sha === start.merge_commit_sha && commit.parents.length === 2 && commit.parents[1]?.sha === ref.head
362
+ && (!ref.base || commit.parents[0]?.sha === ref.base.baseSha)
363
+ ? { status: "merged", sha: commit.sha }
364
+ : blocked("GitHub does not establish an ordinary merge commit for the reviewed target.");
365
+ }
366
+ if (!readyPull(start, repo)) return blocked("GitHub does not report a clean, open PR targeting the default branch.");
367
+ if (ref.base && (start.base.ref !== ref.base.baseRef || start.base.sha !== ref.base.baseSha))
368
+ return blocked("GitHub base branch or tip does not match the reviewed base.");
369
+ if (!allowsMerge(repo)) return blocked("Repository does not establish permission for an ordinary merge commit.");
370
+
371
+ const candidates = (await session.get(`${session.root}/rulesets?per_page=100`, pages(Type.Array(rulesetSummary)))).flat()
372
+ .filter(row => applicableRuleset(row, session));
373
+ if (new Set(candidates.map(row => row.id)).size !== candidates.length) throw new PrReadError("response");
374
+ // A wildcard classic branch reading or a boolean `protected` flag cannot prove the retargeted branch is protected.
375
+ let policy: GatePolicy | null = null;
376
+ const sourceRef = literalSameRepoHead(start, repo);
377
+ for (const candidate of candidates) {
378
+ policy = await readPolicy(session, candidate.id, sourceRef);
379
+ if (policy) break;
380
+ }
381
+ if (!policy) return blocked("No non-bypassable review and CI ruleset protects every possible merge destination. "
382
+ + "GitHub's merge API cannot pin the base; only the exact same-repository source branch may be excluded.");
383
+ const required = await readEffectiveChecks(session, start.base, policy);
384
+ if (!required) return blocked("Complete effective GitHub CI rules could not be established.");
385
+ if (!await hasReviews(session, { endpoint, pull: start }, policy.approvals))
386
+ return blocked("Required independent reviews are not established for the reviewed head.");
387
+ if (!await hasCurrentCi(session, ref.head, required))
388
+ return blocked("Complete, current, successful CI from the required sources is not established for the reviewed head.");
389
+ const confirmedPolicy = await readPolicy(session, policy.rulesetId, sourceRef);
390
+ if (JSON.stringify(confirmedPolicy) !== JSON.stringify(policy)) return blocked("GitHub protection changed during preflight.");
391
+ const confirmedRequired = await readEffectiveChecks(session, start.base, policy);
392
+ if (JSON.stringify(confirmedRequired) !== JSON.stringify(required)) return blocked("GitHub effective CI rules changed during preflight.");
393
+ if (!await hasCurrentCi(session, ref.head, required)) return blocked("GitHub CI changed during preflight.");
394
+ const confirmedRepo = await one(session, session.root, repositorySchema);
395
+ if (!sameRepo(confirmedRepo, repo) || confirmedRepo.default_branch !== repo.default_branch || !allowsMerge(confirmedRepo))
396
+ return blocked("GitHub repository identity or merge permission changed during preflight.");
397
+ const end = await one(session, endpoint, detailSchema);
398
+ if (end.number !== ref.number || !sameRepo(end.base.repo, repo) || end.head.sha !== ref.head
399
+ || end.node_id !== start.node_id || end.user?.id !== start.user?.id
400
+ || end.base.ref !== start.base.ref || end.base.sha !== start.base.sha
401
+ || (policy.excludedHead !== null && literalSameRepoHead(end, repo) !== policy.excludedHead)
402
+ || !readyPull(end, repo)) return blocked("GitHub PR changed during preflight.");
403
+ return { status: "ready", nodeId: end.node_id, excludedHead: policy.excludedHead };
404
+ }
405
+
406
+ async function prepare(repository: string, ref: IntakeTarget, signal: AbortSignal): Promise<
407
+ (MergeTarget & { readonly session: Session }) | Blocked | Merged
408
+ > {
409
+ try {
410
+ parsePrRef(`${repository}#${ref.number}`);
411
+ parseWire(sha, JSON.stringify(ref.head));
412
+ if (ref.base) parseWire(sha, JSON.stringify(ref.base.baseSha));
413
+ const session = await openSession(repository, signal);
414
+ const status = await preflight(session, ref);
415
+ return status.status === "ready" ? { ...status, session } : status;
416
+ } catch (error) {
417
+ if (!(error instanceof PrReadError)) throw error;
418
+ return blocked(error.reason === "aborted" ? "GitHub preflight was cancelled."
419
+ : "GitHub repository ownership or merge preflight evidence could not be established.");
420
+ }
421
+ }
422
+
423
+ /** Also reconciles an ambiguous write: only an observed merge of this exact head is a receipt. */
424
+ export async function inspectIntakeMerge(
425
+ repository: string, number: number, head: string, signal: AbortSignal,
426
+ identity: IntakeRepositoryIdentity | IntakeMergeIdentity,
427
+ ): Promise<IntakeMergeStatus> {
428
+ const status = await prepare(repository, { number, head, identity, ...("baseRef" in identity ? { base: identity } : {}) }, signal);
429
+ return status.status === "ready" ? { status: "ready" } : status;
430
+ }
431
+
432
+ /** An ordinary, SHA-conditional merge; callers must fence once and never resubmit an unknown outcome. */
433
+ export async function mergeIntakePull(
434
+ repository: string, number: number, head: string, signal: AbortSignal, beforeWrite: () => void, identity: IntakeMergeIdentity,
435
+ ): Promise<IntakeMergeResult> {
436
+ const base = { baseRef: identity.baseRef, baseSha: identity.baseSha };
437
+ const result = await prepare(repository, { number, head, identity, base }, signal);
438
+ if (result.status !== "ready") return result;
439
+ if (signal.aborted) return blocked("GitHub merge was cancelled before writing.");
440
+ const { env } = result.session;
441
+ const body = JSON.stringify({
442
+ query: mergeMutation,
443
+ variables: { input: { pullRequestId: result.nodeId, expectedHeadOid: head, mergeMethod: "MERGE" } },
444
+ });
445
+ beforeWrite();
446
+ // The immutable PR node cannot be replaced by reassigning the slug. GitHub compares the head
447
+ // and enforces current rules, but the API cannot compare-and-set those rules or the base ref.
448
+ const response = await new Promise<{ readonly failed: boolean; readonly stdout: string }>(resolve => {
449
+ let inputFailed = false;
450
+ const child = execFile("gh", ["api", "--hostname", "github.com", "--method", "POST", "--include",
451
+ "--header", "Accept: application/vnd.github+json", "--header", "Content-Type: application/json",
452
+ "--input", "-", "graphql"],
453
+ { env, signal, encoding: "utf8", timeout: 30_000, maxBuffer: 1024 * 1024 },
454
+ (error, stdout) => resolve({ failed: error !== null || inputFailed, stdout }));
455
+ child.stdin?.once("error", () => { inputFailed = true; });
456
+ child.stdin?.end(body);
457
+ });
458
+ const status = /^HTTP\/[0-9.]+ ([0-9]{3})[^\r\n]*\r?\n/.exec(response.stdout)?.[1];
459
+ if (!signal.aborted && response.failed && status && ["401", "403", "404", "405", "409", "422"].includes(status))
460
+ return blocked("GitHub refused the conditional merge.");
461
+ if (!signal.aborted && !response.failed && status === "200") {
462
+ const separator = /\r?\n\r?\n/.exec(response.stdout);
463
+ if (separator) {
464
+ try {
465
+ const receipt = parseWire(receiptSchema, response.stdout.slice(separator.index + separator[0].length));
466
+ const pull = receipt.data.mergePullRequest.pullRequest;
467
+ const parents = pull.mergeCommit.parents.nodes;
468
+ if (pull.id === result.nodeId && pull.headRefOid === head && pull.baseRefName === base.baseRef
469
+ && (result.excludedHead === null
470
+ || (pull.headRefName === result.excludedHead && pull.headRepository?.databaseId === identity.repositoryId))
471
+ && parents[0]?.oid === base.baseSha && parents[1]?.oid === head)
472
+ return { status: "merged", sha: pull.mergeCommit.oid };
473
+ } catch (error) {
474
+ if (!(error instanceof PrReadError)) throw error;
475
+ }
476
+ }
477
+ }
478
+ return { status: "unknown", reason: "GitHub merge outcome is unconfirmed; reconcile without resubmitting." };
479
+ }