@jagreehal/shepherd 0.15.0 → 0.16.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 (81) hide show
  1. package/AGENTS.md +3 -3
  2. package/README.md +40 -27
  3. package/THIRD_PARTY_NOTICES.md +2 -0
  4. package/gate/.shepherd/gate.schema.json +647 -0
  5. package/gate/.shepherd/gate.yml +122 -0
  6. package/gate/.shepherd/review-guidance.md +95 -0
  7. package/gate/src/actions.ts +32 -0
  8. package/gate/src/cli.ts +1028 -0
  9. package/gate/src/config.ts +102 -0
  10. package/gate/src/delta.ts +29 -0
  11. package/gate/src/env.ts +30 -0
  12. package/gate/src/eval.ts +288 -0
  13. package/gate/src/familiarity.ts +461 -0
  14. package/gate/src/github.ts +761 -0
  15. package/gate/src/inline.ts +59 -0
  16. package/gate/src/isolated-cli.ts +281 -0
  17. package/gate/src/leads.ts +257 -0
  18. package/gate/src/llm.ts +606 -0
  19. package/gate/src/notify.ts +57 -0
  20. package/gate/src/policy.ts +1297 -0
  21. package/gate/src/provider-errors.ts +80 -0
  22. package/gate/src/retention.ts +86 -0
  23. package/gate/src/reviewer.ts +739 -0
  24. package/gate/src/signals.ts +105 -0
  25. package/gate/src/smoke-live.ts +64 -0
  26. package/gate/src/stack.ts +87 -0
  27. package/gate/src/stories.ts +297 -0
  28. package/gate/templates/policy-strict.yml +127 -0
  29. package/gate/templates/reviewer.Dockerfile +8 -0
  30. package/gate/templates/rules/observability/SKILL.md +33 -0
  31. package/gate/templates/shepherd-gate-actions.yml +35 -0
  32. package/gate/templates/shepherd-gate-edited.yml +29 -0
  33. package/gate/templates/shepherd-gate.yml +111 -0
  34. package/lenses/dotnet/SKILL.md +1 -1
  35. package/lenses/go/SKILL.md +1 -1
  36. package/lenses/java/SKILL.md +1 -1
  37. package/lenses/nextjs/SKILL.md +1 -1
  38. package/lenses/node-api/SKILL.md +1 -1
  39. package/lenses/nx-monorepo/SKILL.md +1 -1
  40. package/lenses/observability/SKILL.md +1 -1
  41. package/lenses/owasp-asvs/SKILL.md +1 -1
  42. package/lenses/owasp-llm/SKILL.md +1 -1
  43. package/lenses/pstack/SKILL.md +1 -1
  44. package/lenses/python/SKILL.md +1 -1
  45. package/lenses/react/SKILL.md +1 -1
  46. package/lenses/rust/SKILL.md +1 -1
  47. package/package.json +20 -6
  48. package/schema/config.json +1 -1
  49. package/skills/branch-review/SKILL.md +123 -0
  50. package/skills/ci-repair/SKILL.md +79 -35
  51. package/skills/garden/SKILL.md +8 -8
  52. package/skills/garden/references/telemetry.md +4 -4
  53. package/skills/incident/SKILL.md +9 -9
  54. package/skills/lens-import/SKILL.md +7 -7
  55. package/skills/review-slop/SKILL.md +1 -1
  56. package/skills/shepherd/SKILL.md +43 -41
  57. package/skills/shepherd/references/degradation.md +3 -3
  58. package/skills/shepherd/references/dispatch.md +1 -1
  59. package/skills/shepherd/references/formats.md +5 -5
  60. package/skills/shepherd/references/models.md +2 -2
  61. package/skills/shepherd/references/policy.md +9 -9
  62. package/skills/swarm/SKILL.md +21 -17
  63. package/skills/swarm/references/custom-lenses.md +2 -2
  64. package/skills/swarm/references/formats.md +1 -1
  65. package/skills/triage/SKILL.md +10 -10
  66. package/src/bin.ts +10 -0
  67. package/src/cli.ts +283 -41
  68. package/src/config.ts +26 -25
  69. package/src/doctor.ts +31 -18
  70. package/src/garden-traces.ts +13 -13
  71. package/src/garden.ts +4 -4
  72. package/src/lens.ts +19 -7
  73. package/src/setup.ts +72 -0
  74. package/src/stack.ts +2 -2
  75. package/src/status.ts +80 -0
  76. package/src/summary.ts +52 -9
  77. package/src/trace.ts +4 -4
  78. package/src/working.ts +30 -0
  79. package/templates/shepherd-audit.yml +7 -15
  80. package/templates/shepherd-incident.yml +7 -12
  81. package/templates/shepherd.yml +39 -40
@@ -0,0 +1,761 @@
1
+ // GitHub I/O through the `gh` CLI. Fetch on one side, post the verdict on the other.
2
+ // Every response is parsed against a schema at this boundary, so a shape change in the API
3
+ // fails here with a message, not three functions later as an undefined property.
4
+ import { execFileSync } from "node:child_process";
5
+ import { z } from "zod";
6
+ import { AUTOMATED_HEADER, CARD_MARKER, renderCard } from "./actions.ts";
7
+ import type { Anchored } from "./inline.ts";
8
+ import type { PRFile } from "./policy.ts";
9
+
10
+ // A hung call must fail rather than wait for the job to be killed: a killed run skips every catch,
11
+ // including the one that falls through to dismissing a stale approval.
12
+ const CALL_TIMEOUT_MS = 5 * 60_000;
13
+
14
+ let deadline: number | null = null;
15
+
16
+ /** Milliseconds the next gh or git call may take: the per-call cap, or what is left of an active budget. */
17
+ export function callTimeout(): number {
18
+ if (deadline === null) return CALL_TIMEOUT_MS;
19
+ const left = deadline - Date.now();
20
+
21
+ if (left <= 0) throw Object.assign(new Error("time budget exhausted"), { code: "ETIMEDOUT" });
22
+
23
+ return Math.min(left, CALL_TIMEOUT_MS);
24
+ }
25
+
26
+ /** A call killed by its timeout, or an exhausted budget. A catch that reads failure as "absent" must rethrow it. */
27
+ export const TimedOut = z.object({ code: z.literal("ETIMEDOUT") });
28
+
29
+ /** Run `fn` with every gh and git call inside it sharing one budget of `ms`. */
30
+ export function withBudget<T>(ms: number, fn: () => T): T {
31
+ deadline = Date.now() + ms;
32
+
33
+ try {
34
+ return fn();
35
+ } finally {
36
+ deadline = null;
37
+ }
38
+ }
39
+
40
+ /** Runs `fn`, and again after each delay while the error is `transient`. The last error propagates. */
41
+ export function retrying<T>(delays: number[], transient: (e: Error) => boolean, fn: () => T, wait: (ms: number) => void = Bun.sleepSync): T {
42
+ for (let attempt = 0; ; attempt++) {
43
+ try {
44
+ return fn();
45
+ } catch (e) {
46
+ const delay = delays[attempt];
47
+
48
+ if (delay === undefined || !(e instanceof Error) || !transient(e)) throw e;
49
+ console.error(`retrying in ${delay}ms: ${e.message.split("\n").at(-2) ?? e.message}`);
50
+ wait(delay);
51
+ }
52
+ }
53
+ }
54
+
55
+ /** A GitHub 5xx or a dropped connection. A 4xx is an answer, and a call killed by its timeout has used its time. */
56
+ export const transientGh = (e: Error) => /HTTP 5\d\d|ECONNRESET|connection reset|i\/o timeout|TLS handshake timeout|unexpected EOF/i.test(e.message);
57
+
58
+ // GitHub's generic 422 on `POST .../reviews`: it names no field, and the same request goes through on a retry.
59
+ export const transientReviewError = (e: Error) => /internal error occurred, please try again/i.test(e.message);
60
+
61
+ const READ_DELAYS_MS = [500, 2000];
62
+
63
+ const REVIEW_DELAYS_MS = [1000, 3000];
64
+
65
+ // A POST may already have landed, so it runs once. The other calls repeat safely.
66
+ const gh = (args: string[], cwd: string, input?: string) =>
67
+ retrying(args.includes("POST") ? [] : READ_DELAYS_MS, transientGh, () => execFileSync("gh", args, { cwd, encoding: "utf8", maxBuffer: 64 << 20, timeout: callTimeout(), input }));
68
+
69
+ const call = <T>(schema: z.ZodType<T>, args: string[], cwd: string, input?: string): T => schema.parse(JSON.parse(gh(args, cwd, input)));
70
+
71
+ const paginated = <T>(schema: z.ZodType<T>, endpoint: string, cwd: string): T[] =>
72
+ z
73
+ .array(z.array(schema))
74
+ .parse(JSON.parse(gh(["api", "--paginate", "--slurp", endpoint], cwd)))
75
+ .flat();
76
+
77
+ const Login = z.object({ login: z.string() });
78
+
79
+ // Only people who could merge anyway. A drive-by contributor's PR is never auto-approved.
80
+ export const TRUSTED_ASSOCIATIONS = new Set(["OWNER", "MEMBER", "COLLABORATOR"]);
81
+
82
+ const MERGERS = new Set(["admin", "maintain", "write"]);
83
+
84
+ /** A user's effective permission on the repository, team grants included. */
85
+ export const permissionOf = (repo: string, login: string, cwd: string) => call(z.object({ permission: z.string() }), ["api", `repos/${repo}/collaborators/${login}/permission`], cwd).permission;
86
+
87
+ /**
88
+ * author_association reads write access through a team, and a private org member, as CONTRIBUTOR. Someone the
89
+ * permission API says can push counts as COLLABORATOR; a failed lookup keeps the association GitHub gave.
90
+ */
91
+ export function effectiveAssociation(association: string, permission: () => string): string {
92
+ if (TRUSTED_ASSOCIATIONS.has(association)) return association;
93
+
94
+ try {
95
+ return MERGERS.has(permission()) ? "COLLABORATOR" : association;
96
+ } catch (e) {
97
+ if (TimedOut.safeParse(e).success) throw e;
98
+
99
+ return association;
100
+ }
101
+ }
102
+
103
+ const CheckRuns = z.object({ check_runs: z.array(z.object({ name: z.string(), status: z.string() })) });
104
+
105
+ /** The check runs with one name on one commit, by name and status. */
106
+ export const checkRuns = (repo: string, sha: string, name: string, cwd: string) =>
107
+ call(CheckRuns, ["api", `repos/${repo}/commits/${sha}/check-runs?check_name=${encodeURIComponent(name)}&per_page=100`], cwd).check_runs;
108
+
109
+ const RepoView = z.object({ nameWithOwner: z.string(), defaultBranchRef: z.object({ name: z.string() }) });
110
+
111
+ const Pull = z.object({
112
+ title: z.string(),
113
+ body: z.string().nullable(),
114
+ user: Login,
115
+ author_association: z.string(),
116
+ draft: z.boolean(),
117
+ mergeable_state: z.string(),
118
+ labels: z.array(z.object({ name: z.string() })),
119
+ head: z.object({ ref: z.string().default(""), sha: z.string(), repo: z.object({ full_name: z.string() }).nullable() }),
120
+ base: z.object({ ref: z.string(), sha: z.string(), repo: z.object({ full_name: z.string(), private: z.boolean().optional() }) }),
121
+ });
122
+
123
+ const File = z.object({ filename: z.string(), previous_filename: z.string().optional(), additions: z.number(), deletions: z.number(), status: z.string() });
124
+
125
+ const ReviewRow = z.object({ id: z.number(), user: Login, state: z.string(), body: z.string(), commit_id: z.string(), author_association: z.string().optional() });
126
+
127
+ const ThreadPage = z.object({
128
+ data: z.object({
129
+ repository: z.object({
130
+ pullRequest: z.object({
131
+ reviewThreads: z.object({
132
+ nodes: z.array(
133
+ z.object({
134
+ id: z.string(),
135
+ isResolved: z.boolean(),
136
+ isOutdated: z.boolean(),
137
+ path: z.string(),
138
+ comments: z.object({ totalCount: z.number(), nodes: z.array(z.object({ author: z.object({ login: z.string(), __typename: z.string() }).nullable(), body: z.string(), createdAt: z.string() })) }),
139
+ }),
140
+ ),
141
+ }),
142
+ }),
143
+ }),
144
+ }),
145
+ });
146
+
147
+ // REST lists inline comments without their thread's resolution, so threads come from GraphQL.
148
+ const THREADS_QUERY = `query($owner:String!,$name:String!,$number:Int!,$endCursor:String){repository(owner:$owner,name:$name){pullRequest(number:$number){reviewThreads(first:100,after:$endCursor){pageInfo{hasNextPage endCursor} nodes{id isResolved isOutdated path comments(first:50){totalCount nodes{author{login __typename} body createdAt}}}}}}}`;
149
+
150
+ const IssueNode = z.object({
151
+ number: z.number(),
152
+ title: z.string(),
153
+ body: z.string().nullable(),
154
+ labels: z.object({ totalCount: z.number(), nodes: z.array(z.object({ name: z.string() })) }),
155
+ repository: z.object({ nameWithOwner: z.string() }),
156
+ });
157
+
158
+ // `--paginate --slurp` returns every page of the query; the closing references are the paginated connection.
159
+ const IssuesPages = z.array(z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({ closingIssuesReferences: z.object({ nodes: z.array(IssueNode) }) }) }) }) }));
160
+
161
+ // The issues the PR says it closes: the request the change claims to implement.
162
+ const ISSUES_QUERY = `query($owner:String!,$name:String!,$number:Int!,$endCursor:String){repository(owner:$owner,name:$name){pullRequest(number:$number){closingIssuesReferences(first:50,after:$endCursor){pageInfo{hasNextPage endCursor} nodes{number title body labels(first:100){totalCount nodes{name}} repository{nameWithOwner}}}}}}`;
163
+
164
+ const CommitRow = z.object({ sha: z.string(), commit: z.object({ message: z.string() }) });
165
+
166
+ const CommentRow = z.object({ user: Login, body: z.string(), created_at: z.string(), reactions: z.record(z.string(), z.union([z.number(), z.string()])).optional() });
167
+
168
+ const ReactionRow = z.object({ user: Login, content: z.string(), created_at: z.string() });
169
+
170
+ type Thread = z.infer<typeof ThreadPage>["data"]["repository"]["pullRequest"]["reviewThreads"]["nodes"][number];
171
+
172
+ /** Every review thread of a PR, from every page. */
173
+ /** How many of the PR's review threads are unresolved, whoever opened them. */
174
+ export const openThreadCount = (repo: string, number: number, cwd: string) => reviewThreads(repo, number, cwd).filter((t) => !t.isResolved).length;
175
+
176
+ function reviewThreads(repo: string, number: number, cwd: string): Thread[] {
177
+ const [owner = "", name = ""] = repo.split("/");
178
+
179
+ return z
180
+ .array(ThreadPage)
181
+ .parse(JSON.parse(gh(["api", "graphql", "--paginate", "--slurp", "-f", `query=${THREADS_QUERY}`, "-F", `owner=${owner}`, "-F", `name=${name}`, "-F", `number=${number}`], cwd)))
182
+ .flatMap((p) => p.data.repository.pullRequest.reviewThreads.nodes);
183
+ }
184
+
185
+ // GraphQL names a bot account without the `[bot]` suffix REST uses; restore it so logins match everywhere.
186
+ const threadLogin = (c: Thread["comments"]["nodes"][number]) => (c.author ? `${c.author.login}${c.author.__typename === "Bot" ? "[bot]" : ""}` : "ghost");
187
+
188
+ export type Review = { user: string; state: string; body: string; commit: string; isCurrentHead: boolean };
189
+
190
+ /** One comment in a review thread; `thread` groups comments of the same thread. */
191
+ export type InlineComment = { user: string; path: string; body: string; outdated: boolean; resolved: boolean; thread: number; created: string };
192
+
193
+ export type Comment = { user: string; body: string; created: string; reactions: string[] };
194
+
195
+ export type PR = {
196
+ /** owner/name, as fetchPR read it: every later call on this PR reuses it instead of asking again. */
197
+ repo: string;
198
+ number: number;
199
+ title: string;
200
+ body: string;
201
+ author: string;
202
+ authorAssociation: string;
203
+ isFork: boolean;
204
+ /** Set when anyone can read what gate posts here, so its reviews leave out exploit detail. */
205
+ isPublic?: boolean;
206
+ isDraft: boolean;
207
+ mergeable: string;
208
+ baseRef: string;
209
+ headRef: string;
210
+ defaultBranch: string;
211
+ headSha: string;
212
+ baseSha: string;
213
+ labels: string[];
214
+ files: PRFile[];
215
+ reviews: Review[];
216
+ inline: InlineComment[];
217
+ discussion: Comment[];
218
+ reactions: { user: string; content: string; created: string }[];
219
+ commits: { sha: string; message: string }[];
220
+ /** Issues the PR closes, from GitHub's closing references. Context, never assurance; an `incident` label only tightens the review. */
221
+ issues?: LinkedIssue[];
222
+ diff: string;
223
+ /** Set when the review covers only this PR's change over an open stacked parent: files, commits and diff are that delta. */
224
+ stack?: { parent: number; parentHead: string };
225
+ };
226
+
227
+ export type LinkedIssue = { ref: string; title: string; body: string; labels: string[] };
228
+
229
+ /**
230
+ * The closing issues that live in the PR's own repository, from every page of the query. An issue elsewhere can be
231
+ * private while the PR is public, and its text would reach the model, the evidence bundle and possibly the posted
232
+ * review. An issue with more labels than the query returned gets its full list from `allLabels`: a label past the
233
+ * first page (`incident`) can tighten the review, so it must not be dropped.
234
+ */
235
+ export function sameRepoIssues(pages: z.infer<typeof IssuesPages>, repo: string, allLabels: (issue: number) => string[]): LinkedIssue[] {
236
+ return pages
237
+ .flatMap((p) => p.data.repository.pullRequest.closingIssuesReferences.nodes)
238
+ .filter((i) => i.repository.nameWithOwner.toLowerCase() === repo.toLowerCase())
239
+ .map((i) => ({
240
+ ref: `#${i.number}`,
241
+ title: i.title,
242
+ body: i.body ?? "",
243
+ labels: i.labels.totalCount > i.labels.nodes.length ? allLabels(i.number) : i.labels.nodes.map((l) => l.name),
244
+ }));
245
+ }
246
+
247
+ /**
248
+ * Closing issues for a PR. A failed fetch fails the run, like every other PR fetch: an `incident` label it would
249
+ * have found tightens the review, so going on without it would fail open.
250
+ */
251
+ function closingIssues(owner: string, name: string, number: number, cwd: string): LinkedIssue[] {
252
+ const pages = IssuesPages.parse(JSON.parse(gh(["api", "graphql", "--paginate", "--slurp", "-f", `query=${ISSUES_QUERY}`, "-F", `owner=${owner}`, "-F", `name=${name}`, "-F", `number=${number}`], cwd)));
253
+
254
+ return sameRepoIssues(pages, `${owner}/${name}`, (issue) => paginated(z.object({ name: z.string() }), `repos/${owner}/${name}/issues/${issue}/labels`, cwd).map((l) => l.name));
255
+ }
256
+
257
+ export function repoSlug(cwd: string): string {
258
+ return call(z.object({ nameWithOwner: z.string() }), ["repo", "view", "--json", "nameWithOwner"], cwd).nameWithOwner;
259
+ }
260
+
261
+ // GitHub's reaction rollup: counts keyed by emoji name, plus `url` and `total_count`.
262
+ const reactionList = (r: Record<string, number | string> | undefined) => {
263
+ const out: string[] = [];
264
+
265
+ for (const [k, v] of Object.entries(r ?? {})) if (k !== "total_count" && v !== 0 && Number.isInteger(v)) out.push(`${k}×${v}`);
266
+
267
+ return out;
268
+ };
269
+
270
+ export function fetchPR(number: number, cwd: string, exclude: string[] = []): PR {
271
+ const repo = call(RepoView, ["repo", "view", "--json", "nameWithOwner,defaultBranchRef"], cwd);
272
+ const base = `repos/${repo.nameWithOwner}`;
273
+ const view = call(Pull, ["api", `${base}/pulls/${number}`], cwd);
274
+ const headSha = view.head.sha;
275
+ const notOurs = <T extends { user: { login: string } }>(rows: T[]) => rows.filter((r) => !exclude.includes(r.user.login));
276
+ const [owner = "", name = ""] = repo.nameWithOwner.split("/");
277
+ const threads = reviewThreads(repo.nameWithOwner, number, cwd);
278
+
279
+ return {
280
+ repo: repo.nameWithOwner,
281
+ number,
282
+ title: view.title,
283
+ body: view.body ?? "",
284
+ author: view.user.login,
285
+ authorAssociation: effectiveAssociation(view.author_association, () => permissionOf(repo.nameWithOwner, view.user.login, cwd)),
286
+ isFork: view.head.repo?.full_name !== view.base.repo.full_name,
287
+ isPublic: view.base.repo.private === false,
288
+ isDraft: view.draft,
289
+ mergeable: view.mergeable_state === "dirty" ? "CONFLICTING" : "MERGEABLE",
290
+ baseRef: view.base.ref,
291
+ headRef: view.head.ref,
292
+ defaultBranch: repo.defaultBranchRef.name,
293
+ headSha,
294
+ baseSha: view.base.sha,
295
+ labels: view.labels.map((l) => l.name),
296
+ files: paginated(File, `${base}/pulls/${number}/files`, cwd).map((f) => ({
297
+ filename: f.filename,
298
+ previousFilename: f.previous_filename, // a rename out of a sensitive path is still a change to it
299
+ additions: f.additions,
300
+ deletions: f.deletions,
301
+ status: f.status,
302
+ })),
303
+ // Our own earlier verdicts describe an older snapshot and are never independent signal, whatever login posted them.
304
+ reviews: notOurs(paginated(ReviewRow, `${base}/pulls/${number}/reviews`, cwd)).filter((r) => !RUN_MARKER.test(r.body)).map((r) => ({
305
+ user: r.user.login,
306
+ state: r.state,
307
+ body: r.body,
308
+ commit: r.commit_id,
309
+ isCurrentHead: r.commit_id === headSha,
310
+ })),
311
+ inline: threads.flatMap((t, thread) =>
312
+ t.comments.nodes
313
+ .map((c) => ({ user: threadLogin(c), path: t.path, body: c.body, outdated: t.isOutdated, resolved: t.isResolved, thread, created: c.createdAt }))
314
+ // Our own findings, whatever login posted them, as for reviews below: an App token's login is not `exclude`.
315
+ .filter((c) => !exclude.includes(c.user) && !isOwnBot(c.user, c.body)),
316
+ ),
317
+ discussion: notOurs(paginated(CommentRow, `${base}/issues/${number}/comments`, cwd)).filter((c) => !c.body.includes(CARD_MARKER)).map((c) => ({
318
+ user: c.user.login,
319
+ body: c.body,
320
+ created: c.created_at,
321
+ reactions: reactionList(c.reactions),
322
+ })),
323
+ reactions: prReactions(base, number, cwd),
324
+ commits: paginated(CommitRow, `${base}/pulls/${number}/commits`, cwd).map((c) => ({ sha: c.sha, message: c.commit.message })),
325
+ issues: closingIssues(owner, name, number, cwd),
326
+ diff: gh(["pr", "diff", String(number)], cwd),
327
+ };
328
+ }
329
+
330
+ /**
331
+ * The PR's reactions, read for reviewer bots still at work. The endpoint sits behind the `issues` permission, and
332
+ * without it the only loss is not waiting for those bots, so a 403 warns and reads as none rather than failing the run.
333
+ */
334
+ function prReactions(base: string, number: number, cwd: string): PR["reactions"] {
335
+ try {
336
+ return paginated(ReactionRow, `${base}/issues/${number}/reactions`, cwd).map((r) => ({ user: r.user.login, content: r.content, created: r.created_at }));
337
+ } catch (e) {
338
+ if (!(e instanceof Error) || !e.message.includes("HTTP 403")) throw e;
339
+ console.error("PR reactions unreadable (HTTP 403: grant the workflow `issues: read`); not waiting for reviewer bots");
340
+
341
+ return [];
342
+ }
343
+ }
344
+
345
+ const VERDICTS = ["APPROVED", "REFUSED", "ESCALATE", "ERROR"] as const;
346
+
347
+ export type Verdict = (typeof VERDICTS)[number];
348
+
349
+ /** True when the live PR still has the head, base ref and base sha that were reviewed. */
350
+ export function unchanged(pr: PR, cwd: string): boolean {
351
+ const live = call(Pull, ["api", `repos/${pr.repo}/pulls/${pr.number}`], cwd);
352
+
353
+ if (live.head.sha === pr.headSha && live.base.ref === pr.baseRef && live.base.sha === pr.baseSha) return true;
354
+
355
+ console.log(`PR changed (head ${pr.headSha.slice(0, 7)}→${live.head.sha.slice(0, 7)}, base ${pr.baseRef}@${pr.baseSha.slice(0, 7)}→${live.base.ref}@${live.base.sha.slice(0, 7)})`);
356
+
357
+ return false;
358
+ }
359
+
360
+ // Every posted review carries the ISO start time of the run that produced it, so concurrent runs
361
+ // can be ordered without shared state: the run that started later owns the newer verdict.
362
+ const RUN_MARKER = /<!-- gate-run:(\S+) -->/;
363
+
364
+ /**
365
+ * Git config for a fetch that authenticates through gh (GH_TOKEN in CI), so the workflow can check out with
366
+ * persist-credentials: false and no token sits in .git/config for a reviewer to read.
367
+ */
368
+ export const GH_CREDENTIALS = ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential"];
369
+
370
+ export const runMarker = (started: string) => `<!-- gate-run:${started} -->`;
371
+
372
+ /** Text with no HTML comment delimiter left, nested ones (`<!<!---->--`) included. */
373
+ export function withoutComments(text: string): string {
374
+ let out = text;
375
+
376
+ for (let before = ""; before !== out; ) {
377
+ before = out;
378
+ out = out.replace(/<!--|-->/g, "");
379
+ }
380
+
381
+ return out;
382
+ }
383
+
384
+ // The full SHAs a review covered. Approval retention compares diffs on exactly these.
385
+ const REVIEWED_MARKER = /<!-- gate-reviewed:head=([0-9a-f]+);base=([0-9a-f]+) -->/;
386
+
387
+ export const reviewedMarker = (headSha: string, baseSha: string) => `<!-- gate-reviewed:head=${headSha};base=${baseSha} -->`;
388
+
389
+ export const listReviews = (repo: string, prNumber: number, cwd: string) => paginated(ReviewRow, `repos/${repo}/pulls/${prNumber}/reviews`, cwd);
390
+
391
+ export type ReviewRecord = z.infer<typeof ReviewRow>;
392
+
393
+ /**
394
+ * Written on a verdict reached while policy asked for CI test evidence and the review did not read it
395
+ * (pending, stale, missing or unreadable). Retention never keeps such an approval: the evidence may have
396
+ * landed since, and a byte-identical diff says nothing about it.
397
+ */
398
+ export const EVIDENCE_UNSEEN_MARKER = "<!-- gate-evidence:unseen -->";
399
+
400
+ export const evidenceUnseen = (r: ReviewRecord) => r.body.includes(EVIDENCE_UNSEEN_MARKER);
401
+
402
+ /** The head and base one of our reviews covered, from its marker; null for a review posted before the marker existed. */
403
+ export function reviewedShas(r: ReviewRecord): { head: string; base: string } | null {
404
+ // The last marker: gate writes it after the review text, so text above it cannot stand in for it.
405
+ const m = [...r.body.matchAll(new RegExp(REVIEWED_MARKER, "g"))].at(-1);
406
+
407
+ // SAFETY: both capture groups in REVIEWED_MARKER are mandatory, so a match fills them.
408
+ return m ? { head: m[1]!, base: m[2]! } : null;
409
+ }
410
+
411
+ /** The heading and first paragraph gate wrote on a review, folded or not. The model's text below them stays out. */
412
+ function opening(body: string) {
413
+ const [heading = "", , first = ""] = (body.startsWith(SUPERSEDED) ? body.slice(body.indexOf("\n\n") + 2) : body).split("\n");
414
+
415
+ return { heading, first };
416
+ }
417
+
418
+ /** An ERROR or a gate denial, which posts without a model reading the head. */
419
+ const unread = (body: string) => {
420
+ const { heading, first } = opening(body);
421
+
422
+ return /: ERROR\b/.test(heading) || /^(Gates denied|Not reviewed): /.test(first);
423
+ };
424
+
425
+ /** The head and base our newest completed review covered, or null when it covered `head`. */
426
+ export function lastReviewed(reviews: ReviewRecord[], botLogin: string, head: string) {
427
+ const last = reviews.filter((r) => isOurs(r, botLogin) && !unread(r.body)).flatMap((r) => reviewedShas(r) ?? []).at(-1);
428
+
429
+ return last && last.head !== head ? last : null;
430
+ }
431
+
432
+ /** How many earlier heads of this PR a model refused, a refusal the cap escalated included. A rerun on `head` adds none. */
433
+ export function refusedRounds(reviews: ReviewRecord[], botLogin: string, head: string): number {
434
+ const wasRefused = (body: string) => /: REFUSED\b/.test(opening(body).heading) || /^Round \d+ on this PR/.test(opening(body).first);
435
+ const refused = reviews.filter((r) => isOurs(r, botLogin) && wasRefused(r.body) && !unread(r.body));
436
+
437
+ return new Set(refused.flatMap((r) => reviewedShas(r)?.head ?? []).filter((h) => h !== head)).size;
438
+ }
439
+
440
+ // Which head one of our reviews covered. GitHub moves a standing approval's `commit_id` forward when
441
+ // the branch is updated from its base, so `commit_id` can name a head the review never saw. Our own
442
+ // marker is the record; `commit_id` is the fallback only for reviews posted before the marker existed.
443
+ const reviewedHead = (r: ReviewRecord) => reviewedShas(r)?.head ?? r.commit_id;
444
+
445
+ /**
446
+ * Whether `r` is one of our verdicts: posted by our login, or by any bot account and carrying our run
447
+ * marker. A GitHub App token posts as `<app>[bot]` while `gh api user` fails, so the login alone can miss
448
+ * our own approvals; the marker keeps them in every sweep.
449
+ */
450
+ export const isOurs = (r: ReviewRecord, botLogin: string) => r.user.login === botLogin || isOwnBot(r.user.login, r.body);
451
+
452
+ const isOwnBot = (login: string, body: string) => login.endsWith("[bot]") && RUN_MARKER.test(body);
453
+
454
+ /**
455
+ * The gate's latest verdict on a PR and the head it reviewed, for a reader that does not know the gate's login:
456
+ * only a bot account's review carrying both markers counts, since a person can paste the heading. An approval
457
+ * GitHub dismissed reads DISMISSED. A gate posting through a person's token is not recognised here.
458
+ */
459
+ export function latestVerdict(reviews: ReviewRecord[]): { verdict: Verdict | "DISMISSED"; head: string; base: string; evidenceUnseen: boolean } | undefined {
460
+ const r = reviews.filter((x) => isOwnBot(x.user.login, x.body) && reviewedShas(x)).at(-1);
461
+ const heading = r && /^## .*?: (APPROVED|REFUSED|ESCALATE|ERROR)\b/.exec(r.body)?.[1];
462
+ const v = VERDICTS.find((x) => x === heading);
463
+
464
+ if (!r || !v) return undefined;
465
+
466
+ const shas = reviewedShas(r);
467
+
468
+ return { verdict: v === "APPROVED" && r.state !== "APPROVED" ? "DISMISSED" : v, head: shas?.head ?? r.commit_id, base: shas?.base ?? "", evidenceUnseen: evidenceUnseen(r) };
469
+ }
470
+
471
+ /** Whether the run that posted `r` started after `iso`: the later-started run owns the newer verdict. */
472
+ const startedAfter = (r: { body: string }, iso: string) => {
473
+ // The last marker, as for the reviewed marker: gate writes it after the review text.
474
+ const started = [...r.body.matchAll(new RegExp(RUN_MARKER, "g"))].at(-1)?.[1];
475
+
476
+ return started !== undefined && started > iso;
477
+ };
478
+
479
+ const Compare = z.object({ files: z.array(File).default([]), commits: z.array(CommitRow) });
480
+
481
+ /**
482
+ * The files and commits of from...to, through the compare API, with its unified diff. The API lists at most 300
483
+ * files, so a fuller list is null: the caller reviews the whole PR instead.
484
+ */
485
+ export function compareDelta(repo: string, from: string, to: string, cwd: string): Pick<PR, "files" | "commits" | "diff"> | null {
486
+ const c = Compare.parse(JSON.parse(gh(["api", `repos/${repo}/compare/${from}...${to}`], cwd)));
487
+
488
+ if (c.files.length >= 300) return null;
489
+
490
+ return {
491
+ files: c.files.map((f) => ({ filename: f.filename, previousFilename: f.previous_filename, additions: f.additions, deletions: f.deletions, status: f.status })),
492
+ commits: c.commits.map((x) => ({ sha: x.sha, message: x.commit.message })),
493
+ diff: compareDiff(repo, from, to, cwd),
494
+ };
495
+ }
496
+
497
+ const OpenPR = z.object({ number: z.number(), headRefOid: z.string(), isCrossRepository: z.boolean() });
498
+
499
+ /** Open PRs into `base` whose head lives in this repository: the candidates for a stacked parent. */
500
+ export const openPRsInto = (base: string, cwd: string) =>
501
+ call(z.array(OpenPR), ["pr", "list", "--state", "open", "--base", base, "--limit", "100", "--json", "number,headRefOid,isCrossRepository"], cwd).filter((p) => !p.isCrossRepository);
502
+
503
+ /** Unified diff of base...head on immutable SHAs, via the compare API. Throws on any gh failure. */
504
+ export const compareDiff = (repo: string, baseSha: string, headSha: string, cwd: string) =>
505
+ gh(["api", "-H", "Accept: application/vnd.github.diff", `repos/${repo}/compare/${baseSha}...${headSha}`], cwd);
506
+
507
+ /** Numbers of up to 1000 PRs by `author` merged into `repo`. */
508
+ export const mergedPRNumbers = (repo: string, author: string, cwd: string) =>
509
+ new Set(call(z.array(z.object({ number: z.number() })), ["pr", "list", "--repo", repo, "--author", author, "--state", "merged", "--limit", "1000", "--json", "number"], cwd).map((p) => p.number));
510
+
511
+ export type PostOptions = { cwd: string; botLogin: string; started: string; triggerLabel?: string };
512
+
513
+ /** True when a run that started after `started` has already posted a verdict of ours on this head. */
514
+ function newerVerdictExists(pr: PR, opts: PostOptions): boolean {
515
+ const newer = listReviews(pr.repo, pr.number, opts.cwd).some(
516
+ (r) => isOurs(r, opts.botLogin) && r.state !== "DISMISSED" && reviewedHead(r) === pr.headSha && startedAfter(r, opts.started),
517
+ );
518
+
519
+ if (newer) console.log("a newer gate run already posted on this head; this run's verdict is stale");
520
+
521
+ return newer;
522
+ }
523
+
524
+ const SUPERSEDED = "<details><summary>Superseded: ";
525
+
526
+ /**
527
+ * An older review of ours, folded under one line that names its verdict and links the latest. The body stays whole
528
+ * inside, markers included, so retention and the sweeps read it exactly as before.
529
+ */
530
+ export function supersededBody(r: ReviewRecord, latestId: number): string | null {
531
+ if (r.body.startsWith(SUPERSEDED)) return null;
532
+
533
+ const verdict = /: (APPROVED|REFUSED|ESCALATE|ERROR)\b/.exec(r.body.split("\n", 1)[0] ?? "")?.[1] ?? r.state.toLowerCase();
534
+
535
+ return `${SUPERSEDED}gate ${verdict} on <code>${reviewedHead(r).slice(0, 7)}</code> · <a href="#pullrequestreview-${latestId}">latest review</a></summary>\n\n${r.body}\n\n</details>`;
536
+ }
537
+
538
+ /**
539
+ * The older reviews of ours to fold under `latestId`, by id; null when a run that started after `started` has posted,
540
+ * since its verdict is the current one and this run must neither fold it nor rewrite the card over it.
541
+ */
542
+ export function foldTargets(reviews: ReviewRecord[], latestId: number, botLogin: string, started: string): number[] | null {
543
+ const ours = reviews.filter((r) => r.id !== latestId && isOurs(r, botLogin));
544
+
545
+ if (ours.some((r) => startedAfter(r, started))) return null;
546
+
547
+ return ours.flatMap((r) => (supersededBody(r, latestId) ? [r.id] : []));
548
+ }
549
+
550
+ /**
551
+ * Fold every older review of ours under the one just posted, so the PR reads one current verdict. Folds nothing
552
+ * when a newer run has posted since: that run folds this one. Best effort.
553
+ */
554
+ export function foldSuperseded(pr: PR, latestId: number, botLogin: string, started: string, cwd: string): void {
555
+ const reviews = listReviews(pr.repo, pr.number, cwd);
556
+ const targets = foldTargets(reviews, latestId, botLogin, started);
557
+
558
+ for (const r of reviews.filter((x) => targets?.includes(x.id))) {
559
+ gh(["api", "-X", "PUT", `repos/${pr.repo}/pulls/${pr.number}/reviews/${r.id}`, "-f", `body=${supersededBody(r, latestId)}`], cwd);
560
+ }
561
+ }
562
+
563
+ const OwnComment = z.object({ id: z.number(), user: Login, body: z.string() });
564
+
565
+ const VERDICT_HEADING = /^## (.*?: (APPROVED|REFUSED|ESCALATE|ERROR))\b/;
566
+
567
+ /**
568
+ * The card for the newest verdict of ours on the PR (by run start), or null when there is none. Derived from the
569
+ * reviews alone, so every run computes the same card and whichever writes last leaves the newest verdict showing.
570
+ */
571
+ export function cardFor(reviews: ReviewRecord[], botLogin: string, shepherd: boolean): string | null {
572
+ const runStart = (r: ReviewRecord) => [...r.body.matchAll(new RegExp(RUN_MARKER, "g"))].at(-1)?.[1] ?? "";
573
+ const newest = reviews.filter((r) => isOurs(r, botLogin) && !r.body.startsWith(SUPERSEDED)).sort((a, b) => runStart(a).localeCompare(runStart(b))).at(-1);
574
+ const heading = newest ? VERDICT_HEADING.exec(newest.body.split("\n", 1)[0] ?? "") : null;
575
+
576
+ if (!newest || !heading) return null;
577
+
578
+ // SAFETY: VERDICT_HEADING's second group only matches one of the four verdicts.
579
+ const verdict = heading[2] as Verdict;
580
+
581
+ // A dismissed approval was withdrawn (a push, a draft, a lost label), and the card says so.
582
+ const title = newest.state === "DISMISSED" ? `${heading[1]!} (withdrawn)` : heading[1]!;
583
+
584
+ return `${renderCard({ heading: title, verdict, head: reviewedHead(newest), reviewId: newest.id, shepherd })}\n${runMarker(runStart(newest))}`;
585
+ }
586
+
587
+ /**
588
+ * Bring the PR's gate card in line with the newest verdict. A run can write over a newer run's card in the gap
589
+ * between reading it and writing, and two first runs can each post one, so every write is followed by a re-read:
590
+ * the loop ends when exactly one card matches the newest verdict. Duplicates go, the oldest card stays.
591
+ */
592
+ export function publishCard(prNumber: number, botLogin: string, shepherd: boolean, cwd: string): void {
593
+ const pr = { repo: repoSlug(cwd), number: prNumber };
594
+
595
+ for (let attempt = 0; attempt < 3; attempt++) {
596
+ const desired = cardFor(listReviews(pr.repo, pr.number, cwd), botLogin, shepherd);
597
+ const [card, ...extra] = paginated(OwnComment, `repos/${pr.repo}/issues/${pr.number}/comments`, cwd).filter((c) => c.user.login === botLogin && c.body.startsWith(CARD_MARKER));
598
+
599
+ for (const c of extra) gh(["api", "-X", "DELETE", `repos/${pr.repo}/issues/comments/${c.id}`], cwd);
600
+
601
+ if (!desired || (card?.body === desired && !extra.length)) return;
602
+
603
+ if (card) gh(["api", "-X", "PATCH", `repos/${pr.repo}/issues/comments/${card.id}`, "-f", `body=${desired}`], cwd);
604
+ else gh(["api", "-X", "POST", `repos/${pr.repo}/issues/${pr.number}/comments`, "-f", `body=${desired}`], cwd);
605
+ }
606
+ }
607
+
608
+ /** The JSON gate posts for a review: pinned to the reviewed commit, credentials redacted, each anchored finding carrying the run marker. */
609
+ export function reviewPayload(headSha: string, verdict: Verdict, body: string, comments: Anchored[], started: string) {
610
+ return {
611
+ commit_id: headSha,
612
+ event: verdict === "APPROVED" ? "APPROVE" : "COMMENT",
613
+ body: scrub(body),
614
+ comments: comments.map((c) => ({ path: c.path, line: c.line, side: "RIGHT", body: `${AUTOMATED_HEADER}\n\n${scrub(c.body)}\n\n${runMarker(started)}` })),
615
+ };
616
+ }
617
+
618
+ /**
619
+ * Approvals are real reviews (count toward branch protection); everything else is a comment. Never request-changes.
620
+ * `comments` anchor findings to lines. On a 422 the review goes again without them: the body holds every finding.
621
+ */
622
+ export function postVerdict(pr: PR, verdict: Verdict, body: string, opts: PostOptions, comments: Anchored[] = []): number | null {
623
+ // The diff can change under a finished review two ways: a push moves the head, a retarget moves the
624
+ // base without touching the head. Refuse to post over either; the next run reviews what is live.
625
+ // A newer run may also have already ruled on this exact head; its verdict governs, not this one.
626
+ if (!unchanged(pr, opts.cwd) || newerVerdictExists(pr, opts)) return null;
627
+
628
+ // The review is pinned to the reviewed commit, so a push that lands between the check above and
629
+ // this call cannot inherit the approval: GitHub records it against pr.headSha, not the live head.
630
+ const submit = (anchored: Anchored[]) =>
631
+ retrying(REVIEW_DELAYS_MS, transientReviewError, () =>
632
+ call(z.object({ id: z.number() }), ["api", "-X", "POST", `repos/${pr.repo}/pulls/${pr.number}/reviews`, "--input", "-"], opts.cwd, JSON.stringify(reviewPayload(pr.headSha, verdict, body, anchored, opts.started))),
633
+ );
634
+
635
+ let posted: { id: number };
636
+
637
+ try {
638
+ posted = submit(comments);
639
+ } catch (e) {
640
+ if (!comments.length || !(e instanceof Error) || !e.message.includes("HTTP 422")) throw e;
641
+ console.error(`GitHub refused the review's ${comments.length} inline comment(s); posting without them`);
642
+ posted = submit([]);
643
+ }
644
+
645
+ // Substantive non-approvals strip the trigger label so a human takes over; ERROR keeps it so the next push retries.
646
+ if (opts.triggerLabel && (verdict === "REFUSED" || verdict === "ESCALATE") && pr.labels.includes(opts.triggerLabel)) {
647
+ execFileSync("gh", ["pr", "edit", String(pr.number), "--remove-label", opts.triggerLabel], { cwd: opts.cwd, stdio: "inherit", timeout: callTimeout() });
648
+ }
649
+
650
+ return posted.id;
651
+ }
652
+
653
+ /** Open threads of our earlier findings nobody else has joined, by id: the verdict of the run that started at `started` replaces them. */
654
+ export function retiredThreads(threads: Thread[], botLogin: string, started: string): string[] {
655
+ const ours = (c: Thread["comments"]["nodes"][number]) => threadLogin(c) === botLogin || isOwnBot(threadLogin(c), c.body);
656
+
657
+ const earlier = (body: string) => {
658
+ const at = [...body.matchAll(new RegExp(RUN_MARKER, "g"))].at(-1)?.[1];
659
+
660
+ return at !== undefined && at < started;
661
+ };
662
+
663
+ // The query fetches the first 50 comments, so a longer thread stays open: a later reply could be someone else's.
664
+ const whole = (t: Thread) => t.comments.totalCount === t.comments.nodes.length;
665
+
666
+ return threads.flatMap((t) => (!t.isResolved && whole(t) && t.comments.nodes.every(ours) && t.comments.nodes.some((c) => earlier(c.body)) ? [t.id] : []));
667
+ }
668
+
669
+ /**
670
+ * Resolves the threads a new verdict replaces. Each run reviews from scratch, so a finding that still holds comes back
671
+ * in this run's review, and repositories that require resolved conversations can merge. A thread with anyone else's
672
+ * reply stays open. Best effort, like folding.
673
+ */
674
+ export function retireOwnThreads(pr: PR, botLogin: string, started: string, cwd: string): void {
675
+ for (const id of retiredThreads(reviewThreads(pr.repo, pr.number, cwd), botLogin, started)) {
676
+ gh(["api", "graphql", "-f", "query=mutation($id:ID!){resolveReviewThread(input:{threadId:$id}){thread{id}}}", "-f", `id=${id}`], cwd);
677
+ }
678
+ }
679
+
680
+ /** Deterministic redaction of anything that could be a credential before it reaches GitHub. */
681
+ export function scrub(text: string): string {
682
+ const keys = ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "GH_TOKEN", "GITHUB_TOKEN", "CODEX_API_KEY", "OPENAI_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "OPENCODE_API_KEY", "OPENROUTER_API_KEY", "GROQ_API_KEY", "MISTRAL_API_KEY", "AI_GATEWAY_API_KEY", "AWS_BEARER_TOKEN_BEDROCK", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "TYPESAFE_API_KEY", "OTEL_EXPORTER_OTLP_HEADERS", "SHEPHERD_NOTIFY_WEBHOOK", "OPENAI_COMPATIBLE_API_KEY", "DEEPSEEK_API_KEY"];
683
+
684
+ const values = keys.flatMap((k) => {
685
+ const v = process.env[k];
686
+
687
+ return v ? [v] : [];
688
+ }).sort((a, b) => b.length - a.length);
689
+
690
+ for (const v of values) text = text.split(v).join("[redacted]");
691
+
692
+ return text.replace(/\b(sk-(?:ant-|proj-|svcacct-)?[\w-]{20,}|gsk_[A-Za-z0-9]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, "[redacted]");
693
+ }
694
+
695
+ type EvidenceValue = string | number | boolean | null | undefined | EvidenceValue[] | { [key: string]: EvidenceValue };
696
+
697
+ type EvidenceBundle = { [key: string]: EvidenceValue };
698
+
699
+ /** Redact string values before JSON escaping so evidence preserves its structure. */
700
+ export const scrubJson = (value: EvidenceBundle): string => JSON.stringify(value, (_k, v) => {
701
+ const text = z.string().safeParse(v);
702
+
703
+ return text.success ? scrub(text.data) : v;
704
+ }, 2);
705
+
706
+ export type Sweep = {
707
+ /** The review this run just posted; never dismissed. */
708
+ keep?: number | null;
709
+ /** When set, an approval on the live head is dismissed only if its run started before this ISO time. */
710
+ olderThan?: string;
711
+ };
712
+
713
+ /**
714
+ * A gate approval must never stand over commits it didn't review. With no options (startup) every
715
+ * active approval of ours goes: fresh judgment is pending and, if a later step crashes, the old
716
+ * approval is already gone. With `olderThan` (terminal sweep) an approval pinned to the live head
717
+ * survives if its run started after ours, because that run's verdict is the newer one; everything
718
+ * off-head or older is dismissed. Needs only the PR number, so it can run before any fallible fetch.
719
+ */
720
+ export function dismissOwnApprovals(prNumber: number, botLogin: string, cwd: string, sweep: Sweep = {}): void {
721
+ const repo = repoSlug(cwd);
722
+ const liveHead = sweep.olderThan ? call(Pull, ["api", `repos/${repo}/pulls/${prNumber}`], cwd).head.sha : null;
723
+
724
+ for (const id of sweepTargets(listReviews(repo, prNumber, cwd), botLogin, liveHead, sweep)) {
725
+ gh(["api", "-X", "PUT", `repos/${repo}/pulls/${prNumber}/reviews/${id}/dismissals`, "-f", "message=Superseded by a newer gate run"], cwd);
726
+ }
727
+ }
728
+
729
+ /** The approvals of ours a sweep dismisses, by id; `liveHead` is read only for the terminal sweep. */
730
+ export function sweepTargets(reviews: ReviewRecord[], botLogin: string, liveHead: string | null, sweep: Sweep = {}): number[] {
731
+ return reviews.flatMap((r) => {
732
+ if (!isOurs(r, botLogin) || r.state !== "APPROVED" || r.id === sweep.keep) return [];
733
+
734
+ if (sweep.olderThan && reviewedHead(r) === liveHead && startedAfter(r, sweep.olderThan)) return []; // a newer run's approval of this same head
735
+
736
+ return [r.id];
737
+ });
738
+ }
739
+
740
+ /**
741
+ * After posting, re-verify the PR is still what was reviewed and that no newer run ruled on this head
742
+ * in the meantime; if either fails, the review just posted is an orphan. An orphaned approval MUST
743
+ * come down, so a failed dismissal propagates and fails the run loudly: a silent 503 here would leave
744
+ * an approval standing over code nobody reviewed. A comment cannot be dismissed on GitHub and grants
745
+ * nothing, so a stale one is logged and left.
746
+ */
747
+ /** Returns true when the verdict just posted is still current; false when it went stale (and an approval was dismissed). */
748
+ export function reconcilePosted(pr: PR, reviewId: number, verdict: Verdict, opts: PostOptions): boolean {
749
+ if (unchanged(pr, opts.cwd) && !newerVerdictExists(pr, opts)) return true;
750
+
751
+ if (verdict !== "APPROVED") {
752
+ console.log("the comment just posted is stale; it grants nothing and stays");
753
+
754
+ return false;
755
+ }
756
+
757
+ console.log("dismissing the approval just posted");
758
+ gh(["api", "-X", "PUT", `repos/${pr.repo}/pulls/${pr.number}/reviews/${reviewId}/dismissals`, "-f", "message=Superseded while gate was posting"], opts.cwd);
759
+
760
+ return false;
761
+ }