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
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-22 02:14:15 +00:00
1 parent abdc09dad1
commit 973b49eabb
11 files changed
+451 -15

No files matched your search

+1 -1
View File
@@ -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 <sha>] [--help]');
expect(r.stdout).toContain('usage: gstack-gate-diff [base-ref] [--format table|jsonl] [--commit <sha> | --head <sha>] [--help]');
});
test('an unknown option or bad --format is a tool failure: GATE_ERROR=internal, exit 2', () => {
+139
View File
@@ -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<string, string>): 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<string, string>): { 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/);
});
});
+68
View File
@@ -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}$/);
});
});