From 973b49eabb82c456aed8af9237f9bf8786ebddad Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Sat, 21 Nov 2026 18:14:15 -0800 Subject: [PATCH] Pull requests get a Test changes summary of deleted or skipped tests and edits to their own checks (GST-3386) (#4645) Every gstack pull request now gets a flag-only Test changes check listing removed or skipped tests, loosened limits and edits to the files that run its own checks. Why: agents write most of our tests, and a pull request shouldn't be able to quietly weaken them or grade itself with an edited checker; this two-week trial measures how often that happens. Nothing to do: the check isn't required, and a flag never turns it red. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team Review-Finding: lib/gate-diff/git.ts:314:stale-comment reader=core Review-Finding: p3/outside-voice#1 reader=outside-voice --- .github/workflows/test-changes.yml | 68 +++++++++ bin/gstack-gate-diff | 44 ++++-- changelog.d/test-changes-report.md | 1 + docs/ship-policy.md | 40 +++++ lib/gate-diff/git.ts | 10 +- .../scripts/test-pr-profile.ts.json | 2 +- scripts/test-changes-report.ts | 91 ++++++++++++ scripts/test-pr-profile.ts | 1 + test/gate-diff-cli.test.ts | 2 +- test/test-changes-report.test.ts | 139 ++++++++++++++++++ test/test-changes-workflow-safety.test.ts | 68 +++++++++ 11 files changed, 451 insertions(+), 15 deletions(-) create mode 100644 .github/workflows/test-changes.yml create mode 100644 changelog.d/test-changes-report.md create mode 100755 scripts/test-changes-report.ts create mode 100644 test/test-changes-report.test.ts create mode 100644 test/test-changes-workflow-safety.test.ts diff --git a/.github/workflows/test-changes.yml b/.github/workflows/test-changes.yml new file mode 100644 index 000000000..6f594e495 --- /dev/null +++ b/.github/workflows/test-changes.yml @@ -0,0 +1,68 @@ +name: Test changes + +# Flag-only report of what a pull request does to its own tests and checks +# (docs/ship-policy.md#test-changes): tests removed or skipped, suppressions, +# gate bypasses and relaxed gate values that bin/gstack-gate-diff tags, the net +# count of added and removed test declarations, and edits to the files that run +# or define this repository's own checks. Flags never fail it: they exit 0. It +# fails only when the checker itself fails, so a broken run is never read as a +# quiet pull request; like any failed check, that holds gstack-ship-queue land +# until the job is rerun. Not a required check. +# +# WHY pull_request_target: it runs the base repository's copy of this workflow, +# of scripts/test-changes-report.ts and of bin/gstack-gate-diff, so a pull +# request cannot edit the checker that reports on it. +# +# WHY this is SAFE: +# - The job checks out the BASE repo (no ref:) and never runs PR code. The +# pull request's commits are fetched as git objects and read as a diff. +# - The token is read-only (contents: read) and is not persisted; no secrets. +# - PR fields arrive only through env:; none is inlined into run:. +# - The report names paths, tags and hunk ids, never PR line content. +# test/test-changes-workflow-safety.test.ts is the static tripwire for all of it. + +on: + pull_request_target: + types: [opened, synchronize, reopened] + +permissions: + contents: read + +jobs: + test-changes: + name: Test changes + runs-on: ubuntu-24.04 + timeout-minutes: 10 + concurrency: + group: test-changes-${{ github.event.pull_request.number }} + cancel-in-progress: true + steps: + # Base repo only: trusted code. No PR-head checkout. Full history for the merge base. + - name: Checkout base repo (trusted) + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + filter: blob:none + persist-credentials: false + + - name: Setup Bun + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: 1.4.2 + + - name: Fetch the pull request's commits as data + env: + PR_NUM: ${{ github.event.pull_request.number }} + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + git fetch --no-tags --quiet origin "+refs/pull/$PR_NUM/head:refs/remotes/pr/head" + git cat-file -e "$PR_HEAD_SHA^{commit}" + + - name: Report test changes + env: + PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + GSTACK_HOME="$RUNNER_TEMP/gstack-home" bun --no-env-file --config=/dev/null scripts/test-changes-report.ts \ + --base "$(git rev-parse HEAD)" --head "$PR_HEAD_SHA" --summary-file "$GITHUB_STEP_SUMMARY" diff --git a/bin/gstack-gate-diff b/bin/gstack-gate-diff index ad92815d2..9a89c0ba2 100755 --- a/bin/gstack-gate-diff +++ b/bin/gstack-gate-diff @@ -3,7 +3,7 @@ * gstack-gate-diff — list the gate edits in a candidate so a human can * disposition each one (W1 of docs/designs/HONEST_WORK_GATE_INTEGRITY.md). * - * gstack-gate-diff [base-ref] [--format table|jsonl] [--commit ] [--help] + * gstack-gate-diff [base-ref] [--format table|jsonl] [--commit | --head ] [--help] * * The tool produces the inventory and the tags; it never judges and never * suppresses. stdout, first line always: @@ -32,7 +32,7 @@ import * as path from 'node:path'; import * as os from 'node:os'; import { scanCandidate, parseGateIntegrityBlock, specDirectoryHoldsSpecs, type FileDiff, type CommitInfo } from '../lib/gate-diff/index'; import { - baseNote, commitInfo, commitsInRange, defaultBase, diffCommit, diffWorkingTree, firstParent, headSha, mergeBase, noBaseFix, readClaudeMd, repoRoot, + baseNote, commitInfo, commitsInRange, defaultBase, diffCommit, diffRange, diffWorkingTree, firstParent, headSha, mergeBase, noBaseFix, readClaudeMd, repoRoot, resolveBase, resolvesToCommit, treePaths, untrackedAsAdded, } from '../lib/gate-diff/git'; import { baseContainsHead, noDefaultBaseLine } from '../lib/default-base'; @@ -42,14 +42,17 @@ import { resolveStateRoot } from '../lib/state-root'; import { runScriptSync, wtreeFingerprint } from '../lib/script-invocation'; const BIN_DIR = path.dirname(Bun.fileURLToPath(import.meta.url)); -const USAGE = `usage: gstack-gate-diff [base-ref] [--format table|jsonl] [--commit ] [--help] +const USAGE = `usage: gstack-gate-diff [base-ref] [--format table|jsonl] [--commit | --head ] [--help] Lists every hunk in a test, CI, runner/lint-config, snapshot or golden path of the candidate (merge-base of and HEAD -> working tree + untracked files; a branch name resolves to origin/, the local ref only when no remote has it), tags the gate edits it recognises (RH-1 RH-3 RH-4 RH-12 RH-13 RH-14 RH-15 RH-16), and prints the read-level listing after one GATE_SUMMARY: line. --commit -scans that commit's first-parent delta instead of the working tree. +scans that commit's first-parent delta instead of the working tree. --head +scans merge-base(, ) -> from commit objects alone, never the +working tree, so a fetched pull request is read as data; CLAUDE.md still comes from +the checkout. Exit 0 with or without hunks; 2 only for an unresolvable base (GATE_ERROR=no_base) or a tool failure (GATE_ERROR=internal). Full jsonl artifact path is in the summary.`; @@ -57,6 +60,7 @@ interface Args { base?: string; format: 'table' | 'jsonl'; commit?: string; + head?: string; help: boolean; } @@ -77,10 +81,15 @@ function parseArgs(argv: string[]): Args | string { const v = argv[++i]; if (!v || v.startsWith('-')) return '--commit requires a '; args.commit = v; + } else if (a === '--head') { + const v = argv[++i]; + if (!v || v.startsWith('-')) return '--head requires a '; + args.head = v; } else if (a.startsWith('-')) return `unknown option ${a}`; else if (args.base !== undefined) return `unexpected extra argument ${a}`; else args.base = a; } + if (args.commit && args.head) return '--commit and --head cannot be combined'; return args; } @@ -156,7 +165,11 @@ function main(argv: string[]): number { return 2; } const baseRef = found.ref; - const head = headSha(root); + const head = parsed.head ? resolvesToCommit(parsed.head, root) : headSha(root); + if (parsed.head && !head) { + process.stdout.write(`GATE_ERROR=internal reason=head_unresolvable ref=${JSON.stringify(parsed.head)}\n`); + return 2; + } const base = resolveBase(baseRef, root, head ?? undefined); if (!base || !head) { process.stdout.write(`GATE_ERROR=no_base ref=${baseRef} fix=${noBaseFix(baseRef, root)}\n`); @@ -169,18 +182,25 @@ function main(argv: string[]): number { process.stdout.write(`GATE_ERROR=no_base ref=${baseRef} fix=${noBaseFix(baseRef, root)}\n`); return 2; } - const self = mb === head ? baseContainsHead(root, base.ref) : null; + const self = mb === head && !parsed.head ? baseContainsHead(root, base.ref) : null; if (self) { console.error(resultLine('gstack-gate-diff', 'BASE_CONTAINS_HEAD', self)); process.stdout.write(`GATE_ERROR=base_contains_head ref=${baseRef}\n`); return 2; } - files = [...diffWorkingTree(mb, root), ...untrackedAsAdded(root, root)]; - commits = commitsInRange(mb, head, root); - const fp = wtreeFingerprint({ cwd: root }); - if ('error' in fp) console.error(`gstack-gate-diff: working-tree fingerprint unavailable (${fp.error}); candidate recorded without it`); - candidate = `${mb.slice(0, 12)}+${'tree' in fp ? fp.tree.slice(0, 12) : 'nowtree'}`; - specIsTestPath = specDirectoryHoldsSpecs(treePaths(root)); + if (parsed.head) { + files = diffRange(mb, head, root); + commits = commitsInRange(mb, head, root, true); + candidate = `${mb.slice(0, 12)}..${head.slice(0, 12)}`; + specIsTestPath = specDirectoryHoldsSpecs(treePaths(root, head)); + } else { + files = [...diffWorkingTree(mb, root), ...untrackedAsAdded(root, root)]; + commits = commitsInRange(mb, head, root); + const fp = wtreeFingerprint({ cwd: root }); + if ('error' in fp) console.error(`gstack-gate-diff: working-tree fingerprint unavailable (${fp.error}); candidate recorded without it`); + candidate = `${mb.slice(0, 12)}+${'tree' in fp ? fp.tree.slice(0, 12) : 'nowtree'}`; + specIsTestPath = specDirectoryHoldsSpecs(treePaths(root)); + } } const artifact = path.join(artifactDir(root), `${candidate}.jsonl`); diff --git a/changelog.d/test-changes-report.md b/changelog.d/test-changes-report.md new file mode 100644 index 000000000..19ef58a27 --- /dev/null +++ b/changelog.d/test-changes-report.md @@ -0,0 +1 @@ +**Every gstack pull request now gets a Test changes summary that lists deleted or skipped tests, loosened limits and edits to the files that run its own checks.** The check runs main's copy of the scan on `pull_request_target`, reads the pull request's commits as data without checking them out, and a flag never fails it: it is a two-week flag-only trial. `gstack-gate-diff` gains `--head ` to scan merge-base to a fetched commit without touching the working tree. docs/ship-policy.md#test-changes (GST-3386) diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 161b2b1f4..f2dac9c3d 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -3352,6 +3352,46 @@ run until its title or body is edited or a commit is pushed; do one of those before landing it. The workflow reads the PR body from the event file, not an environment variable, so a very long body still reaches the checker. + +## Test changes: what a pull request does to its own tests (flag only) + +`.github/workflows/test-changes.yml` adds a **Test changes** check to every pull +request in this repository. It is a two-week, flag-only trial (GST-3386): it is not +a required check, and a flag never turns it red. A run that fails because the scan +itself broke does show red, and `gstack-ship-queue land` refuses a pull request with +any failed check at its head, so rerun that job from the Actions page before landing. + +It reports three things in the check's summary: + +- hunks that `bin/gstack-gate-diff` tags as removing or skipping a test (RH-1), + adding a suppression (RH-13), bypassing a gate (RH-14) or relaxing a gate value + (RH-15), by path and hunk id; +- the number of test declarations the pull request adds and removes; +- edits to the files that run or define this repository's own checks: any + workflow, `.gstack/`, `package.json`, the lockfile, `bunfig.toml`, the free-suite + shard runner and engine, `scripts/ci-tree-reuse.ts`, `lib/run-evidence.ts` and + `test/land-merged-checks.txt`. + +The workflow runs on `pull_request_target`, so main's copy of the workflow, of +`scripts/test-changes-report.ts` and of the gate scan reports on the pull request, +and the pull request can't edit the checker. It checks out main only, fetches the +pull request's commits as git objects, and reads them with +`gstack-gate-diff --head `, which diffs merge-base to that commit without +touching the working tree. The report names paths, tags and hunk ids, never the +pull request's line content. A flag never turns the check red. The check fails only +when the scan itself fails, so a broken run is never read as a quiet pull request. + +Each flag wants a reason in the pull request or a reviewer's ruling. The flags +don't replace /review's and /ship's gate findings, which still need an owner ruling +([gate dispositions](#gate-dispositions)). + +Replayed over the 303 landings on main from 2026-11-07 to 2026-11-21 +(`gstack-gate-diff --commit` on each landing), 24 (8%) carried at +least one of the four tags and 50 (17%) edited a listed check file, about 12 and +25 a week. The trial counts how many flags had a reason. A rule that would make +`gstack-ship-queue land` refuse a pull request that edits its own checks without an +owner ruling is out of scope until the trial reports. + ## Approval classes `.gstack/approval-classes.json` lists change classes that need an explicit diff --git a/lib/gate-diff/git.ts b/lib/gate-diff/git.ts index e083bc8af..97792bf0f 100644 --- a/lib/gate-diff/git.ts +++ b/lib/gate-diff/git.ts @@ -311,6 +311,13 @@ function decode(buf: Buffer): string { return new TextDecoder('utf-8', { fatal: false }).decode(buf); } +/** fromSha → toSha from commit objects alone, never the working tree (with rename detection). */ +export function diffRange(fromSha: string, toSha: string, cwd: string): FileDiff[] { + const r = runGit([...DIFF_FLAGS, fromSha, toSha, '--'], cwd); + if (r.status !== 0) throw new Error(`git diff failed: ${r.stderr.trim() || `exit ${r.status}`}`); + return parseUnifiedDiff(decode(r.stdout)); +} + /** merge-base → working tree (tracked changes, staged and unstaged, with rename detection). */ export function diffWorkingTree(mergeBaseSha: string, cwd: string): FileDiff[] { const r = runGit([...DIFF_FLAGS, mergeBaseSha, '--'], cwd); @@ -382,8 +389,9 @@ export function untrackedAsAdded(cwd: string, root: string): FileDiff[] { return out; } -export function commitsInRange(fromExclusive: string, toInclusive: string, cwd: string): CommitInfo[] { +export function commitsInRange(fromExclusive: string, toInclusive: string, cwd: string, strict = false): CommitInfo[] { const r = runGit(['log', '--format=%H%x00%B%x00', `${fromExclusive}..${toInclusive}`, '--'], cwd); + if (r.status !== 0 && strict) throw new Error(`git log failed: ${r.stderr.toString().trim() || `exit ${r.status}`}`); if (r.status !== 0) return []; const parts = r.stdout.toString('utf-8').split('\0'); const out: CommitInfo[] = []; diff --git a/scripts/harness-pins/scripts/test-pr-profile.ts.json b/scripts/harness-pins/scripts/test-pr-profile.ts.json index 299c6ffd0..932768a4a 100644 --- a/scripts/harness-pins/scripts/test-pr-profile.ts.json +++ b/scripts/harness-pins/scripts/test-pr-profile.ts.json @@ -1 +1 @@ -{"blob":"c1d0b8ffabc86df40aa8785a7af87b0dae64f3f2","since":7} +{"blob":"7de8d1dd5060bc0ec25fca1f3b348c354e5938a1","since":7,"nonBehavioral":"GST-3386 adds .github/workflows/test-changes.yml to FREE_ONLY_PR_FILES in scripts/test-pr-profile.ts: the new workflow is a free, flag-only check, so it only classifies that file as free-lane in the workflow inventory; no paid case's selection, prompt, threshold, samples or verdict can change"} diff --git a/scripts/test-changes-report.ts b/scripts/test-changes-report.ts new file mode 100755 index 000000000..91393383a --- /dev/null +++ b/scripts/test-changes-report.ts @@ -0,0 +1,91 @@ +#!/usr/bin/env -S bun --no-env-file --config=/dev/null +/** + * test-changes-report — what a pull request does to its own tests and gate, for the + * flag-only Test changes check (.github/workflows/test-changes.yml, docs/ship-policy.md#test-changes). + * + * bun scripts/test-changes-report.ts --base --head [--summary-file ] + * bun scripts/test-changes-report.ts --commit + * + * Runs this checkout's bin/gstack-gate-diff over merge-base(, ).. (or one commit's + * first-parent delta) from commit objects only, so a fetched pull request is read as data and never + * checked out. Prints one line, + * + * TEST_CHANGES: tagged={RH-1:2} tests_added=N tests_removed=N gate_files=N unread=N candidate= + * + * and, with --summary-file, appends a Markdown report naming paths, tags and hunk ids only (no PR + * text). Exit 0 whatever it finds; 1 when gate-diff or git fails, so a broken run is never counted + * as a quiet pull request. + */ +import * as path from 'node:path'; +import * as fs from 'node:fs'; +import { spawnSync } from '../lib/spawn-sync'; +import { TEST_DECLARATION } from '../lib/gate-diff/classify'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const gateDiffBin = path.join(ROOT, 'bin', 'gstack-gate-diff'); +const WATCHED = [/^\.github\/workflows\//, /^\.gstack\//, /^package\.json$/, /^bun\.lockb?$/, /^bunfig\.toml$/, + /^scripts\/test-free-shards\.ts$/, /^scripts\/lib\/shard-engine\.ts$/, /^scripts\/ci-tree-reuse\.ts$/, + /^lib\/run-evidence\.ts$/, /^test\/land-merged-checks\.txt$/]; +const COUNTED = ['RH-1', 'RH-13', 'RH-14', 'RH-15']; +const DATA_FILE = /\.(?:json|jsonl|ndjson|csv|tsv|log|out|md|mdx|txt)(?:\.tmpl)?$/i; + +interface Hunk { id: string; path: string; old_path?: string; tags: string[]; old: string[]; new: string[]; unsupported?: string } + +function fail(msg: string): never { + process.stderr.write(`test-changes-report: ${msg}\n`); + process.stdout.write('TEST_CHANGES: error\n'); + process.exit(1); +} + +function run(cmd: string, args: string[]): string { + const r = spawnSync(cmd, args, { cwd: process.cwd(), encoding: 'utf-8', timeout: 300_000, maxBuffer: 256 * 1024 * 1024 }); + if (r.error || r.status !== 0) fail(`${args.includes(gateDiffBin) ? 'gstack-gate-diff' : `git ${args[0]}`} failed (${r.error?.message ?? `exit ${r.status}`}): ${(r.stdout ?? '').split('\n')[0]} ${(r.stderr ?? '').trim().slice(0, 400)}`); + return r.stdout; +} + +function arg(argv: string[], name: string): string | undefined { + const i = argv.indexOf(name); + if (i === -1) return undefined; + const v = argv[i + 1]; + if (!v || v.startsWith('--')) fail(`${name} needs a value`); + return v; +} + +const cell = (s: string) => '`' + s.replace(/[^\x20-\x7e]/g, '?').replace(/[`|]/g, '?') + '`'; + +const argv = process.argv.slice(2); +const base = arg(argv, '--base'), head = arg(argv, '--head'), commit = arg(argv, '--commit'), summaryFile = arg(argv, '--summary-file'); +if (commit ? base || head : !base || !head) fail('use --base --head , or --commit '); + +const out = run(process.execPath, ['--no-env-file', '--config=/dev/null', gateDiffBin, ...(commit ? ['--commit', commit] : [base!, '--head', head!]), '--format', 'jsonl']); +const [first, ...rest] = out.split('\n'); +const summary = /^GATE_SUMMARY: .*unread=(\d+) .*candidate=(\S+) /.exec(first); +if (!summary) fail(`gate-diff printed no GATE_SUMMARY line: ${first.slice(0, 200)}`); +const hunks: Hunk[] = rest.filter(Boolean).map((l) => JSON.parse(l)); + +const range = commit ? [`${commit}^`, commit] : [summary[2].split('..')[0], head!]; +const changed = run('git', ['diff', '--name-only', '-z', '--no-renames', range[0], range[1], '--']).split('\0').filter(Boolean); +const gateFiles = changed.filter((p) => WATCHED.some((re) => re.test(p))); + +const tagged: Record = {}; +const flagged = hunks.filter((h) => h.tags.some((t) => COUNTED.includes(t))); +for (const h of flagged) for (const t of h.tags) if (COUNTED.includes(t)) tagged[t] = (tagged[t] ?? 0) + 1; +const declarations = (lines: string[]) => lines.filter((l) => TEST_DECLARATION.test(l)).length; +const code = hunks.filter((h) => !DATA_FILE.test(h.path)); +const added = code.reduce((n, h) => n + declarations(h.new), 0); +const removed = code.reduce((n, h) => n + declarations(h.old), 0); +const tagText = COUNTED.filter((t) => tagged[t]).map((t) => `${t}:${tagged[t]}`).join(','); + +process.stdout.write(`TEST_CHANGES: tagged={${tagText}} tests_added=${added} tests_removed=${removed} gate_files=${gateFiles.length} unread=${summary[1]} candidate=${summary[2]}\n`); + +if (summaryFile) { + const md = ['## Test changes (flags never fail this check)', '', + `Tests added: ${added}. Tests removed: ${removed}. Hunks that remove or skip a test (RH-1), add a suppression (RH-13), bypass a gate (RH-14) or relax a gate value (RH-15): ${flagged.length}.`]; + if (+summary[1] > 0) md.push('', `Partial read: ${summary[1]} eligible hunks past the reading cap were not tagged.`); + const unreadable = hunks.filter((h) => h.unsupported); + if (unreadable.length) md.push('', `Not read as text, so tests removed in them are not counted: ${unreadable.map((h) => `${cell(h.path)} (${h.unsupported})`).join(', ')}.`); + if (gateFiles.length) md.push('', '**This pull request edits files that run or define its own checks:**', '', ...gateFiles.map((p) => `- ${cell(p)}`)); + if (flagged.length) md.push('', '| Hunk | Path | Tags |', '|---|---|---|', ...flagged.map((h) => `| ${cell(h.id)} | ${cell(h.path)} | ${h.tags.join(', ')} |`)); + md.push('', 'Each flag needs a reason in the pull request, or a reviewer ruling. See docs/ship-policy.md#test-changes.', ''); + fs.appendFileSync(summaryFile, md.join('\n')); +} diff --git a/scripts/test-pr-profile.ts b/scripts/test-pr-profile.ts index c1d0b8ffa..7de8d1dd5 100644 --- a/scripts/test-pr-profile.ts +++ b/scripts/test-pr-profile.ts @@ -287,6 +287,7 @@ export const FREE_ONLY_PR_FILES = [ '.github/workflows/quality-gate.yml', '.github/workflows/scorecard.yml', '.github/workflows/skill-docs.yml', + '.github/workflows/test-changes.yml', '.github/workflows/test-health.yml', '.github/workflows/trunk-flaky-tests.yml', '.github/workflows/eval-sweep.yml', // The weekly off-ship sweep on main; no PR-gate case reads it, and it never gates a PR. diff --git a/test/gate-diff-cli.test.ts b/test/gate-diff-cli.test.ts index e80b42562..773ac8792 100644 --- a/test/gate-diff-cli.test.ts +++ b/test/gate-diff-cli.test.ts @@ -51,7 +51,7 @@ describe('gstack-gate-diff arguments and exit contract', () => { test('--help exits 0 with usage on stdout', () => { const r = run(repo(), ['--help']); expect(r.status).toBe(0); - expect(r.stdout).toContain('usage: gstack-gate-diff [base-ref] [--format table|jsonl] [--commit ] [--help]'); + expect(r.stdout).toContain('usage: gstack-gate-diff [base-ref] [--format table|jsonl] [--commit | --head ] [--help]'); }); test('an unknown option or bad --format is a tool failure: GATE_ERROR=internal, exit 2', () => { diff --git a/test/test-changes-report.test.ts b/test/test-changes-report.test.ts new file mode 100644 index 000000000..a3f758dd5 --- /dev/null +++ b/test/test-changes-report.test.ts @@ -0,0 +1,139 @@ +/** + * scripts/test-changes-report.ts and gstack-gate-diff --head over real git repos: a pull request's commits are read as + * objects from a checkout that stays on the base, its removed and skipped tests are tagged, its edits to check files + * are listed, and a checker failure is an error, never a quiet result. + * + * Value: protects=the Test changes report counts what a pull request did to its tests without checking it out; + * fails_when=--head reads the working tree, a removed test or new skip goes uncounted, a gate-file edit is missed, a + * clean pull request is flagged, or a failed run exits 0; why_new=the report and --head are new (GST-3386); + * seam=real git and the real CLIs; no_claim=GitHub's fetch of refs/pull + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { gitArgvIn } from './helpers/scratch-repo'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const REPORT = path.join(ROOT, 'scripts', 'test-changes-report.ts'); +const GATE_DIFF = path.join(ROOT, 'bin', 'gstack-gate-diff'); +const dirs: string[] = []; +afterEach(() => { for (const d of dirs.splice(0)) fs.rmSync(d, { recursive: true, force: true }); }); + +function tmp(prefix: string): string { + const d = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); + dirs.push(d); + return d; +} +function git(dir: string, args: string[]): string { + const r = gitArgvIn(dir, args, 10_000); + if (r.status !== 0) throw new Error(`git ${args.join(' ')} failed: ${(r.stderr ?? '').toString()}`); + return (r.stdout ?? '').toString().trim(); +} +function write(dir: string, files: Record): void { + for (const [rel, body] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true }); + fs.writeFileSync(path.join(dir, rel), body); + } +} + +const BASE_TEST = "import { test, expect } from 'bun:test';\ntest('adds', () => {\n expect(1 + 1).toBe(2);\n});\ntest('subtracts', () => {\n expect(2 - 1).toBe(1);\n});\n"; + +/** main holds a test file and a workflow; the candidate commit, never checked out, is `change` applied on top. */ +function repo(change: Record): { dir: string; base: string; head: string } { + const dir = tmp('gstack-test-changes-'); + git(dir, ['init', '-q', '-b', 'main']); + write(dir, { 'test/math.test.ts': BASE_TEST, '.github/workflows/ci.yml': 'name: ci\non: push\n', 'src/math.ts': 'export const one = 1;\n' }); + git(dir, ['add', '-A']); + git(dir, ['commit', '-q', '-m', 'seed']); + const base = git(dir, ['rev-parse', 'HEAD']); + git(dir, ['checkout', '-q', '-b', 'pr']); + write(dir, change); + git(dir, ['add', '-A']); + git(dir, ['commit', '-q', '-m', 'candidate']); + const head = git(dir, ['rev-parse', 'HEAD']); + git(dir, ['checkout', '-q', 'main']); + return { dir, base, head }; +} +function run(bin: string, cwd: string, args: string[]) { + const r = spawnSync(process.execPath, ['--no-env-file', '--config=/dev/null', bin, ...args], { + cwd, encoding: 'utf-8', timeout: 60_000, env: { ...process.env, GSTACK_HOME: tmp('gstack-test-changes-home-'), GSTACK_STATE_ROOT: '' }, + }); + return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' }; +} + +describe('test-changes report over a fetched, never checked-out pull request', () => { + test('a removed test, a new skip and a workflow edit are all reported, and the checkout stays on main', () => { + const { dir, base, head } = repo({ + 'test/math.test.ts': "import { test, expect } from 'bun:test';\ntest.skip('adds', () => {\n expect(1 + 1).toBe(2);\n});\n", + '.github/workflows/ci.yml': 'name: ci\non: [push, pull_request]\n', + }); + const summary = path.join(tmp('gstack-test-changes-out-'), 'summary.md'); + const r = run(REPORT, dir, ['--base', base, '--head', head, '--summary-file', summary]); + expect(r.status).toBe(0); + expect(r.stdout).toMatch(/^TEST_CHANGES: tagged=\{RH-1:\d+\} tests_added=1 tests_removed=2 gate_files=1 unread=0 candidate=[0-9a-f]{12}\.\.[0-9a-f]{12}\n$/); + const md = fs.readFileSync(summary, 'utf8'); + expect(md).toContain('`.github/workflows/ci.yml`'); + expect(md).toContain('`test/math.test.ts`'); + expect(md).not.toContain('expect(1 + 1)'); + expect(git(dir, ['rev-parse', '--abbrev-ref', 'HEAD'])).toBe('main'); + expect(fs.readFileSync(path.join(dir, 'test/math.test.ts'), 'utf8')).toBe(BASE_TEST); + }); + + test('negative control: a pull request that only adds a test and changes source is not flagged', () => { + const { dir, base, head } = repo({ + 'test/math.test.ts': BASE_TEST + "test('multiplies', () => {\n expect(2 * 2).toBe(4);\n});\n", + 'src/math.ts': 'export const one = 1;\nexport const two = 2;\n', + }); + const r = run(REPORT, dir, ['--base', base, '--head', head]); + expect(r.status).toBe(0); + expect(r.stdout).toMatch(/^TEST_CHANGES: tagged=\{\} tests_added=1 tests_removed=0 gate_files=0 /); + }); + + test('a test file that git reads as binary is named as unread, never counted as a quiet pass', () => { + const { dir, base, head } = repo({ 'test/math.test.ts': "import { test } from 'bun:test';\n\0\n" }); + const summary = path.join(tmp('gstack-test-changes-out-'), 'summary.md'); + const r = run(REPORT, dir, ['--base', base, '--head', head, '--summary-file', summary]); + expect(r.status).toBe(0); + expect(fs.readFileSync(summary, 'utf8')).toContain('Not read as text, so tests removed in them are not counted: `test/math.test.ts` (binary).'); + }); + + test('a branch-name base resolves once: a stale local main adds no upstream check-file edits', () => { + const { dir, base } = repo({ 'src/math.ts': 'export const one = 1;\n// z\n' }); + git(dir, ['checkout', '-q', '-b', 'upstream', base]); + write(dir, { '.github/workflows/ci.yml': 'name: ci\non: [push, workflow_dispatch]\n' }); + git(dir, ['commit', '-q', '-am', 'upstream']); + git(dir, ['remote', 'add', 'origin', dir]); + git(dir, ['update-ref', 'refs/remotes/origin/main', git(dir, ['rev-parse', 'HEAD'])]); + write(dir, { 'src/math.ts': 'export const one = 1;\nexport const three = 3;\n' }); + git(dir, ['commit', '-q', '-am', 'pr']); + const head = git(dir, ['rev-parse', 'HEAD']); + git(dir, ['checkout', '-q', 'main']); + const r = run(REPORT, dir, ['--base', 'main', '--head', head]); + expect(r.status).toBe(0); + expect(r.stdout).toMatch(/ gate_files=0 /); + }); + + test('--commit reads one commit the same way', () => { + const { dir, head } = repo({ 'test/math.test.ts': "import { test } from 'bun:test';\n" }); + const r = run(REPORT, dir, ['--commit', head]); + expect(r.status).toBe(0); + expect(r.stdout).toMatch(/tests_added=0 tests_removed=2 gate_files=0 /); + }); + + test('an unresolvable head is an error with exit 1, never a quiet report', () => { + const { dir, base } = repo({ 'src/math.ts': 'export const one = 1;\n// x\n' }); + const r = run(REPORT, dir, ['--base', base, '--head', '0123456789abcdef0123456789abcdef01234567']); + expect(r.status).toBe(1); + expect(r.stdout).toBe('TEST_CHANGES: error\n'); + expect(r.stderr).toContain('gstack-gate-diff failed'); + }); + + test('gate-diff refuses --head together with --commit', () => { + const { dir, head } = repo({ 'src/math.ts': 'export const one = 1;\n// y\n' }); + const r = run(GATE_DIFF, dir, ['--commit', head, '--head', head]); + expect(r.status).toBe(2); + expect(r.stdout).toMatch(/^GATE_ERROR=internal reason=usage .*cannot be combined/); + }); +}); diff --git a/test/test-changes-workflow-safety.test.ts b/test/test-changes-workflow-safety.test.ts new file mode 100644 index 000000000..86ec76849 --- /dev/null +++ b/test/test-changes-workflow-safety.test.ts @@ -0,0 +1,68 @@ +/** + * test-changes.yml runs on pull_request_target, so it is held to the same static + * tripwire as plain-title.yml: the job checks out the base repo only (no ref:), + * fetches the pull request's commits as git objects, passes every PR field through + * env:, never inlines ${{ github.event.pull_request.* }} into run:, holds a + * read-only token it does not persist, uses no secrets, and pins every action. + * + * Value: protects=a pull request can never run its own code with the base repo's token or edit the checker that + * reports on it; fails_when=a ref: checkout, an inlined PR field, a write permission, a secret or an unpinned action + * appears; why_new=the workflow is new (GST-3386); seam=the workflow text; no_claim=GitHub's runtime behaviour + */ +import { describe, expect, test } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; + +const content = fs.readFileSync(path.resolve(import.meta.dir, '..', '.github/workflows/test-changes.yml'), 'utf8'); +const indent = (line: string) => line.match(/^( *)/)![1]!.length; + +function runBlockLines(text: string): string[] { + const out: string[] = []; + let runIndent = -1; + for (const line of text.split('\n')) { + const inline = line.match(/^\s*(?:-\s*)?run:\s*(\S.*)$/); + if (runIndent >= 0 && line.trim() !== '' && indent(line) <= runIndent) runIndent = -1; + if (runIndent >= 0) { out.push(line); continue; } + if (inline && !/^[|>]/.test(inline[1]!)) { out.push(inline[1]!); continue; } + if (/^\s*(?:-\s*)?run:\s*[|>][+-]?\s*$/.test(line)) runIndent = indent(line); + } + return out; +} + +describe('test-changes.yml pull_request_target safety', () => { + test('runs on pull_request_target when a pull request opens or its head moves', () => { + expect(content).toMatch(/^on:\s*\n\s+pull_request_target:\s*\n\s+types:\s*\[opened, synchronize, reopened\]/m); + }); + + test('checks out the base repo only, full history, without persisting the token', () => { + expect(content.split('\n').filter((l) => /^\s*ref:/.test(l))).toEqual([]); + expect(content).toMatch(/fetch-depth: 0\n\s+filter: blob:none/); + expect(content).toMatch(/persist-credentials[:] false/); + }); + + test('the pull request arrives as git objects and the report reads it with --head', () => { + const run = runBlockLines(content).join('\n'); + expect(run).toContain('git fetch --no-tags --quiet origin "+refs/pull/$PR_NUM/head:refs/remotes/pr/head"'); + expect(run).toContain('git cat-file -e "$PR_HEAD_SHA^{commit}"'); + expect(run).toMatch(/scripts\/test-changes-report\.ts \\\n\s+--base "\$\(git rev-parse HEAD\)" --head "\$PR_HEAD_SHA" --summary-file "\$GITHUB_STEP_SUMMARY"/); + expect(run).not.toMatch(/git (?:checkout|switch|worktree|merge|reset)\b/); + expect(run).not.toMatch(/\bbun (?:install|run)\b|\bnpm\b|\bnpx\b|\bbunx\b/); + }); + + test('no ${{ github.event.pull_request.* }} inside any run: block, and the tripwire catches one', () => { + const lines = runBlockLines(content); + expect(lines.length).toBeGreaterThan(3); + expect(lines.filter((l) => /\$\{\{\s*github\.event/.test(l))).toEqual([]); + const planted = 'steps:\n - run: |\n echo "${{ github.event.pull_request.title }}"\n - run: echo ${{ github.event.pull_request.body }}\n'; + expect(runBlockLines(planted).filter((l) => /\$\{\{\s*github\.event/.test(l)).length).toBe(2); + }); + + test('read-only token, no secrets, every action pinned to a commit', () => { + expect(content).toMatch(/^permissions:\n contents: read\n\n/m); + expect(content).not.toMatch(/:\s*write\b/); + expect(content).not.toMatch(/\$\{\{\s*secrets\./); + const uses = [...content.matchAll(/uses:\s*(\S+)/g)].map((m) => m[1]!); + expect(uses.length).toBe(2); + for (const u of uses) expect(u).toMatch(/@[0-9a-f]{40}$/); + }); +});