Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
ci: fix-wave closeout closes the PRs a merged wave supersedes
time-attack2f21989c6f05
diff --git a/.github/workflows/fix-wave-closeout.yml b/.github/workflows/fix-wave-closeout.ymlnew file mode 100644index 0000000000..fc6a9026e9--- /dev/null+++ b/.github/workflows/fix-wave-closeout.yml@@ -0,0 +1,39 @@+name: Fix-wave closeout++# When a fix wave (a same-repo PR) merges into master, close every pull request+# its body names on a `Supersedes #N` line, with a thank-you comment linking the+# wave (docs/RELEASING.md, "Fix-wave closeout"). `Fixes #N` closes issues+# through GitHub itself.+#+# pull_request_target runs this file and the checked-out script from the+# default branch. It reads only event metadata and the REST API: it NEVER+# checks out, builds or runs PR code.++on:+ pull_request_target:+ branches: [master]+ types: [closed]++permissions: {}++jobs:+ close-superseded:+ if: github.event.pull_request.merged == true && github.event.pull_request.head.repo.full_name == 'garrytan/gbrain'+ runs-on: ubicloud-standard-2-ubuntu-2404+ timeout-minutes: 10+ permissions:+ contents: read+ pull-requests: write+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ persist-credentials: false+ sparse-checkout: scripts/fix-wave-closeout.ts+ sparse-checkout-cone-mode: false+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.2+ - name: Close superseded PRs+ env:+ GH_TOKEN: ${{ github.token }}+ run: bun scripts/fix-wave-closeout.tsdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex c7090c94a3..5ac00dfd5b 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -680,7 +680,8 @@ accepted contribution is credited in `CHANGELOG.md`.Contributor PRs are never merged into master as-is. A maintainer folds thechange into a fix-wave PR, revises it there (tests, agent-facing errors,conventions) and lands it with credit: the commit says `Contributed by @handle`-and carries a `Co-Authored-By:` trailer. Your PR stays open until then.+and carries a `Co-Authored-By:` trailer. Your PR stays open until then. When+the fix wave merges, a workflow closes your PR with a comment that links the wave.The **Fix-wave gate** check enforces this. It fails every PR into master whosehead branch is not in `garrytan/gbrain` itself, and posts one comment sayingdiff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 08785f03ae..e32e8cb2f4 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -555,7 +555,11 @@ Never merge external PRs directly into master. Instead, use the "fix wave" workfthis. It is a net, not a proof — a human still reads the diffs.6. **Close with context** — every closed PR gets a comment explaining why and what (ifanything) supersedes it. Contributors did real work; respect that with clear communication- and thank them.+ and thank them. In the wave PR body, put each folded-in contributor PR on a+ `Supersedes #N` line and each fixed issue on a `Fixes #N` line: when the wave merges,+ the [fix-wave closeout](#fix-wave-closeout) closes those PRs with a thank-you comment and+ GitHub closes the issues. Write `Addresses #N` or `Refs #N` for anything only partly+ done, so it stays open. Close declined or duplicate PRs by hand, with the reason.7. **Ship as one PR** — single PR to master with all attributions preserved via`Co-Authored-By:` trailers. Include a summary of what merged and what closed.@@ -604,6 +608,31 @@ run once on any PR before GitHub offers it in the picker.contributor commits passes by design. Keeping contributor work inside a revised fixwave on those branches stays a policy rule, enforced by review, not by this check.+### Fix-wave closeout++`.github/workflows/fix-wave-closeout.yml` (job `close-superseded`) runs when a PR+into master closes. If it merged and its head repository is `garrytan/gbrain`,+`scripts/fix-wave-closeout.ts` reads the merged PR's body and closes every open pull+request named on a `Supersedes #N` line (`Supersedes #5085`, `- Supersedes #5089,+#5096 and #5107`, `**Supersedes:** #5113`). Only the list right after the keyword+counts, so `Supersedes #5140, which conflicts with #5000` closes #5140 alone. Each+closed PR gets one comment, keyed by `<!-- fix-wave-closeout -->`, that thanks the+contributor, links the wave, and says the work landed with credit when the wave body+contains `Contributed by @<their handle>`. Numbers that are issues or already-closed+PRs are skipped. A failed close is a warning in the run log, and the step summary+lists every number with what happened to it. One run closes at most 50 PRs.++Issues need nothing extra: `Fixes #N` in the same body closes them through GitHub.+Before this workflow, contributor PRs stayed open after their wave merged, which is+most of why the open-PR count grew. To preview a body locally without writing+anything, save the event payload and run+`bun scripts/fix-wave-closeout.ts --event <payload.json> --dry-run`.++Like the gate, it uses `pull_request_target`: the workflow and script come from the+default branch, it sparse-checks-out only the script, and it never checks out or+runs PR code. Permissions are `{}` at the top and `contents: read` plus+`pull-requests: write` for the one job.+## Checking out PRs from garrytan-agents`garrytan-agents` is the AI-authored PR account and is NOT a collaborator ondiff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.mdindex 1f043822c4..37b7f2e795 100644--- a/docs/architecture/key-files/ci-health-and-test-guards.md+++ b/docs/architecture/key-files/ci-health-and-test-guards.md@@ -19,3 +19,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/check-image-decoders-embedded.sh` — `check:image-decoders` (in `verify`): compiles a smoke binary and proves HEIC and AVIF decode inside a `bun --compile` artifact; a failure prints the bun build error with Why/Fix.- `scripts/contributor-audit.ts` + `scripts/contributor-audit-fixture.ts` — `bun run audit:contributors <base>..<head> [--prs <manifest>] [--json]`. Per first-parent commit in the range and per pinned PR head trial-merged onto `<head>`: green baseline of the change's test files (one Bun process per file), reverse only its product hunks (non-test, non-doc) with `git apply -R` in an isolated worktree of `<head>` (falling back to the merge commit when the hunks no longer apply), classify (`discriminates`, `does_not_discriminate`, `vacuous_failure`, `setup_failed`, `conflict`, `not_audited` with a reason), restore, verify the tree is identical and green again. Untrusted install and tests run under `env -i` with `sandboxEnv()`'s allowlist (temporary `HOME`/`GBRAIN_HOME`, empty `DATABASE_URL`/`GBRAIN_DATABASE_URL` unless `--postgres` names a test-shaped database). Runs the trusted `wave-security-scan.sh` and `check-postgres-lane-coverage.ts` (`GBRAIN_GUARD_ROOT` = audited tree). State, logs and `prs.pinned.json` live in `<git-dir>/contributor-audit/<base>-<head>/`; `--resume` refuses on changed refs or pins (`preview_changed`). Human verdicts come only from the verdicts file. Exit 0 clean, 1 review, 2 refusal envelope, 130 interrupted. The fixture builds the offline demo range. Tests: `test/scripts/contributor-audit.test.ts`. Docs: `docs/TESTING.md#contributor-audit`.- `.github/workflows/fix-wave-gate.yml` + `scripts/fix-wave-gate.ts` — the contributor gate. `pull_request_target` on master (`opened`, `edited`, `reopened`, `synchronize`, `labeled`, `unlabeled`); sparse-checks-out only the script from the default branch and never PR code. `decide()` (pure) passes a head repository equal to `TRUSTED_HEAD_REPO` with the base repository's id, or a present `maintainer-override` label whose latest `labeled` timeline event was made by a `User` on `MAINTAINERS` (no `[bot]` login); a null head repository, a missing label or any other labeler fails. Overrides print a `notice` and step-summary line naming the actor, time and event id. `--comment` (the `welcome-comment` job, `pull-requests: write`, `opened` only) posts `gateMessage()` once per PR, keyed by `COMMENT_MARKER`. The script imports only `node:` modules. Tests: `test/scripts/fix-wave-gate.test.ts` (fixture payloads in `test/fixtures/fix-wave-gate/`). Process and the required-check settings step: `docs/RELEASING.md#fix-wave-gate`.+- `.github/workflows/fix-wave-closeout.yml` + `scripts/fix-wave-closeout.ts` — closes what a merged fix wave superseded. `pull_request_target` on master (`closed`); the job runs only when the PR merged and its head repository is `garrytan/gbrain`, and sparse-checks-out only the script from the default branch. `supersededNumbers()` (pure) reads the PR numbers listed right after a line-leading `Supersedes` keyword; `runCloseout()` skips non-PRs and closed PRs, posts `closeoutMessage()` once per PR (keyed by `COMMENT_MARKER`, crediting the contributor only when the wave body says `Contributed by @handle`), closes it, caps a run at `MAX_CLOSES`, and turns a failed close into a warning. `--dry-run` reads without writing. Tests: `test/scripts/fix-wave-closeout.test.ts`. Process: `docs/RELEASING.md#fix-wave-closeout`.diff --git a/scripts/fix-wave-closeout.ts b/scripts/fix-wave-closeout.tsnew file mode 100644index 0000000000..00ded46409--- /dev/null+++ b/scripts/fix-wave-closeout.ts@@ -0,0 +1,170 @@+#!/usr/bin/env bun+/**+ * scripts/fix-wave-closeout.ts — the decision behind .github/workflows/fix-wave-closeout.yml.+ *+ * When a same-repo PR (a fix wave on a capy/* or garrytan/* branch) merges into+ * master, every pull request its body names on a `Supersedes #N` line is closed+ * with a thank-you comment that links the merged PR. Issues need no help here:+ * `Fixes #N` in the same body closes them through GitHub itself.+ *+ * Supersedes #5085+ * - Supersedes #5089, #5096 and #5107+ *+ * Only the list right after the keyword counts, so in "Supersedes #5140, which+ * conflicts with #5000" only #5140 is closed. A number that is not an open pull request is skipped with a log line, so an+ * issue number or an already-closed PR on a Supersedes line is harmless. The+ * comment is keyed by COMMENT_MARKER, so a re-run never comments twice.+ *+ * The workflow runs on pull_request_target, so this file and the workflow come+ * from the default branch. It reads only the event payload and the REST API; it+ * never checks out or runs PR code, and imports nothing outside the runtime so+ * the workflow can sparse-check-out this one file.+ *+ * bun scripts/fix-wave-closeout.ts [--event <payload.json>] [--dry-run]+ *+ * --event defaults to $GITHUB_EVENT_PATH. Always exits 0 unless the payload is+ * missing; a failed close is a warning in the run log and step summary.+ * Docs: docs/RELEASING.md#fix-wave-closeout.+ */+import { appendFileSync, readFileSync } from 'node:fs';++export const TRUSTED_HEAD_REPO = 'garrytan/gbrain';+export const COMMENT_MARKER = '<!-- fix-wave-closeout -->';+export const MAX_CLOSES = 50;++interface Repo { id?: number; full_name?: string }+export interface CloseoutEvent {+ action?: string;+ pull_request?: {+ number: number;+ title?: string;+ merged?: boolean;+ body?: string | null;+ head?: { repo?: Repo | null };+ base?: { repo?: Repo | null; ref?: string };+ };+}+export interface PullInfo { number: number; state: string; login: string; title: string }+export interface CloseoutClient {+ getPull(n: number): Promise<PullInfo | null>;+ commentBodies(n: number): Promise<string[]>;+ createComment(n: number, body: string): Promise<void>;+ close(n: number): Promise<void>;+}+export interface Output { line(s: string): void; summary(s: string): void }++/** Pure. PR numbers named on `Supersedes` lines, in order, deduplicated, without `self`. */+export function supersededNumbers(body: string | null | undefined, self: number): number[] {+ const out: number[] = [];+ for (const line of (body ?? '').split('\n')) {+ const lead = /^\s*(?:[-*]\s+)?\**Supersedes\b/i.exec(line);+ if (!lead) continue;+ const list = /^(?:[\s:*,]|and\b|#\d+\b)+/i.exec(line.slice(lead[0].length))?.[0] ?? '';+ for (const m of list.matchAll(/#(\d+)\b/g)) {+ const n = Number(m[1]);+ if (n !== self && !out.includes(n)) out.push(n);+ }+ }+ return out;+}++export function isMergedWave(event: CloseoutEvent): boolean {+ const pr = event.pull_request;+ const head = pr?.head?.repo, base = pr?.base?.repo;+ return !!pr?.merged && !!head && !!base && head.full_name === TRUSTED_HEAD_REPO && head.id !== undefined && head.id === base.id;+}++export function closeoutMessage(handle: string, wave: number, waveTitle: string, credited: boolean): string {+ const credit = credited+ ? ` with credit to you: the wave says \`Contributed by @${handle}\` and carries a \`Co-Authored-By:\` trailer.`+ : '.';+ return [+ COMMENT_MARKER,+ `Thank you, @${handle}. Fix-wave PR #${wave} (${waveTitle}) merged into master and supersedes this PR, so the change it proposed has landed there${credit}`,+ '',+ `I'm closing this PR because nothing is left for it to land, not because anything was wrong with it. If part of it didn't make it into #${wave}, reply here with what's missing and the next fix wave will pick it up.`,+ '',+ 'This comment comes from the fix-wave closeout workflow.',+ ].join('\n');+}++export async function runCloseout(event: CloseoutEvent, client: CloseoutClient, out: Output, dryRun = false): Promise<number> {+ const pr = event.pull_request;+ if (!pr || !isMergedWave(event)) {+ out.line(`PR #${pr?.number ?? '?'} is not a merged same-repo PR; nothing to close.`);+ return 0;+ }+ const targets = supersededNumbers(pr.body, pr.number);+ if (targets.length === 0) { out.line(`PR #${pr.number} names no Supersedes PRs.`); return 0; }+ const body = pr.body ?? '';+ const rows: string[] = [];+ for (const [i, n] of targets.entries()) {+ if (i >= MAX_CLOSES) { rows.push(`#${n}: skipped, over the ${MAX_CLOSES}-PR cap for one run`); continue; }+ try {+ const target = await client.getPull(n);+ if (!target) { rows.push(`#${n}: skipped, not a pull request`); continue; }+ if (target.state !== 'open') { rows.push(`#${n}: skipped, already ${target.state}`); continue; }+ const credited = body.toLowerCase().includes(`contributed by @${target.login.toLowerCase()}`);+ if (dryRun) { rows.push(`#${n}: would close (@${target.login}${credited ? ', credited' : ''})`); continue; }+ const bodies = await client.commentBodies(n);+ if (!bodies.some(b => b.includes(COMMENT_MARKER))) {+ await client.createComment(n, closeoutMessage(target.login, pr.number, pr.title ?? `#${pr.number}`, credited));+ }+ await client.close(n);+ rows.push(`#${n}: closed (@${target.login}${credited ? ', credited' : ''})`);+ } catch (e) {+ rows.push(`#${n}: FAILED, ${e instanceof Error ? e.message : String(e)}`);+ out.line(`::warning title=Fix-wave closeout::Could not close #${n}. Why: ${e instanceof Error ? e.message : String(e)}. Fix: close it by hand with a comment linking #${pr.number}, or re-run this workflow.`);+ }+ }+ for (const r of rows) out.line(r);+ out.summary(`### Fix-wave closeout for #${pr.number}\n\n${rows.map(r => `- ${r}`).join('\n')}\n`);+ return 0;+}++function restClient(): CloseoutClient {+ const api = process.env.GITHUB_API_URL ?? 'https://api.github.com';+ const repo = process.env.GITHUB_REPOSITORY ?? TRUSTED_HEAD_REPO;+ const token = process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN;+ const call = async (path: string, init: RequestInit = {}): Promise<Response> => fetch(`${api}/repos/${repo}${path}`, {+ ...init,+ headers: { accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28', 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },+ });+ const ok = async (res: Response, what: string) => {+ if (!res.ok) throw new Error(`GitHub API ${what} returned ${res.status}`);+ return res.json();+ };+ return {+ getPull: async n => {+ const res = await call(`/pulls/${n}`);+ if (res.status === 404) return null;+ const p = await ok(res, `GET /pulls/${n}`) as { number: number; state: string; title: string; user?: { login?: string } };+ return { number: p.number, state: p.state, title: p.title, login: p.user?.login ?? 'contributor' };+ },+ commentBodies: async n => {+ const all: string[] = [];+ for (let page = 1; page <= 20; page++) {+ const batch = await ok(await call(`/issues/${n}/comments?per_page=100&page=${page}`), `GET /issues/${n}/comments`) as Array<{ body?: string }>;+ all.push(...batch.map(c => c.body ?? ''));+ if (batch.length < 100) break;+ }+ return all;+ },+ createComment: async (n, body) => { await ok(await call(`/issues/${n}/comments`, { method: 'POST', body: JSON.stringify({ body }) }), `POST /issues/${n}/comments`); },+ close: async n => { await ok(await call(`/pulls/${n}`, { method: 'PATCH', body: JSON.stringify({ state: 'closed' }) }), `PATCH /pulls/${n}`); },+ };+}++if (import.meta.main) {+ const args = process.argv.slice(2);+ const at = args.indexOf('--event');+ const path = at >= 0 ? args[at + 1] : process.env.GITHUB_EVENT_PATH;+ if (!path) {+ console.log('::error title=Fix-wave closeout::No event payload. Why: neither --event nor GITHUB_EVENT_PATH is set. Fix: run inside the fix-wave-closeout workflow or pass --event <payload.json>.');+ process.exit(1);+ }+ const event = JSON.parse(readFileSync(path, 'utf8')) as CloseoutEvent;+ const summaryPath = process.env.GITHUB_STEP_SUMMARY;+ const out: Output = { line: s => console.log(s), summary: s => { if (summaryPath) appendFileSync(summaryPath, s); } };+ process.exit(await runCloseout(event, restClient(), out, args.includes('--dry-run')));+}diff --git a/scripts/fix-wave-gate.ts b/scripts/fix-wave-gate.tsindex 9f0303fba1..1aeb0c97fb 100644--- a/scripts/fix-wave-gate.ts+++ b/scripts/fix-wave-gate.ts@@ -58,7 +58,7 @@ export function gateMessage(handle: string): string {COMMENT_MARKER,`Thanks for this pull request, @${handle}. The work is welcome, and this PR stays open.`,'',- 'gbrain does not merge contributor pull requests into master directly. A maintainer folds the change into a fix-wave PR, revises it there (tests, agent-facing errors, conventions), and lands it with credit to you: the commit says `Contributed by @' + handle + '` and carries a `Co-Authored-By:` trailer with your name.',+ 'gbrain does not merge contributor pull requests into master directly. A maintainer folds the change into a fix-wave PR, revises it there (tests, agent-facing errors, conventions), and lands it with credit to you: the commit says `Contributed by @' + handle + '` and carries a `Co-Authored-By:` trailer with your name. When that fix wave merges, this PR is closed with a comment that links it.','',`You don't need to do anything else. To see where a change belongs and what the fix wave checks, read CONTRIBUTING.md, "Where does my change go?": ${CONTRIBUTING_URL}`,'',diff --git a/test/scripts/fix-wave-closeout.test.ts b/test/scripts/fix-wave-closeout.test.tsnew file mode 100644index 0000000000..ffc9686f46--- /dev/null+++ b/test/scripts/fix-wave-closeout.test.ts@@ -0,0 +1,168 @@+/**+ * .github/workflows/fix-wave-closeout.yml + scripts/fix-wave-closeout.ts — closing what a fix wave superseded.+ *+ * Protects: when a same-repo fix wave merges, every open PR on a `Supersedes #N`+ * line is closed with one thank-you comment linking the wave, and nothing else+ * is touched. Regressions it catches: closing PRs a wave merely mentions, acting+ * on an unmerged or fork PR, commenting twice on a re-run, claiming credit the+ * wave body does not give, and the workflow growing a PR checkout or a+ * pull_request trigger that would run the PR's own copy.+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { safeLoad } from 'js-yaml';+import {+ COMMENT_MARKER, closeoutMessage, isMergedWave, runCloseout, supersededNumbers,+ type CloseoutClient, type CloseoutEvent, type PullInfo,+} from '../../scripts/fix-wave-closeout.ts';++const ROOT = join(import.meta.dir, '..', '..');+const REPO = { id: 1, full_name: 'garrytan/gbrain' };++function wave(body: string, over: Partial<NonNullable<CloseoutEvent['pull_request']>> = {}): CloseoutEvent {+ return { action: 'closed', pull_request: { number: 9000, title: 'v0.60.70.0 fix wave 9', merged: true, body, head: { repo: REPO }, base: { repo: REPO, ref: 'master' }, ...over } };+}++function fakeClient(pulls: Record<number, PullInfo>, comments: Record<number, string[]> = {}) {+ const calls: string[] = [];+ const client: CloseoutClient = {+ getPull: async n => { calls.push(`get ${n}`); return pulls[n] ?? null; },+ commentBodies: async n => comments[n] ?? [],+ createComment: async (n, body) => { calls.push(`comment ${n}`); (comments[n] ??= []).push(body); },+ close: async n => { calls.push(`close ${n}`); pulls[n] = { ...pulls[n]!, state: 'closed' }; },+ };+ return { client, calls, comments };+}++async function run(event: CloseoutEvent, client: CloseoutClient, dryRun = false) {+ const lines: string[] = [];+ const summary: string[] = [];+ const code = await runCloseout(event, client, { line: s => lines.push(s), summary: s => summary.push(s) }, dryRun);+ return { code, out: lines.join('\n'), summary: summary.join('') };+}++const open = (number: number, login = 'alice-example'): PullInfo => ({ number, state: 'open', login, title: `fix ${number}` });++describe('supersededNumbers', () => {+ test('reads bare, bulleted, bold and list forms, in order, without duplicates', () => {+ const body = [+ 'Fixes #100.',+ 'Supersedes #5085',+ '- Supersedes #5089, #5096 and #5107',+ '* **Supersedes:** #5113',+ 'supersedes #5085 again',+ ].join('\n');+ expect(supersededNumbers(body, 9000)).toEqual([5085, 5089, 5096, 5107, 5113]);+ });++ test('ignores mentions outside a leading Supersedes list', () => {+ const body = [+ 'Fixes #5490. Supersedes #5140, which no longer merges.',+ 'Supersedes #5140, which conflicts with #5000 in gateway.ts',+ '| #5133 | adopted scope |',+ 'This supersedes nothing: see #4954.',+ ].join('\n');+ expect(supersededNumbers(body, 9000)).toEqual([5140]);+ });++ test('never names the wave itself and tolerates an empty body', () => {+ expect(supersededNumbers('Supersedes #9000 and #1', 9000)).toEqual([1]);+ expect(supersededNumbers(null, 9000)).toEqual([]);+ });+});++describe('fix-wave closeout run', () => {+ test('closes each open superseded PR with one comment linking the wave', async () => {+ const { client, calls, comments } = fakeClient({ 5085: open(5085), 5089: open(5089, 'bob-example') });+ const r = await run(wave('Supersedes #5085 and #5089\n\nContributed by @alice-example'), client);+ expect(r.code).toBe(0);+ expect(calls).toEqual(['get 5085', 'comment 5085', 'close 5085', 'get 5089', 'comment 5089', 'close 5089']);+ expect(comments[5085]![0]).toContain(COMMENT_MARKER);+ expect(comments[5085]![0]).toContain('Fix-wave PR #9000 (v0.60.70.0 fix wave 9)');+ expect(comments[5085]![0]).toContain('`Contributed by @alice-example`');+ expect(comments[5089]![0]).not.toContain('Contributed by');+ expect(r.summary).toContain('#5085: closed (@alice-example, credited)');+ expect(r.summary).toContain('#5089: closed (@bob-example)');+ });++ test('skips issues, closed PRs and an existing comment, and never fails the run', async () => {+ const { client, calls } = fakeClient(+ { 5140: { ...open(5140), state: 'closed' }, 5156: open(5156) },+ { 5156: [`${COMMENT_MARKER}\nalready said thanks`] },+ );+ const r = await run(wave('Supersedes #5134, #5140 and #5156'), client);+ expect(r.code).toBe(0);+ expect(calls).toEqual(['get 5134', 'get 5140', 'get 5156', 'close 5156']);+ expect(r.out).toContain('#5134: skipped, not a pull request');+ expect(r.out).toContain('#5140: skipped, already closed');+ });++ test('a failed close is a warning with a fix, and later PRs still close', async () => {+ const { client, calls } = fakeClient({ 1: open(1), 2: open(2) });+ const failing: CloseoutClient = { ...client, close: async n => { if (n === 1) throw new Error('GitHub API PATCH /pulls/1 returned 403'); await client.close(n); } };+ const r = await run(wave('Supersedes #1, #2'), failing);+ expect(r.code).toBe(0);+ expect(r.out).toContain('::warning title=Fix-wave closeout::Could not close #1.');+ expect(r.out).toContain('Fix: close it by hand');+ expect(calls).toContain('close 2');+ });++ test('does nothing for an unmerged PR, a fork PR or a deleted fork', async () => {+ const forkRepo = { id: 2, full_name: 'alice-example/gbrain' };+ for (const event of [+ wave('Supersedes #1', { merged: false }),+ wave('Supersedes #1', { head: { repo: forkRepo } }),+ wave('Supersedes #1', { head: { repo: null } }),+ wave('Supersedes #1', { head: { repo: { id: 2, full_name: 'garrytan/gbrain' } } }),+ ]) {+ const { client, calls } = fakeClient({ 1: open(1) });+ expect(isMergedWave(event)).toBe(false);+ await run(event, client);+ expect(calls).toEqual([]);+ }+ });++ test('--dry-run reads but never writes', async () => {+ const { client, calls } = fakeClient({ 1: open(1) });+ const r = await run(wave('Supersedes #1'), client, true);+ expect(calls).toEqual(['get 1']);+ expect(r.out).toContain('#1: would close (@alice-example)');+ });++ test('the message thanks the contributor and invites a follow-up', () => {+ const m = closeoutMessage('alice-example', 9000, 'wave 9', false);+ expect(m.startsWith(COMMENT_MARKER)).toBe(true);+ expect(m).toContain('Thank you, @alice-example.');+ expect(m).toContain('not because anything was wrong with it');+ expect(m).toContain("reply here with what's missing");+ });+});++describe('fix-wave-closeout workflow', () => {+ const wf = safeLoad(readFileSync(join(ROOT, '.github', 'workflows', 'fix-wave-closeout.yml'), 'utf8')) as {+ on: Record<string, { branches?: string[]; types?: string[] }>;+ permissions: Record<string, string>;+ jobs: Record<string, { if?: string; permissions: Record<string, string>; steps: Array<{ uses?: string; with?: Record<string, unknown>; run?: string }> }>;+ };++ test('runs only from the default branch on a merged same-repo PR into master', () => {+ expect(Object.keys(wf.on)).toEqual(['pull_request_target']);+ expect(wf.on.pull_request_target!.branches).toEqual(['master']);+ expect(wf.on.pull_request_target!.types).toEqual(['closed']);+ const job = wf.jobs['close-superseded']!;+ expect(job.if).toContain('github.event.pull_request.merged == true');+ expect(job.if).toContain("github.event.pull_request.head.repo.full_name == 'garrytan/gbrain'");+ });++ test('checks out only the script, never PR code, with least privilege', () => {+ expect(wf.permissions).toEqual({});+ const job = wf.jobs['close-superseded']!;+ expect(job.permissions).toEqual({ contents: 'read', 'pull-requests': 'write' });+ const checkout = job.steps.find(s => s.uses?.startsWith('actions/checkout@'))!;+ expect(checkout.with).toMatchObject({ 'persist-credentials': false, 'sparse-checkout': 'scripts/fix-wave-closeout.ts' });+ expect(checkout.with).not.toHaveProperty('ref');+ expect(checkout.with).not.toHaveProperty('repository');+ expect(job.steps.flatMap(s => s.run ? [s.run] : [])).toEqual(['bun scripts/fix-wave-closeout.ts']);+ });+});