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
22.6 KB
Raw Blame
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/**
 * gstack-ship-queue — the shared merge queue, one subcommand per protocol
 * step (field list 2, W1; docs/ship-policy.md#run-a-shared-merge-queue).
 *
 *   gstack-ship-queue ready --pr <n> [--pregate <pregate.json>] [--gate-exit <rc> --gate-log <file>]
 *                           (refused with QUEUE_RECEIPT_MISSING|STALE unless the PR body carries /ship's receipt for HEAD)
 *   gstack-ship-queue stamp --pr <n> --version <X> --expect-gated <sha> --expect-base <sha>
 *                           [--expect-order <pr,...>] [--allow-repo-commands] [--gate-exit <rc> --gate-log <file>]
 *   gstack-ship-queue verify --pr <n> (--gated <sha> | --record <gate-ahead.json>) [--receipt <sha256>]
 *                           [--expect-head <sha>] [--ref <ref>] [--no-fetch] [--gate-exit <rc> --gate-log <file>]
 *   gstack-ship-queue gate-ahead --after <pr> --pr <n> [--predecessor-ref <ref>] [--allow-repo-commands]
 *   gstack-ship-queue gate-ahead --record --pr <n> --attempt <id> --exit <rc> --log <file>
 *   gstack-ship-queue gate-ahead --list --pr <n>
 *   gstack-ship-queue verify --pr <n> --screen                  (train policy: the head's screen verdict from its run)
 *   gstack-ship-queue verify --post-merge <sha> [--timeout <s>] (after a merge: main's push workflows at that commit until they settle)
 *   gstack-ship-queue land --pr <n> --pin <sha> [--accept-gate-disposition <id>]... [--repair] [--dry-run] [--allow-repo-commands] [--break-lock]   (merge: direct; lib/ship-queue-land-direct.ts)
 *   gstack-ship-queue verify --pr <n> --pin <sha> [--accept-gate-disposition <id>]...   (land's receipt and gate-disposition acceptance, read-only, for a lander that merges another way)
 *   gstack-ship-queue land --pr <n> [--dry-run] [--no-wait] [--break-lock [--break-train-lock]]   (the merge step; lib/ship-queue-land.ts)
 *   gstack-ship-queue land --pr <n> --repair                    (after QUEUE_LAND_DRIFT: open the outside merge's release PR)
 *   gstack-ship-queue land --census
 *   gstack-ship-queue count [--authors <login,...>]   (R119: finished PRs waiting to land, one gh call; lib/ship-queue-count.ts)
 *   gstack-ship-queue train build|status|verdict|bisect|rebuild|watch|prune ...   (merge trains; train --help)
 *   gstack-ship-queue wave plan|build|status|settle ...   (wave PRs: 3-6 same-area PRs in one train slot; wave --help)
 *
 * Every subcommand takes --base <branch> (default: ready's --pr PR base, else lib/default-base.ts) and
 * ends with GSTACK_RESULT: skill=ship-queue status=complete|refused run=<path>.
 * gstack-restamp stays the primitive. Nothing here pushes, except land, ready
 * under changelog_fragments (its READY receipt note), and under a
 * ship policy with a `train` block: merge trains push train/<nonce> branches
 * and the refs/notes/gstack-trains records, and dispatch through eval-bg.
 * Logic: lib/ship-queue.ts, crew/lib/ship-queue-gate.ts, crew/lib/ship-queue-train*.ts
 * (loaded only on the train paths).
 */
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { ghSpawnSync } from '../lib/gh-poll';
import { EXIT, exitTableHelp, formatResult } from '../lib/headless-artifacts';
import { versionAtRef } from '../lib/restamp';
import { RESULT_CODES } from '../lib/result-codes';
import { resolveBaseBranch } from '../lib/ship-policy';
import { loadBasePolicy, ready, refreshBase, stamp, verify, type QueueContext, type StepOutput } from '../lib/ship-queue';
import { attemptFile, listAttempts, prepareGateAhead, recordGateAhead, type QueueFailure } from '../crew/lib/ship-queue-gate';
import { logShipCall } from '../lib/ship-call-log';

logShipCall('gstack-ship-queue');

const HELP = `gstack-ship-queue — the shared merge queue's protocol steps (docs/ship-policy.md#run-a-shared-merge-queue)

  ready --pr <n> [--pregate <file>] [--gate-exit <rc> --gate-log <file>]
                                           READY #<n> <head> STAMP_VERSION=<X|unstamped>, CI at that head, PREGATE, gate state,
                                           SHIP_RECEIPT (refused unless the PR body carries /ship's receipt for that head),
                                           TRIAL_MERGES for each open PR sharing a file, and the Attention section opened by the
                                           receipt's risk class
  stamp --pr <n> --version <X> --expect-gated <sha> --expect-base <sha> [--expect-order <pr,...>] [--allow-repo-commands]
        [--gate-exit <rc> --gate-log <file>]
                                           restamp, commit and prove: QUEUE_STAMP: <pr> <X> head= gated= tree= receipt=
  verify --pr <n> --gated <sha> | --record <file> [--receipt <sha256>] [--expect-head <sha>] [--ref <ref>] [--no-fetch]
        [--gate-exit <rc> --gate-log <file>]   (full_e2e: --gated needs the lane's passing gate run on that head)
                                           the coordinator's check from the PR's pushed head: VERIFY: ... and MERGE_CONDITION
  gate-ahead --after <pr> --pr <n> [--predecessor-ref <ref>] [--allow-repo-commands]
                                           prepare an attempt: merged, stamped worktree, gated sha and the gate command
  gate-ahead --record --pr <n> --attempt <id> --exit <rc> --log <file>
                                           bind the gate result to that attempt's gated tree; removes its worktree
  gate-ahead --list --pr <n>               attempts for a PR, newest last (the current one)
  verify --pr <n> --pin <sha> [--accept-gate-disposition <id>]...
                                           land --pin's receipt and gate-disposition check, read-only, for a lander that merges
                                           another way: prints each GATE_DISPOSITION line and exits 0 only when every one is accepted
  verify --pr <n> --screen                 (train policy) the PR head's screen verdict read from its run (SCREEN_VERDICT)
  verify --post-merge <sha> [--timeout <s>] wait for every check run at a merged commit to settle: POST_MERGE: green|red|pending
                                           and one CHECK: line per workflow; resumable, default timeout 2700 s
  land --pr <n> --pin <sha> [--accept-gate-disposition <id>]... [--repair] [--dry-run] [--allow-repo-commands] [--break-lock] [--body-file <f>]
                                           merge: direct: merge the PR at its own green head (receipt and READY at the pin, no stamp
                                           files, checks green, mergeable clean), verify the tree, write a land note; a stale base
                                           runs land.merged_checks, repo commands, only with --allow-repo-commands (never --dry-run);
                                           it holds the land lock from the re-fetch to the merge (--break-lock: a stale one);
                                           --repair: while frozen, land the one repair PR the freeze admits (recorded under the lock);
                                           an owner gate disposition the approval store applies at the pin merges only when the
                                           lander passes --accept-gate-disposition <its approval id> (docs/ship-policy.md#gate-dispositions)
  land --pr <n> [--dry-run] [--no-wait] [--timeout <min>] [--break-lock [--break-train-lock]] [--allow-repo-commands] [--body-file <f>]
                                           the merge step: lock, merge the base, stamp (fragments folded), push the stamp commit,
                                           wait for its checks, squash with --match-head-commit, confirm the base tree; resumable
                                           Both forms merge as one commit titled "<PR title> (#n)" whose body is the PR body's opening
                                           lines (at most 3) plus the branch's trailers; --body-file replaces the opening lines; METHOD,
                                           SUBJECT and BODY lines show it first (docs/writing-prs.md#the-commit-on-main)
  land --pr <n> --repair                   after QUEUE_LAND_DRIFT: open the PR that gives the merge outside land its own
                                           release; /ship and land it, which releases the lock
  land --census                            what land would do with every open PR (read-only)
  count [--authors <login,...>]            finished PRs waiting to land, from one gh call: QUEUE_COUNT (count, how many waited 24h
                                           or more, the oldest wait), a FINISHED line each, and DRAIN when more than 6 wait or one
                                           has waited 24h (docs/captain.md#drain-the-queue); finished = by an author (default
                                           garrytan,capy-ai,garrytan-agents), on the base, not a draft or conflicting, green at its head
  train build|status|verdict|bisect|rebuild|watch|prune ...
                                           merge trains, when the base policy declares a train block (train --help;
                                           docs/ship-policy.md#run-a-merge-train); ready then takes --screen|--no-screen
  wave plan|build|status|settle ...        wave PRs under a train policy: 3-6 same-area PRs in one slot and one version
                                           (wave --help; docs/ship-policy.md#wave-prs)

--base <branch>: base branch (default: for ready, the base of the PR --pr names; otherwise origin/HEAD unless it names the checked-out branch, else the PR's base, origin/main; ready refuses a --base that is not its PR's base). Nothing here pushes, except land (the stamp commit and the
refs/notes/gstack-land lock), ready under changelog_fragments (its READY receipt note) and merge trains.
${exitTableHelp()}`;

/** land --body-file: the plain lines that replace the PR body's opening in the merge commit; land scans them like the rest of the message. */
function landBody(file: string | undefined): { text?: string } | { error: string } {
  if (file === undefined) return {};
  try { return { text: fs.readFileSync(path.resolve(file), 'utf8') }; } catch (e) { return { error: `cannot read --body-file ${file}: ${(e as NodeJS.ErrnoException).code ?? String(e)}` }; }
}

function flag(args: string[], name: string): string | undefined {
  const i = args.indexOf(name);
  return i >= 0 ? args[i + 1] : undefined;
}

/** Every --accept-gate-disposition value, or the first one that is not an approval id. */
function acceptedIds(args: string[]): { ids: string[]; bad?: string } {
  const ids = args.flatMap((a, i) => a === '--accept-gate-disposition' ? [args[i + 1] ?? ''] : []);
  return { ids, bad: ids.find(id => !/^a-[0-9a-f]{12}$/.test(id)) };
}

function finish(cmd: string, out: StepOutput): number {
  for (const line of out.lines) process.stdout.write(line + '\n');
  if (out.failure) {
    const f = out.failure;
    process.stderr.write(`gstack-ship-queue ${cmd}: ${f.message}; fix: ${f.fix ?? RESULT_CODES[f.code].fix} (${f.code})\n`);
  }
  process.stdout.write(formatResult('ship-queue', out.ok ? 'complete' : 'refused', out.run) + '\n');
  if (out.ok) return EXIT.ok;
  return out.failure && ['QUEUE_VERIFY_MISMATCH', 'QUEUE_STAMP_NOT_STAMP_ONLY', 'QUEUE_LAND_UNVERIFIED'].includes(out.failure.code) ? EXIT.fail : EXIT.refused;
}

const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;

function usage(message: string): number {
  process.stderr.write(`gstack-ship-queue: ${message}\n${HELP}\n`);
  return EXIT.usage;
}

function gateAhead(ctx: QueueContext, args: string[]): number {
  const pr = flag(args, '--pr');
  if (!pr) return usage('gate-ahead needs --pr <n> (records are keyed by PR)');
  if (args.includes('--list')) {
    const all = listAttempts(ctx.repoRoot, pr);
    for (const a of all) process.stdout.write(`ATTEMPT: ${a.attempt} state=${a.state} gated_tree=${a.gated_tree} predecessor=#${a.predecessor_pr}@${a.predecessor_head.slice(0, 12)}${a.result ? ` exit=${a.result.exit}` : ''}${a === all.at(-1) ? ' current' : ''}\n`);
    if (!all.length) process.stdout.write(`ATTEMPT: none for #${pr}\n`);
    return EXIT.ok;
  }
  if (args.includes('--record')) {
    const attempt = flag(args, '--attempt');
    const exit = flag(args, '--exit');
    const log = flag(args, '--log');
    if (!attempt || exit === undefined || !/^-?\d+$/.test(exit) || !log) return usage('gate-ahead --record needs --attempt <id> --exit <rc> --log <file>');
    const r = recordGateAhead({ repoRoot: ctx.repoRoot, pr, attempt, exit: Number(exit), log: path.resolve(log) });
    if ('code' in r) return finish('gate-ahead', { ok: false, lines: [], failure: r, run: attemptFile(ctx.repoRoot, pr, attempt) });
    const cur = r.current && r.current.attempt !== attempt ? `no (superseded by ${r.current.attempt})` : 'yes';
    return finish('gate-ahead', {
      ok: true, run: path.relative(ctx.repoRoot, r.file),
      lines: [
        `GATE_RECORD: pr=${pr} attempt=${attempt} exit=${r.record.result!.exit} gated_tree=${r.record.gated_tree} log_sha256=${r.record.result!.log_sha256} current=${cur}`,
        ...(r.repeated ? ['note: identical retry; the stored result is returned'] : []),
        `record: ${r.file}`,
        `next: send the record file with the READY report; the coordinator runs gstack-ship-queue verify --pr ${pr} --record <file> once this PR is stamped`,
      ],
    });
  }
  const after = flag(args, '--after');
  if (!after) return usage('gate-ahead needs --after <predecessor-pr>, --record or --list');
  const policy = loadBasePolicy(ctx);
  if ('message' in policy) return finish('gate-ahead', { ok: false, lines: [], failure: policy, run: 'none' });
  const at = versionAtRef(ctx.repoRoot, 'HEAD');
  const r = prepareGateAhead({
    repoRoot: ctx.repoRoot, base: ctx.base, pr, after, predecessorRef: flag(args, '--predecessor-ref'), allowRepoCommands: args.includes('--allow-repo-commands'),
    policy: policy.policy, versionRel: 'rel' in at ? at.rel : 'VERSION',
  });
  if ('code' in r) return finish('gate-ahead', { ok: false, lines: [], failure: r as QueueFailure, run: 'none' });
  const rec = r.record;
  const log = path.join(path.dirname(rec.worktree), 'gate.log');
  const cmd = rec.gate_command ?? '<your gate command>';
  const superseded = listAttempts(ctx.repoRoot, pr).filter(a => a.attempt !== rec.attempt && a.state === 'prepared').map(a => a.attempt);
  return finish('gate-ahead', {
    ok: true, run: path.relative(ctx.repoRoot, r.file),
    lines: [
      `GATE_AHEAD: pr=${pr} attempt=${rec.attempt} gated=${rec.gated_head} tree=${rec.gated_tree} merge_tree=${rec.merge_tree} predecessor=#${rec.predecessor_pr}@${rec.predecessor_head.slice(0, 12)} version=${rec.version}`,
      `worktree: ${rec.worktree}`,
      `record: ${r.file}`,
      `GATE_COMMAND: ${rec.gate_command ?? 'none (the policy sets no gate_command; run the repo gate you would run on a PR head)'}`,
      ...(superseded.length ? [`note: this attempt is now current; earlier unrecorded attempts (${superseded.join(', ')}) keep their worktrees until recorded`] : []),
      `next: (cd ${shq(rec.worktree)} && ${cmd}) > ${shq(log)} 2>&1; gstack-ship-queue gate-ahead --record --pr ${pr} --attempt ${rec.attempt} --exit $? --log ${shq(log)}`,
    ],
  });
}

/** Which land form this checkout's base policy takes, so a lander never guesses between the two. */
function landFormLine(repoRoot: string): string {
  const loaded = loadBasePolicy({ repoRoot, base: resolveBaseBranch(repoRoot), gh: () => ({ ok: false, out: '', err: 'no gh in --help' }) });
  if ('message' in loaded) return '';
  return loaded.policy.merge === 'direct'
    ? `\nThis repository (merge: direct): land each READY PR with gstack-ship-queue land --pr <n> --pin <the READY's head sha>.\n`
    : `\nThis repository (merge: ${loaded.policy.merge}): land with gstack-ship-queue land --pr <n>${loaded.policy.train ? ', or train land for a built train' : ''}; --pin is the merge: direct form.\n`;
}

async function main(argv: string[]): Promise<number> {
  const [cmd, ...args] = argv;
  const probe = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });
  if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n' + (probe.status === 0 ? landFormLine(probe.stdout.trim()) : '')); return cmd ? EXIT.ok : EXIT.usage; }
  if (probe.status !== 0) return usage('not inside a git repository');
  const repoRoot = probe.stdout.trim();
  const gh = (a: string[]) => { const r = ghSpawnSync(a, { cwd: repoRoot, encoding: 'utf8', timeout: 60_000 }); return { ok: r.status === 0, out: r.stdout ?? '', err: r.stderr ?? (r.error ? String(r.error.message) : '') }; };
  const pr = flag(args, '--pr');
  const explicitBase = flag(args, '--base');
  let prBase: string | undefined;
  if (pr && /^\d+$/.test(pr) && cmd === 'ready') {
    const view = gh(['pr', 'view', pr, '--json', 'baseRefName']);
    try { prBase = view.ok ? JSON.parse(view.out).baseRefName || undefined : undefined; } catch {}
  }
  const ctx: QueueContext = { repoRoot, base: resolveBaseBranch(repoRoot, explicitBase ?? prBase), gh };
  if (cmd === 'gate-ahead') return gateAhead(ctx, args);
  if (cmd === 'train') {
    const train = await import('../crew/lib/ship-queue-train-cli');
    if (!args[0] || args[0].startsWith('-')) { process.stdout.write(train.TRAIN_HELP + '\n'); return args.includes('--help') || args.includes('-h') ? EXIT.ok : EXIT.usage; }
    const loaded = args[0] === 'build' || args[0] === 'land' ? loadBasePolicy(ctx) : null;
    if (loaded && !('message' in loaded) && loaded.policy.merge === 'direct') return finish(`train ${args[0]}`, { ok: false, lines: [], run: 'none', failure: { code: 'QUEUE_NOT_READY', message: 'the base policy sets merge: direct, so trains are off', fix: 'land each READY PR with gstack-ship-queue land --pr <n> --pin <sha> (docs/ship-policy.md#land-direct)' } });
    return train.trainMain(ctx, args);
  }
  if (cmd === 'count') return finish('count', (await import('../lib/ship-queue-count')).queueCount(ctx, { authors: flag(args, '--authors')?.split(',').map(s => s.trim()).filter(Boolean) }));
  if (cmd === 'wave') return (await import('../crew/lib/ship-queue-wave')).waveMain(ctx, args);
  if (cmd === 'verify' && flag(args, '--post-merge') !== undefined) return (await import('../crew/lib/ship-queue-train-cli')).postMergeMain(ctx, args);
  if (cmd === 'land') {
    const l = await import('../lib/ship-queue-land');
    if (args.includes('--census')) return finish('land', l.census(ctx));
    if (!pr || !/^\d+$/.test(pr)) return usage('land needs --pr <number> (or --census)');
    const body = landBody(flag(args, '--body-file'));
    if ('error' in body) return usage(body.error);
    if (args.includes('--pin')) {
      const pin = flag(args, '--pin') ?? '';
      if (!/^[0-9a-f]{40,64}$/.test(pin)) return usage('--pin needs the full head sha the READY names');
      const accept = acceptedIds(args);
      if (accept.bad !== undefined) return usage(`--accept-gate-disposition needs an approval id (a-<12 hex>), not ${JSON.stringify(accept.bad)}`);
      return finish('land', (await import('../lib/ship-queue-land-direct')).landDirect(ctx, { pr, pin, body: body.text, acceptGateDispositions: accept.ids, dryRun: args.includes('--dry-run'), allowRepoCommands: args.includes('--allow-repo-commands'), breakLock: args.includes('--break-lock'), repair: args.includes('--repair') }));
    }
    const timeout = flag(args, '--timeout');
    return finish('land', l.land(ctx, { pr, body: body.text, repair: args.includes('--repair'), dryRun: args.includes('--dry-run'), noWait: args.includes('--no-wait'), breakLock: args.includes('--break-lock'), breakTrainLock: args.includes('--break-train-lock'), allowRepoCommands: args.includes('--allow-repo-commands'), waitTimeoutMin: timeout && /^\d+$/.test(timeout) ? Number(timeout) : undefined }));
  }
  if (!pr || !/^\d+$/.test(pr)) return usage(`${cmd} needs --pr <number>`);
  const gateExit = flag(args, '--gate-exit');
  if (gateExit !== undefined && !/^-?\d+$/.test(gateExit)) return usage('--gate-exit needs an exit code');
  const gate = { gateExit: gateExit === undefined ? undefined : Number(gateExit), gateLog: flag(args, '--gate-log') };
  if (cmd === 'ready') {
    if (explicitBase && prBase && prBase !== ctx.base) return finish('ready', { ok: false, lines: [], run: 'none', failure: { code: 'QUEUE_NOT_READY', message: `#${pr} targets ${prBase}, not ${ctx.base}, so a receipt reviewed against ${ctx.base} does not cover it`, fix: `rerun ready without --base, or with --base ${prBase}` } });
    const unfetched = refreshBase(ctx);
    const loaded = loadBasePolicy(ctx);
    if (!('message' in loaded) && loaded.policy.train) return (await import('../crew/lib/ship-queue-train-cli')).readyMain(ctx, args, { pr, pregate: flag(args, '--pregate'), ...gate });
    if (unfetched) return finish('ready', { ok: false, lines: [], run: 'none', failure: unfetched });
    if (['--screen', '--no-screen', '--broad'].some(f => args.includes(f))) process.stderr.write('gstack-ship-queue ready: --screen/--no-screen/--broad ignored: the base policy declares no train block\n');
    return finish('ready', ready(ctx, { pr, pregate: flag(args, '--pregate'), ...gate }));
  }
  if (cmd === 'stamp') {
    const version = flag(args, '--version');
    const expectGated = flag(args, '--expect-gated');
    const expectBase = flag(args, '--expect-base');
    if (!version || !expectGated || !expectBase) return usage('stamp needs --version <X> --expect-gated <sha> --expect-base <sha>');
    return finish('stamp', stamp(ctx, {
      pr, version, expectGated, expectBase, expectOrder: flag(args, '--expect-order')?.split(',').map(s => s.trim()).filter(Boolean),
      allowRepoCommands: args.includes('--allow-repo-commands'), ...gate,
      failAfter: process.env.GSTACK_SHIP_QUEUE_FAIL_AFTER,
    }));
  }
  if (cmd === 'verify' && args.includes('--pin')) {
    const pin = flag(args, '--pin') ?? '';
    if (!/^[0-9a-f]{40,64}$/.test(pin)) return usage('--pin needs the full head sha the READY names');
    const accept = acceptedIds(args);
    if (accept.bad !== undefined) return usage(`--accept-gate-disposition needs an approval id (a-<12 hex>), not ${JSON.stringify(accept.bad)}`);
    return finish('verify', (await import('../lib/ship-queue-land-direct')).verifyPin(ctx, { pr, pin, acceptGateDispositions: accept.ids }));
  }
  if (cmd === 'verify') {
    if (flag(args, '--train') || args.includes('--screen')) return (await import('../crew/lib/ship-queue-train-cli')).verifyMain(ctx, args, pr);
    const record = flag(args, '--record');
    return finish('verify', verify(ctx, {
      pr, gated: flag(args, '--gated'), record: record ? path.resolve(record) : undefined, receipt: flag(args, '--receipt'),
      expectHead: flag(args, '--expect-head'), ref: flag(args, '--ref'), noFetch: args.includes('--no-fetch'), ...gate,
    }));
  }
  return usage(`unknown subcommand ${cmd}`);
}

process.exitCode = await main(process.argv.slice(2));