Skip to content

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

TypeScript
21.6 KB
Raw Blame
/**
 * Versions at release (docs/ship-policy.md#release-stamp): gstack-restamp --release folds every fragment on the base
 * under base + their bump, classifyRelease accepts exactly that stamp, gstack-release-stamp open pushes it as
 * release/<version> and opens its PR, the Version Gate passes it, and land --pin merges it without a receipt.
 */
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { classifyRelease, openRelease } from '../lib/release-stamp';
import { checkBodyShape, visibleOpening } from '../lib/pr-body-shape';
import { DEFAULT_TERMS } from '../lib/plain-title';
import { sectionText } from '../lib/squash-message';
import { loadPolicyFromBase, MERGE_KEY_VERSION } from '../lib/ship-policy';
import { classifyTrainHead } from '../crew/lib/version-gate-train';
import { BASE_POLICY, cleanup, makeFixtureRepo, readFile, runBin, type FixtureRepo } from './helpers/restamp-fixture';

const POLICY = { ...BASE_POLICY, changelog_fragments: { dir: 'changelog.d', required_checks: ['free-tests'] }, merge: 'direct', min_gstack_version: MERGE_KEY_VERSION };
const repos: FixtureRepo[] = [];
afterEach(() => { while (repos.length) cleanup(repos.pop()!); });

/** A fixture whose main carries two landed fragments (one bump: minor) and a tentative stamp_paths mention, like PRs landed unstamped under merge: direct. */
function landed(fragments: Record<string, string> = { 'a.md': '- a change\n', 'b.md': '---\nbump: minor\n---\n- b feature\n' }, opts: { policy?: Record<string, unknown>; version?: string } = {}): FixtureRepo {
  const repo = makeFixtureRepo({ policy: opts.policy ?? POLICY, version: opts.version, prefix: 'gstack-release-stamp-fx-' });
  repos.push(repo);
  fs.mkdirSync(path.join(repo.work, 'changelog.d'), { recursive: true });
  for (const [name, body] of Object.entries(fragments)) fs.writeFileSync(path.join(repo.work, 'changelog.d', name), body);
  fs.writeFileSync(path.join(repo.work, 'docs', 'feature.md'), 'since: 1.2.9.0\n');
  fs.writeFileSync(path.join(repo.work, 'feature.txt'), 'product\n');
  repo.git('add', '-A');
  repo.git('commit', '-q', '-m', 'land unstamped PRs');
  repo.git('push', '-q', 'origin', 'main');
  repo.git('checkout', '-q', '--detach', 'origin/main');
  return repo;
}
/** Real changelog.d fragments, byte for byte: v1.103.2.0's five (#4785) and gbrain d7278e4c's one that quotes its own VERSION (GBRA-784). */
const realFragments = (dir: string): Record<string, string> => Object.fromEntries(fs.readdirSync(path.join(import.meta.dir, 'fixtures', 'release-stamp', dir)).sort().map(f => [f, fs.readFileSync(path.join(import.meta.dir, 'fixtures', 'release-stamp', dir, f), 'utf8')]));
const sectionOf = (cl: string, version: string) => cl.slice(cl.indexOf(`## [${version}]`), cl.indexOf('\n## [', cl.indexOf(`## [${version}]`) + 1));
const policyOf = (repo: FixtureRepo) => { const l = loadPolicyFromBase(repo.work, 'main'); if ('detail' in l && !('policy' in l)) throw new Error('no policy'); return (l as any).policy; };
function stampRelease(repo: FixtureRepo): string {
  const r = runBin(repo, 'gstack-restamp', ['--release', '--base', 'main', '--allow-repo-commands']);
  expect(r.status).toBe(0);
  repo.git('add', '-A');
  repo.git('commit', '-q', '-m', 'release');
  return repo.git('rev-parse', 'HEAD');
}

describe('gstack-restamp --release', () => {
  test('folds every fragment on the base under base + their bump, regenerates outputs and moves the tentative mention', () => {
    const repo = landed();
    const r = runBin(repo, 'gstack-restamp', ['--release', '--base', 'main', '--allow-repo-commands']);
    expect(r.status).toBe(0);
    expect(r.out).toContain('STAMP_VERSION: 1.3.0.0');
    expect(readFile(repo, 'VERSION').trim()).toBe('1.3.0.0');
    expect(JSON.parse(readFile(repo, 'package.json')).version).toBe('1.3.0');
    const cl = readFile(repo, 'CHANGELOG.md');
    expect(cl).toMatch(/## \[1\.3\.0\.0\] - \d{4}-\d{2}-\d{2}\n\n- a change\n\n- b feature\n/);
    expect(cl).toContain('## [1.2.3.0] - 2026-10-01\n\n- base release');
    expect(fs.existsSync(path.join(repo.work, 'changelog.d', 'a.md'))).toBe(false);
    expect(fs.existsSync(path.join(repo.work, 'changelog.d', 'b.md'))).toBe(false);
    expect(readFile(repo, 'generated/digest.md')).toBe('# digest v1.3.0.0\nbody\n');
    expect(readFile(repo, 'docs/feature.md')).toBe('since: 1.3.0.0\n');
    expect(readFile(repo, 'docs/notes.md')).toContain('Previous release v1.2.3.0.');
  });

  // Value: protects=fragment prose that quotes the version being released from is copied byte for byte, even where the
  //   CHANGELOG is a stamp file; fails_when=the stamp_paths stage moves "v0.60.769.0" in the folded prose to the new
  //   version (GBRA-784, gbrain d7278e4c); seam=gstack-restamp --release on a gbrain-shaped policy
  test('a fragment quoting the current version keeps its prose byte for byte when the CHANGELOG is a stamp file', () => {
    const fragments = realFragments('gbrain-d7278e4c');
    const repo = landed(fragments, { version: '0.60.769.0', policy: { ...POLICY, stamp_files: ['VERSION', 'package.json', 'package-lock.json', 'CHANGELOG.md'] } });
    const base = repo.git('rev-parse', 'origin/main');
    const head = stampRelease(repo);
    expect(readFile(repo, 'VERSION').trim()).toBe('0.60.770.0');
    const section = sectionOf(readFile(repo, 'CHANGELOG.md'), '0.60.770.0');
    expect(section).toContain('- Correction to the v0.60.769.0 note on `file_drift` holds:');
    expect(section).not.toContain('v0.60.770.0');
    const body = fragments['capy-ghost-pages-move-evidence.md']!.replace(/^---\n[\s\S]*?\n---\n/, '').trim();
    expect(section).toContain(body);
    expect(classifyRelease({ repoRoot: repo.work, policy: policyOf(repo), mergeBase: base, head })).toMatchObject({ ok: true });
  });

  // Value: protects=a release section names each subsection once; fails_when=two fragments that each carry
  //   "### For contributors" leave the heading twice in the new section (#4785); seam=gstack-restamp --release
  test('fragments that share a subsection heading fold under one copy of it, after the unheaded entries', () => {
    const repo = landed(realFragments('v1.103.2.0'));
    const base = repo.git('rev-parse', 'origin/main');
    const head = stampRelease(repo);
    const section = sectionOf(readFile(repo, 'CHANGELOG.md'), '1.2.4.0');
    expect(section.match(/^### For contributors$/gm)).toHaveLength(1);
    const at = (text: string) => section.indexOf(text);
    expect(at('**/ship\'s instructions now match how it reviews code.**')).toBeLessThan(at('### For contributors'));
    expect(at('### For contributors')).toBeLessThan(at('- **A weekly benchmark record can no longer slip text'));
    expect(at('### For contributors')).toBeLessThan(at('- **Every stable release plan now prints'));
    expect(classifyRelease({ repoRoot: repo.work, policy: policyOf(repo), mergeBase: base, head }).ok).toBe(true);
  });

  test('takes its bump from the fragments: --bump with --release is a usage error', () => {
    const repo = landed();
    const r = runBin(repo, 'gstack-restamp', ['--release', '--bump', 'major', '--base', 'main', '--allow-repo-commands']);
    expect(r.status).not.toBe(0);
    expect(r.err).toContain('drop --bump');
    expect(readFile(repo, 'VERSION').trim()).toBe('1.2.3.0');
  });

  test('refuses off a clean checkout of origin/<base>, and with no fragment to release', () => {
    const repo = landed();
    repo.git('checkout', '-q', '-b', 'side');
    fs.writeFileSync(path.join(repo.work, 'side.txt'), 'x\n');
    repo.git('add', '-A');
    repo.git('commit', '-q', '-m', 'side');
    const off = runBin(repo, 'gstack-restamp', ['--release', '--base', 'main', '--allow-repo-commands']);
    expect(off.status).not.toBe(0);
    expect(off.err).toContain('RELEASE_STAMP_INVALID');
    expect(readFile(repo, 'VERSION').trim()).toBe('1.2.3.0');
    const empty = landed({});
    const none = runBin(empty, 'gstack-restamp', ['--release', '--base', 'main', '--allow-repo-commands']);
    expect(none.status).not.toBe(0);
    expect(none.err).toContain('RELEASE_STAMP_EMPTY');
  });
});

describe('classifyRelease and the Version Gate', () => {
  test('accept exactly the release stamp of the merge base', () => {
    const repo = landed();
    const base = repo.git('rev-parse', 'origin/main');
    const head = stampRelease(repo);
    expect(classifyRelease({ repoRoot: repo.work, policy: policyOf(repo), mergeBase: base, head })).toEqual({ ok: true, version: '1.3.0.0', fragments: ['changelog.d/a.md', 'changelog.d/b.md'] });
    expect(classifyTrainHead({ repoRoot: repo.work, baseRef: 'main', head })).toEqual({ kind: 'release', version: '1.3.0.0', fragments: 2 });
  });

  test.each([
    ['a product change rides along', (w: string) => fs.writeFileSync(path.join(w, 'feature.txt'), 'sneaked\n'), 'feature.txt'],
    ['a fragment stays unfolded', (w: string) => fs.writeFileSync(path.join(w, 'changelog.d', 'a.md'), '- a change\n'), 'changelog.d/a.md'],
    ['the CHANGELOG entry is edited', (w: string) => fs.writeFileSync(path.join(w, 'CHANGELOG.md'), fs.readFileSync(path.join(w, 'CHANGELOG.md'), 'utf8').replace('- a change', '- a rewritten change')), 'CHANGELOG.md'],
    ['the release output is hand-edited', (w: string) => fs.writeFileSync(path.join(w, 'generated', 'digest.md'), '# digest v1.3.0.0\nedited\n'), 'generated/digest.md'],
    ['package.json keeps the old version', (w: string) => fs.writeFileSync(path.join(w, 'package.json'), fs.readFileSync(path.join(w, 'package.json'), 'utf8').replace('"version": "1.3.0"', '"version": "1.2.3"')), 'package.json'],
    ['the CHANGELOG heading names another version', (w: string) => fs.writeFileSync(path.join(w, 'CHANGELOG.md'), fs.readFileSync(path.join(w, 'CHANGELOG.md'), 'utf8').replace('## [1.3.0.0]', '## [9.0.0.0]')), 'CHANGELOG.md'],
    ['two released sections swap their entries', (w: string) => fs.writeFileSync(path.join(w, 'CHANGELOG.md'), fs.readFileSync(path.join(w, 'CHANGELOG.md'), 'utf8').replace('- base release\n', '\0').replace('- older\n', '- base release\n').replace('\0', '- older\n')), 'rewrites the released section(s) 1.2.3.0'],
    ['the release output is deleted', (w: string) => fs.rmSync(path.join(w, 'generated', 'digest.md')), 'generated/digest.md'],
    ['the release output keeps the old version', (w: string) => fs.writeFileSync(path.join(w, 'generated', 'digest.md'), '# digest v1.2.3.0\nbody\n'), 'generated/digest.md'],
    ['the version is not base + the fragments\' bump', (w: string) => fs.writeFileSync(path.join(w, 'VERSION'), '1.4.0.0\n'), 'is 1.3.0.0'],
  ])('refuse a release head where %s', (_name, tamper, named) => {
    const repo = landed();
    const base = repo.git('rev-parse', 'origin/main');
    runBin(repo, 'gstack-restamp', ['--release', '--base', 'main', '--allow-repo-commands']);
    tamper(repo.work);
    repo.git('add', '-A');
    repo.git('commit', '-q', '-m', 'release');
    const head = repo.git('rev-parse', 'HEAD');
    const v = classifyRelease({ repoRoot: repo.work, policy: policyOf(repo), mergeBase: base, head });
    expect(v.ok).toBe(false);
    expect((v as { reason: string }).reason).toContain(named);
    const gate = classifyTrainHead({ repoRoot: repo.work, baseRef: 'main', head });
    expect(gate.kind).toBe('invalid');
    expect((gate as { reason: string }).reason).toContain('RELEASE_STAMP_INVALID');
  });

});

describe('gstack-release-stamp open', () => {
  test('pushes release/<version> stamped from origin/main and opens its PR', () => {
    const repo = landed();
    repo.git('checkout', '-q', '-b', 'elsewhere');
    const calls: string[][] = [];
    const r = openRelease({ repoRoot: repo.work, base: 'main', gh: (args) => { calls.push(args); return { ok: true, out: args[1] === 'list' ? '' : 'https://github.com/o/r/pull/42\n', err: '' }; } });
    expect(r.ok).toBe(true);
    if (!r.ok) return;
    expect(r.branch).toBe('release/1.3.0.0');
    expect(r.pr).toBe('42');
    expect(repo.git('--git-dir', repo.origin, 'rev-parse', 'refs/heads/release/1.3.0.0')).toBe(r.head!);
    expect(repo.git('--git-dir', repo.origin, 'rev-parse', 'refs/heads/main')).toBe(repo.git('rev-parse', 'origin/main'));
    expect(calls.map(a => a[1])).toEqual(['list', 'create']);
    expect(calls[1]!.slice(0, 7)).toEqual(['pr', 'create', '--base', 'main', '--head', 'release/1.3.0.0', '--title']);
    const body = calls[1]![calls[1]!.indexOf('--body') + 1]!;
    expect(checkBodyShape(body, DEFAULT_TERMS)).toEqual([]);
    expect(visibleOpening(body)[0]).toBe('v1.3.0.0 ships 2 user-visible changes, listed one per line under Release notes with the pull request that made each.');
    expect(sectionText(body, 'Release notes')).toBe('- a change\n- b feature');
    expect(r.lines.join('\n')).toContain('NEXT: gstack-ship-queue land --pr 42 --pin ' + r.head);
    expect(classifyRelease({ repoRoot: repo.work, policy: policyOf(repo), mergeBase: repo.git('rev-parse', 'origin/main'), head: r.head! }).ok).toBe(true);
    expect(repo.git('branch', '--show-current')).toBe('elsewhere');
    expect(repo.git('worktree', 'list').split('\n')).toHaveLength(1);
  });

  // GSTA-643 list: on Capy gh signs in as the owner, so open hands the release PR to the host's PR tool instead of gh pr create.
  // Value: protects=the release PR counts and lists changes, never subsection headings; fails_when=v1.103.2.0's two
  //   "### For contributors" headings count as changes and the body says 7 instead of 5 (#4785); seam=openRelease with a gh stub
  test('the release notes count changes, not the subsection headings fragments carry', () => {
    const repo = landed(realFragments('v1.103.2.0'));
    const calls: string[][] = [];
    const r = openRelease({ repoRoot: repo.work, base: 'main', gh: (args) => { calls.push(args); return { ok: true, out: args[1] === 'list' ? '' : 'https://github.com/o/r/pull/45\n', err: '' }; } });
    expect(r.ok).toBe(true);
    const body = calls[1]![calls[1]!.indexOf('--body') + 1]!;
    expect(visibleOpening(body)[0]).toBe('v1.2.4.0 ships 5 user-visible changes, listed one per line under Release notes with the pull request that made each.');
    expect(sectionText(body, 'Release notes').split('\n')).toEqual([
      '- make-pdf no longer lets a NUL character hide an `onerror` handler, a `javascript:` link or a `<script>` tag from its sanitizer.',
      '- After a blocking fix, /ship\'s second review round is always a full review whose every reader is recorded with the pass, instead of a narrower re-check whose result could go missing.',
      '- /ship\'s instructions now match how it reviews code.',
      '- A weekly benchmark record can no longer slip text into the release job\'s log through its error messages, or lose a model row to an odd model name.',
      '- Every stable release plan now prints the weekly benchmark\'s result, so you can see whether this week\'s gstack measurably fixes more or fewer bugs than the current stable release.',
    ]);
  });

  test('an empty heading line drops only itself from the release notes', () => {
    const repo = landed({ 'a.md': '###\n- **The only change.** More words.\n' });
    const calls: string[][] = [];
    expect(openRelease({ repoRoot: repo.work, base: 'main', gh: (args) => { calls.push(args); return { ok: true, out: args[1] === 'list' ? '' : 'https://github.com/o/r/pull/46\n', err: '' }; } }).ok).toBe(true);
    expect(sectionText(calls[1]![calls[1]!.indexOf('--body') + 1]!, 'Release notes')).toBe('- The only change.');
  });

  test('on Capy, open pushes the release branch and hands the PR to the host tool without gh pr create', () => {
    const repo = landed();
    const state = fs.mkdtempSync(path.join(repo.work, '..', 'state-'));
    const calls: string[][] = [];
    const r = openRelease({ repoRoot: repo.work, base: 'main', env: { GSTACK_CAPY: '1', GSTACK_STATE_ROOT: state }, gh: (args) => {
      calls.push(args);
      if (args[0] === 'repo') return { ok: true, out: JSON.stringify({ nameWithOwner: 'o/r', url: 'https://github.com/o/r' }), err: '' };
      return { ok: true, out: '', err: '' };
    } });
    expect(r.ok).toBe(true);
    if (!r.ok) return;
    expect(calls.map(a => a.slice(0, 2).join(' '))).toEqual(['pr list', 'repo view']);
    expect(repo.git('--git-dir', repo.origin, 'rev-parse', 'refs/heads/release/1.3.0.0')).toBe(r.head!);
    const handed = r.lines.find(l => l.startsWith('HOST_PUBLISH: '))!;
    expect(handed).toStartWith('HOST_PUBLISH: pr-create new repo=o/r base=main head=release/1.3.0.0 title-file=');
    const file = (part: string) => fs.readFileSync(new RegExp(` ${part}-file=(\\S+)`).exec(handed)![1]!, 'utf8');
    expect(file('title')).toBe('v1.3.0.0 release');
    expect(sectionText(file('body'), 'Release notes')).toBe('- a change\n- b feature');
    expect(r.lines.at(-1)).toBe('NEXT: gstack-ship-queue land --pr <n> --pin ' + r.head + ' once the PR the host opens has green checks');
  });

  test('a fork PR on release/<version> is never reused: open lists same-repo heads only and opens its own PR', () => {
    const repo = landed();
    const calls: string[][] = [];
    const fork = [{ url: 'https://github.com/fork/r/pull/9', isCrossRepository: true }];
    const r = openRelease({ repoRoot: repo.work, base: 'main', gh: (args) => {
      calls.push(args);
      if (args[1] !== 'list') return { ok: true, out: 'https://github.com/o/r/pull/43\n', err: '' };
      const jq = args[args.indexOf('--jq') + 1] ?? '';
      return { ok: true, out: jq.includes('select(.isCrossRepository | not)') ? '' : fork[0]!.url + '\n', err: '' };
    } });
    expect(r.ok).toBe(true);
    if (!r.ok) return;
    expect(r.pr).toBe('43');
    expect(calls.map(a => a[1])).toEqual(['list', 'create']);
  });

  test('a checkout with node_modules commits only the stamp, and opening again at the same base replaces the release branch', () => {
    const repo = landed();
    fs.writeFileSync(path.join(repo.work, '.gitignore'), 'node_modules/\n');
    repo.git('add', '.gitignore');
    repo.git('commit', '-q', '-m', 'ignore node_modules');
    repo.git('push', '-q', 'origin', 'HEAD:refs/heads/main');
    fs.mkdirSync(path.join(repo.work, 'node_modules'));
    const gh = () => ({ ok: true, out: 'https://github.com/o/r/pull/43\n', err: '' });
    const first = openRelease({ repoRoot: repo.work, base: 'main', gh });
    expect(first.ok).toBe(true);
    if (!first.ok) return;
    expect(repo.git('show', '--name-only', '--format=', first.head!).split('\n')).not.toContain('node_modules');
    expect(classifyRelease({ repoRoot: repo.work, policy: policyOf(repo), mergeBase: repo.git('rev-parse', 'origin/main'), head: first.head! }).ok).toBe(true);
    const again = openRelease({ repoRoot: repo.work, base: 'main', gh, now: new Date('2030-01-02T00:00:00Z') });
    expect(again.ok).toBe(true);
    if (!again.ok) return;
    expect(repo.git('--git-dir', repo.origin, 'rev-parse', 'refs/heads/' + again.branch)).toBe(again.head!);
    expect(repo.git('branch', '--list', 'release/*')).toBe('');
  });

  // Value: protects=a reopen that force-pushes a new stamp also rewrites the open release PR's body, so its change count, notes, base and
  //   land pin match the pushed head; fails_when=the open PR keeps the old body (GSTA-677 on #4573); seam=openRelease with a gh stub
  test('reopening at a moved base rewrites the open release PR\'s body to the new stamp', () => {
    const repo = landed();
    const calls: string[][] = [];
    const r = openRelease({ repoRoot: repo.work, base: 'main', gh: (args) => { calls.push(args); return { ok: true, out: 'https://github.com/o/r/pull/44\n', err: '' }; } });
    expect(r.ok).toBe(true);
    if (!r.ok) return;
    expect(calls.map(a => a.slice(0, 3))).toEqual([['pr', 'list', '--head'], ['pr', 'edit', 'https://github.com/o/r/pull/44']]);
    const body = calls[1]![calls[1]!.indexOf('--body') + 1]!;
    expect(body).toContain(`--pin ${r.head}`);
    expect(sectionText(body, 'Release notes')).toBe('- a change\n- b feature');
    const refused = openRelease({ repoRoot: repo.work, base: 'main', now: new Date('2030-01-02T00:00:00Z'), gh: (args) => (args[1] === 'edit' ? { ok: false, out: '', err: 'HTTP 502' } : { ok: true, out: 'https://github.com/o/r/pull/44\n', err: '' }) });
    expect(refused).toMatchObject({ ok: false, code: 'RELEASE_STAMP_INVALID' });
  });

  test('on Capy, a reopen hands the new body to the host tool without gh pr edit', () => {
    const repo = landed();
    const state = fs.mkdtempSync(path.join(repo.work, '..', 'state-'));
    const calls: string[][] = [];
    const r = openRelease({ repoRoot: repo.work, base: 'main', env: { GSTACK_CAPY: '1', GSTACK_STATE_ROOT: state }, gh: (args) => {
      calls.push(args);
      if (args[0] === 'repo') return { ok: true, out: JSON.stringify({ nameWithOwner: 'o/r', url: 'https://github.com/o/r' }), err: '' };
      return { ok: true, out: 'https://github.com/o/r/pull/44\n', err: '' };
    } });
    expect(r.ok).toBe(true);
    if (!r.ok) return;
    expect(calls.map(a => a.slice(0, 2).join(' '))).toEqual(['pr list', 'repo view']);
    const handed = r.lines.find(l => l.startsWith('HOST_PUBLISH: '))!;
    expect(handed).toStartWith('HOST_PUBLISH: pr-body 44 repo=o/r');
    const body = fs.readFileSync(/ body-file=(\S+)/.exec(handed)![1]!, 'utf8');
    expect(body).toContain(`--pin ${r.head}`);
    expect(r.lines).toContain('RELEASE_PR: #44 https://github.com/o/r/pull/44');
  });

  test('--dry-run creates nothing; an empty base is refused', () => {
    const repo = landed();
    const dry = openRelease({ repoRoot: repo.work, base: 'main', dryRun: true, gh: () => { throw new Error('no gh in a dry run'); } });
    expect(dry.ok).toBe(true);
    expect(repo.git('--git-dir', repo.origin, 'branch', '--list', 'release/*')).toBe('');
    const empty = landed({});
    const none = openRelease({ repoRoot: empty.work, base: 'main', gh: () => { throw new Error('no gh when empty'); } });
    expect(none.ok).toBe(false);
    expect((none as { code: string }).code).toBe('RELEASE_STAMP_EMPTY');
  });
});