Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
ci: fix-wave gate fails contributor PRs into master unless a maintainer overrides
garrytan00c7c2e2b4ea
diff --git a/.github/workflows/fix-wave-gate.yml b/.github/workflows/fix-wave-gate.ymlnew file mode 100644index 0000000000..87ab57dbe4--- /dev/null+++ b/.github/workflows/fix-wave-gate.yml@@ -0,0 +1,66 @@+name: Fix-wave gate++# Contributor PRs land only through a revised fix-wave PR (docs/RELEASING.md,+# "Fix-wave gate"). This check fails every PR into master unless its head+# repository is garrytan/gbrain, or a human on the maintainer allowlist in+# scripts/fix-wave-gate.ts applied the `maintainer-override` label (audited in+# the run log and step summary).+#+# pull_request_target runs this file and the checked-out script from the+# default branch, so a PR that edits either cannot change its own result. It+# reads only event metadata and the PR timeline: it NEVER checks out, builds or+# runs PR code. Required-check status is a repository setting a maintainer+# turns on (docs/RELEASING.md#fix-wave-gate); until then the check is advisory.++on:+ pull_request_target:+ branches: [master]+ types: [opened, edited, reopened, synchronize, labeled, unlabeled]++permissions: {}++concurrency:+ group: fix-wave-gate-${{ github.event.pull_request.number }}+ cancel-in-progress: true++jobs:+ contributor-gate:+ runs-on: ubicloud-standard-2-ubuntu-2404+ timeout-minutes: 5+ permissions:+ contents: read+ pull-requests: read+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ persist-credentials: false+ sparse-checkout: scripts/fix-wave-gate.ts+ sparse-checkout-cone-mode: false+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.2+ - name: Decide+ env:+ GH_TOKEN: ${{ github.token }}+ run: bun scripts/fix-wave-gate.ts++ welcome-comment:+ if: github.event.action == 'opened'+ runs-on: ubicloud-standard-2-ubuntu-2404+ timeout-minutes: 5+ permissions:+ contents: read+ pull-requests: write+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ persist-credentials: false+ sparse-checkout: scripts/fix-wave-gate.ts+ sparse-checkout-cone-mode: false+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.2+ - name: Post the welcome comment once on a contributor PR+ env:+ GH_TOKEN: ${{ github.token }}+ run: bun scripts/fix-wave-gate.ts --commentdiff --git a/scripts/fix-wave-gate.ts b/scripts/fix-wave-gate.tsnew file mode 100644index 0000000000..9f0303fba1--- /dev/null+++ b/scripts/fix-wave-gate.ts@@ -0,0 +1,173 @@+#!/usr/bin/env bun+/**+ * scripts/fix-wave-gate.ts — the decision behind .github/workflows/fix-wave-gate.yml.+ *+ * A pull request into master passes when either:+ * - its head repository is garrytan/gbrain (only maintainers can push+ * there; covers capy/* and garrytan/* branches), or+ * - the `maintainer-override` label is on it AND the most recent `labeled`+ * timeline event for that label was made by a human on MAINTAINERS.+ * Bots never qualify, including capy-ai[bot] and github-actions[bot].+ * Everything else fails, including a null head repository (a deleted fork).+ *+ * The workflow runs on pull_request_target, so both this file and the workflow+ * come from the default branch: a PR that edits either cannot change its own+ * result. This file reads only the event payload and the PR's timeline and+ * comments through the REST API; it never sees PR code. It imports nothing+ * outside the runtime so the workflow can sparse-check-out this one file.+ *+ * bun scripts/fix-wave-gate.ts [--event <payload.json>] [--comment]+ *+ * --event defaults to $GITHUB_EVENT_PATH. Without --comment it is the gate+ * (exit 0 pass, 1 fail). With --comment it posts the welcome comment once on a+ * failing PR (marker COMMENT_MARKER) and always exits 0.+ * Docs: docs/RELEASING.md#fix-wave-gate, CONTRIBUTING.md.+ */+import { appendFileSync, readFileSync } from 'node:fs';++export const TRUSTED_HEAD_REPO = 'garrytan/gbrain';+export const OVERRIDE_LABEL = 'maintainer-override';+/** Humans who may apply the override label. Edit only through a reviewed PR to master. */+export const MAINTAINERS: readonly string[] = ['garrytan'];+export const COMMENT_MARKER = '<!-- fix-wave-gate -->';+const CONTRIBUTING_URL = 'https://github.com/garrytan/gbrain/blob/master/CONTRIBUTING.md#where-does-my-change-go';++interface Repo { id?: number; full_name?: string }+interface Actor { login?: string; type?: string }+export interface GateEvent {+ action?: string;+ pull_request?: {+ number: number;+ user?: Actor;+ labels?: Array<{ name?: string }>;+ head?: { repo?: Repo | null };+ base?: { repo?: Repo | null };+ };+}+export interface TimelineEvent { id?: number; event?: string; label?: { name?: string }; actor?: Actor | null; created_at?: string }+export type Reason = 'same_repo' | 'maintainer_override' | 'override_not_by_maintainer' | 'fork' | 'head_repo_missing' | 'not_a_pull_request';+export interface Decision { pass: boolean; reason: Reason; log: string[] }+export interface GateClient {+ labelEvents(pr: number): Promise<TimelineEvent[]>;+ commentBodies(pr: number): Promise<string[]>;+ createComment(pr: number, body: string): Promise<void>;+}++export function gateMessage(handle: string): string {+ return [+ 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.',+ '',+ `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}`,+ '',+ 'This message comes from the fix-wave gate check, which stays red on contributor PRs by design.',+ ].join('\n');+}++export function isHumanMaintainer(actor: Actor | null | undefined): boolean {+ if (!actor?.login) return false;+ if (actor.type !== 'User' || actor.login.endsWith('[bot]')) return false;+ return MAINTAINERS.includes(actor.login);+}++export function needsTimeline(event: GateEvent): boolean {+ const pr = event.pull_request;+ return !!pr && !sameRepo(pr) && (pr.labels ?? []).some(l => l.name === OVERRIDE_LABEL);+}++function sameRepo(pr: NonNullable<GateEvent['pull_request']>): boolean {+ const head = pr.head?.repo, base = pr.base?.repo;+ return !!head && !!base && head.full_name === TRUSTED_HEAD_REPO && head.id !== undefined && head.id === base.id;+}++/** Pure. `timeline` is the PR's issue events in chronological order; read only when needsTimeline(). */+export function decide(event: GateEvent, timeline: TimelineEvent[]): Decision {+ const pr = event.pull_request;+ if (!pr) return { pass: false, reason: 'not_a_pull_request', log: ['The event has no pull_request; failing closed.'] };+ const head = pr.head?.repo;+ const log = [`PR #${pr.number} by @${pr.user?.login ?? 'unknown'}; head repository ${head?.full_name ?? 'null (deleted fork)'}.`];+ if (sameRepo(pr)) return { pass: true, reason: 'same_repo', log: [...log, `Head repository is ${TRUSTED_HEAD_REPO}: only maintainers can push there. Pass.`] };+ const fallback: Reason = head ? 'fork' : 'head_repo_missing';+ if (!(pr.labels ?? []).some(l => l.name === OVERRIDE_LABEL)) return { pass: false, reason: fallback, log: [...log, `No ${OVERRIDE_LABEL} label. Fail.`] };+ const applied = timeline.filter(e => e.event === 'labeled' && e.label?.name === OVERRIDE_LABEL).at(-1);+ const who = applied?.actor ? `@${applied.actor.login} (${applied.actor.type ?? 'unknown type'})` : 'an unknown actor';+ const audit = `${OVERRIDE_LABEL} applied by ${who} at ${applied?.created_at ?? 'unknown time'} (timeline event ${applied?.id ?? 'not found'})`;+ if (applied && isHumanMaintainer(applied.actor)) return { pass: true, reason: 'maintainer_override', log: [...log, `${audit}. Maintainer allowlist: ${MAINTAINERS.join(', ')}. Pass.`] };+ return { pass: false, reason: 'override_not_by_maintainer', log: [...log, `${audit}. Only a human on the maintainer allowlist (${MAINTAINERS.join(', ')}) can override. Fail.`] };+}++export interface Output { line(s: string): void; summary(s: string): void }++export async function runGate(event: GateEvent, client: GateClient, out: Output, mode: 'gate' | 'comment'): Promise<number> {+ let timeline: TimelineEvent[] = [];+ if (needsTimeline(event)) {+ try { timeline = await client.labelEvents(event.pull_request!.number); } catch (e) {+ out.line(`::error title=Fix-wave gate::Could not read the PR timeline to audit the ${OVERRIDE_LABEL} label. Why: ${e instanceof Error ? e.message : String(e)}. Fix: re-run this check from the PR's Checks tab; if it repeats, confirm the workflow still has pull-requests: read.`);+ return mode === 'gate' ? 1 : 0;+ }+ }+ const d = decide(event, timeline);+ for (const l of d.log) out.line(d.reason === 'maintainer_override' ? `::notice title=Fix-wave gate override::${l}` : l);+ out.summary(`### Fix-wave gate: ${d.pass ? 'pass' : 'fail'} (${d.reason})\n\n${d.log.map(l => `- ${l}`).join('\n')}\n`);+ const handle = event.pull_request?.user?.login ?? 'contributor';+ if (mode === 'comment') {+ if (d.pass || !event.pull_request) return 0;+ try {+ const bodies = await client.commentBodies(event.pull_request.number);+ if (bodies.some(b => b.includes(COMMENT_MARKER))) { out.line('Welcome comment already posted.'); return 0; }+ await client.createComment(event.pull_request.number, gateMessage(handle));+ out.line('Posted the welcome comment.');+ } catch (e) {+ out.line(`::warning title=Fix-wave gate::Could not post the welcome comment: ${e instanceof Error ? e.message : String(e)}`);+ }+ return 0;+ }+ if (d.pass) return 0;+ out.line(`::error title=Fix-wave gate::${gateMessage(handle).replace(COMMENT_MARKER + '\n', '').replace(/\n+/g, ' ')}`);+ out.line(`Maintainers: a human on the allowlist (${MAINTAINERS.join(', ')}) can apply the ${OVERRIDE_LABEL} label to pass this check; see docs/RELEASING.md#fix-wave-gate.`);+ return 1;+}++function restClient(): GateClient {+ 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 = {}) => {+ const res = await fetch(`${api}/repos/${repo}${path}`, {+ ...init,+ headers: { accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28', ...(token ? { authorization: `Bearer ${token}` } : {}), ...(init.headers ?? {}) },+ });+ if (!res.ok) throw new Error(`GitHub API ${init.method ?? 'GET'} ${path} returned ${res.status}`);+ return res.json();+ };+ const pages = async <T>(path: string): Promise<T[]> => {+ const all: T[] = [];+ for (let page = 1; page <= 50; page++) {+ const batch = await call(`${path}?per_page=100&page=${page}`) as T[];+ all.push(...batch);+ if (batch.length < 100) return all;+ }+ throw new Error(`${path} has more than 5000 entries`);+ };+ return {+ labelEvents: pr => pages<TimelineEvent>(`/issues/${pr}/events`),+ commentBodies: async pr => (await pages<{ body?: string }>(`/issues/${pr}/comments`)).map(c => c.body ?? ''),+ createComment: async (pr, body) => { await call(`/issues/${pr}/comments`, { method: 'POST', body: JSON.stringify({ body }), headers: { 'content-type': 'application/json' } }); },+ };+}++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 gate::No event payload. Why: neither --event nor GITHUB_EVENT_PATH is set. Fix: run inside the fix-wave-gate workflow or pass --event <payload.json>.');+ process.exit(1);+ }+ const event = JSON.parse(readFileSync(path, 'utf8')) as GateEvent;+ 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 runGate(event, restClient(), out, args.includes('--comment') ? 'comment' : 'gate'));+}diff --git a/test/fixtures/fix-wave-gate/deleted-fork.synchronize.json b/test/fixtures/fix-wave-gate/deleted-fork.synchronize.jsonnew file mode 100644index 0000000000..300b16d448--- /dev/null+++ b/test/fixtures/fix-wave-gate/deleted-fork.synchronize.json@@ -0,0 +1,36 @@+{+ "action": "synchronize",+ "pull_request": {+ "number": 9004,+ "title": "fix: something",+ "user": {+ "login": "alice-example",+ "type": "User"+ },+ "labels": [],+ "head": {+ "ref": "patch-2",+ "sha": "1111111111111111111111111111111111111111",+ "repo": null,+ "user": {+ "login": "alice-example"+ }+ },+ "base": {+ "ref": "master",+ "sha": "2222222222222222222222222222222222222222",+ "repo": {+ "id": 1000000001,+ "full_name": "garrytan/gbrain"+ }+ }+ },+ "repository": {+ "id": 1000000001,+ "full_name": "garrytan/gbrain"+ },+ "sender": {+ "login": "alice-example",+ "type": "User"+ }+}diff --git a/test/fixtures/fix-wave-gate/fork-edits-gate.synchronize.json b/test/fixtures/fix-wave-gate/fork-edits-gate.synchronize.jsonnew file mode 100644index 0000000000..d326de32fb--- /dev/null+++ b/test/fixtures/fix-wave-gate/fork-edits-gate.synchronize.json@@ -0,0 +1,40 @@+{+ "action": "synchronize",+ "pull_request": {+ "number": 9005,+ "title": "ci: let fix-wave-gate pass every PR",+ "user": {+ "login": "alice-example",+ "type": "User"+ },+ "labels": [],+ "head": {+ "ref": "garrytan/fix-wave-gate",+ "sha": "1111111111111111111111111111111111111111",+ "repo": {+ "id": 2000000002,+ "full_name": "alice-example/gbrain",+ "fork": true+ },+ "user": {+ "login": "alice-example"+ }+ },+ "base": {+ "ref": "master",+ "sha": "2222222222222222222222222222222222222222",+ "repo": {+ "id": 1000000001,+ "full_name": "garrytan/gbrain"+ }+ }+ },+ "repository": {+ "id": 1000000001,+ "full_name": "garrytan/gbrain"+ },+ "sender": {+ "login": "alice-example",+ "type": "User"+ }+}diff --git a/test/fixtures/fix-wave-gate/fork-gbra-branch.opened.json b/test/fixtures/fix-wave-gate/fork-gbra-branch.opened.jsonnew file mode 100644index 0000000000..0dd335fbb6--- /dev/null+++ b/test/fixtures/fix-wave-gate/fork-gbra-branch.opened.json@@ -0,0 +1,40 @@+{+ "action": "opened",+ "pull_request": {+ "number": 9001,+ "title": "fix: something",+ "user": {+ "login": "alice-example",+ "type": "User"+ },+ "labels": [],+ "head": {+ "ref": "capy/gbra-42-fix-sync",+ "sha": "1111111111111111111111111111111111111111",+ "repo": {+ "id": 2000000002,+ "full_name": "alice-example/gbrain",+ "fork": true+ },+ "user": {+ "login": "alice-example"+ }+ },+ "base": {+ "ref": "master",+ "sha": "2222222222222222222222222222222222222222",+ "repo": {+ "id": 1000000001,+ "full_name": "garrytan/gbrain"+ }+ }+ },+ "repository": {+ "id": 1000000001,+ "full_name": "garrytan/gbrain"+ },+ "sender": {+ "login": "alice-example",+ "type": "User"+ }+}diff --git a/test/fixtures/fix-wave-gate/fork-override.labeled.json b/test/fixtures/fix-wave-gate/fork-override.labeled.jsonnew file mode 100644index 0000000000..fd2e26ebca--- /dev/null+++ b/test/fixtures/fix-wave-gate/fork-override.labeled.json@@ -0,0 +1,47 @@+{+ "action": "labeled",+ "label": {+ "name": "maintainer-override"+ },+ "pull_request": {+ "number": 9003,+ "title": "fix: something",+ "user": {+ "login": "alice-example",+ "type": "User"+ },+ "labels": [+ {+ "name": "maintainer-override"+ }+ ],+ "head": {+ "ref": "patch-1",+ "sha": "1111111111111111111111111111111111111111",+ "repo": {+ "id": 2000000002,+ "full_name": "alice-example/gbrain",+ "fork": true+ },+ "user": {+ "login": "alice-example"+ }+ },+ "base": {+ "ref": "master",+ "sha": "2222222222222222222222222222222222222222",+ "repo": {+ "id": 1000000001,+ "full_name": "garrytan/gbrain"+ }+ }+ },+ "repository": {+ "id": 1000000001,+ "full_name": "garrytan/gbrain"+ },+ "sender": {+ "login": "garrytan",+ "type": "User"+ }+}diff --git a/test/fixtures/fix-wave-gate/same-repo.synchronize.json b/test/fixtures/fix-wave-gate/same-repo.synchronize.jsonnew file mode 100644index 0000000000..885df42076--- /dev/null+++ b/test/fixtures/fix-wave-gate/same-repo.synchronize.json@@ -0,0 +1,40 @@+{+ "action": "synchronize",+ "pull_request": {+ "number": 9002,+ "title": "fix: something",+ "user": {+ "login": "garrytan",+ "type": "User"+ },+ "labels": [],+ "head": {+ "ref": "capy/gbra-42-fix-sync",+ "sha": "1111111111111111111111111111111111111111",+ "repo": {+ "id": 1000000001,+ "full_name": "garrytan/gbrain",+ "fork": false+ },+ "user": {+ "login": "garrytan"+ }+ },+ "base": {+ "ref": "master",+ "sha": "2222222222222222222222222222222222222222",+ "repo": {+ "id": 1000000001,+ "full_name": "garrytan/gbrain"+ }+ }+ },+ "repository": {+ "id": 1000000001,+ "full_name": "garrytan/gbrain"+ },+ "sender": {+ "login": "garrytan",+ "type": "User"+ }+}diff --git a/test/scripts/fix-wave-gate.test.ts b/test/scripts/fix-wave-gate.test.tsnew file mode 100644index 0000000000..25bacfe655--- /dev/null+++ b/test/scripts/fix-wave-gate.test.ts@@ -0,0 +1,169 @@+/**+ * .github/workflows/fix-wave-gate.yml + scripts/fix-wave-gate.ts — the contributor gate.+ *+ * Protects: contributor PRs into master fail unless the head repository is+ * garrytan/gbrain or a human maintainer applied `maintainer-override`; GBRA+ * thread PRs (same-repo heads) always pass; a PR cannot change its own result+ * by editing the workflow or script. Regressions it catches: trusting a branch+ * name instead of the head repository, a bot or non-maintainer override, a+ * null head.repo passing, 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 { spawnSync } from 'node:child_process';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { safeLoad } from 'js-yaml';+import {+ COMMENT_MARKER, MAINTAINERS, OVERRIDE_LABEL, decide, gateMessage, runGate,+ type GateClient, type GateEvent, type TimelineEvent,+} from '../../scripts/fix-wave-gate.ts';++const ROOT = join(import.meta.dir, '..', '..');+const FIXTURES = join(ROOT, 'test', 'fixtures', 'fix-wave-gate');+const load = (name: string) => JSON.parse(readFileSync(join(FIXTURES, name), 'utf8')) as GateEvent;+const labeled = (login: string, type: string, id: number): TimelineEvent =>+ ({ id, event: 'labeled', label: { name: OVERRIDE_LABEL }, actor: { login, type }, created_at: `2026-10-05T0${id}:00:00Z` });++function fakeClient(timeline: TimelineEvent[] = [], comments: string[] = []) {+ const calls: string[] = [];+ const client: GateClient = {+ labelEvents: async () => { calls.push('labelEvents'); return timeline; },+ commentBodies: async () => { calls.push('commentBodies'); return comments; },+ createComment: async (_pr, body) => { calls.push('createComment'); comments.push(body); },+ };+ return { client, calls, comments };+}+async function gate(event: GateEvent, client: GateClient, mode: 'gate' | 'comment' = 'gate') {+ const lines: string[] = [];+ const summary: string[] = [];+ const code = await runGate(event, client, { line: s => lines.push(s), summary: s => summary.push(s) }, mode);+ return { code, out: lines.join('\n'), summary: summary.join('') };+}++describe('fix-wave gate decision', () => {+ test('a fork PR with a GBRA-looking branch name fails with the fix-wave message', async () => {+ const { client, calls } = fakeClient();+ const r = await gate(load('fork-gbra-branch.opened.json'), client);+ expect(r.code).toBe(1);+ expect(r.out).toContain('The work is welcome, and this PR stays open.');+ expect(r.out).toContain('Contributed by @alice-example');+ expect(r.out).toContain('Co-Authored-By:');+ expect(r.out).toContain('CONTRIBUTING.md#where-does-my-change-go');+ expect(r.summary).toContain('fail (fork)');+ expect(calls).toEqual([]);+ });++ test('a same-repo head (a GBRA thread capy/* branch) passes without any API call', async () => {+ const { client, calls } = fakeClient();+ const r = await gate(load('same-repo.synchronize.json'), client);+ expect(r.code).toBe(0);+ expect(r.summary).toContain('pass (same_repo)');+ expect(calls).toEqual([]);+ });++ test('the override label passes only when a human maintainer applied it, and the run log names who', async () => {+ const event = load('fork-override.labeled.json');+ const ok = await gate(event, fakeClient([labeled('garrytan', 'User', 1)]).client);+ expect(ok.code).toBe(0);+ expect(ok.out).toContain('::notice title=Fix-wave gate override::');+ expect(ok.out).toContain(`${OVERRIDE_LABEL} applied by @garrytan (User) at 2026-10-05T01:00:00Z (timeline event 1)`);++ for (const actor of [['capy-ai[bot]', 'Bot'], ['github-actions[bot]', 'Bot'], ['alice-example', 'User'], ['garrytan[bot]', 'User']] as const) {+ const r = await gate(event, fakeClient([labeled(actor[0], actor[1], 2)]).client);+ expect(r.code, actor[0]).toBe(1);+ expect(r.summary).toContain('override_not_by_maintainer');+ }+ const relabeledByBot = await gate(event, fakeClient([+ labeled('garrytan', 'User', 1),+ { id: 2, event: 'unlabeled', label: { name: OVERRIDE_LABEL }, actor: { login: 'garrytan', type: 'User' } },+ labeled('capy-ai[bot]', 'Bot', 3),+ ]).client);+ expect(relabeledByBot.code).toBe(1);+ const noTimeline = await gate(event, fakeClient([]).client);+ expect(noTimeline.code).toBe(1);+ });++ test('removing the label fails again even though the timeline still shows the old override', () => {+ const event = load('fork-override.labeled.json');+ event.pull_request!.labels = [];+ expect(decide(event, [labeled('garrytan', 'User', 1)])).toMatchObject({ pass: false, reason: 'fork' });+ });++ test('a null head repository fails closed', async () => {+ const r = await gate(load('deleted-fork.synchronize.json'), fakeClient().client);+ expect(r.code).toBe(1);+ expect(r.summary).toContain('head_repo_missing');+ expect(decide({}, []).pass).toBe(false);+ });++ test('a timeline read failure fails closed', async () => {+ const client: GateClient = { ...fakeClient().client, labelEvents: async () => { throw new Error('HTTP 502'); } };+ const r = await gate(load('fork-override.labeled.json'), client);+ expect(r.code).toBe(1);+ expect(r.out).toContain('Could not read the PR timeline');+ });++ test('the welcome comment posts once on a contributor PR and never on a same-repo PR', async () => {+ const fake = fakeClient();+ const first = await gate(load('fork-gbra-branch.opened.json'), fake.client, 'comment');+ expect(first.code).toBe(0);+ expect(fake.comments).toHaveLength(1);+ expect(fake.comments[0]).toBe(gateMessage('alice-example'));+ expect(fake.comments[0].startsWith(COMMENT_MARKER)).toBe(true);+ await gate(load('fork-gbra-branch.opened.json'), fake.client, 'comment');+ expect(fake.comments).toHaveLength(1);+ const same = fakeClient();+ await gate(load('same-repo.synchronize.json'), same.client, 'comment');+ expect(same.calls).toEqual([]);+ });++ test('the maintainer allowlist starts with garrytan and holds no bots', () => {+ expect(MAINTAINERS).toEqual(['garrytan']);+ for (const m of MAINTAINERS) expect(m).not.toContain('[bot]');+ });+});++describe('fix-wave gate workflow', () => {+ const text = readFileSync(join(ROOT, '.github', 'workflows', 'fix-wave-gate.yml'), 'utf8');+ type Step = { uses?: string; run?: string; with?: Record<string, unknown>; env?: Record<string, string> };+ const wf = safeLoad(text) as { on: Record<string, { branches: string[]; types: string[] }>; permissions: unknown; jobs: Record<string, { permissions: Record<string, string>; steps: Step[]; if?: string }> };++ test('a PR that edits the workflow or the gate script cannot change its own result', async () => {+ // pull_request_target runs the default-branch copy of both files; a pull_request trigger would run the PR's copy.+ 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].sort()).toEqual(['edited', 'labeled', 'opened', 'reopened', 'synchronize', 'unlabeled']);+ for (const job of Object.values(wf.jobs)) {+ const checkout = job.steps.find(s => s.uses?.startsWith('actions/checkout@'))!;+ expect(checkout.with).toEqual({ 'persist-credentials': false, 'sparse-checkout': 'scripts/fix-wave-gate.ts', 'sparse-checkout-cone-mode': false });+ }+ expect(text).not.toMatch(/pull_request\.head|refs\/pull|head\.sha|head_ref|\bref:/);+ for (const job of Object.values(wf.jobs)) for (const s of job.steps) expect(s.run ?? '').not.toContain('${{');+ // The decision never reads the PR's files, so a fork PR that rewrites the gate still fails.+ expect((await gate(load('fork-edits-gate.synchronize.json'), fakeClient().client)).code).toBe(1);+ });++ test('permissions are minimal, actions are pinned by SHA and the script needs no dependencies', () => {+ expect(wf.permissions).toEqual({});+ expect(wf.jobs['contributor-gate'].permissions).toEqual({ contents: 'read', 'pull-requests': 'read' });+ expect(wf.jobs['welcome-comment'].permissions).toEqual({ contents: 'read', 'pull-requests': 'write' });+ expect(wf.jobs['welcome-comment'].if).toBe("github.event.action == 'opened'");+ for (const job of Object.values(wf.jobs)) for (const s of job.steps) if (s.uses) expect(s.uses).toMatch(/@[0-9a-f]{40}$/);+ const script = readFileSync(join(ROOT, 'scripts', 'fix-wave-gate.ts'), 'utf8');+ const imports = [...script.matchAll(/^import .* from '([^']+)';$/gm)].map(m => m[1]);+ expect(imports.every(i => i.startsWith('node:'))).toBe(true);+ });++ test('the CLI entry decides offline from an event payload', () => {+ const run = (name: string) => spawnSync(process.execPath, [join(ROOT, 'scripts', 'fix-wave-gate.ts'), '--event', join(FIXTURES, name)], {+ encoding: 'utf8', env: { PATH: process.env.PATH, GITHUB_API_URL: 'http://127.0.0.1:9' },+ });+ const same = run('same-repo.synchronize.json');+ expect(same.status).toBe(0);+ expect(same.stdout).toContain('Pass.');+ const fork = run('fork-edits-gate.synchronize.json');+ expect(fork.status).toBe(1);+ expect(fork.stdout).toContain('::error title=Fix-wave gate::');+ });+});