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
33.5 KB
Raw Blame
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
/**
 * gstack-review-plan — how much review the next /ship step dispatches (docs/review-policy.md#review-depth).
 *
 *   gstack-review-plan --base <ref> [--pass <full passes finished>] [--last none|full] [--fixed-blocking] [--fixed-below]
 *                      [--blocking-open] [--touched-gate] [--critical-found] [--adversarial-ran] [--gate-tagged <n>] [--gated a,b] [--force a,b|all]
 *                      [--reviewed-numbers <fingerprint>] [--depth-floor standard|full] [--range-base <sha>] [--pass1-depth light|standard|full] [--no-tiers]
 *                      [--targeted-ran <targeted_patch_id>] [--post-review] [--pr <n>] [--json]
 *
 * Reads the diff against the merge base with <ref> (committed, tracked uncommitted
 * edits and untracked files, through lib/review-collect.ts collectLive), runs
 * gstack-diff-scope and, unless --gate-tagged is given, gstack-gate-diff; prints
 * REVIEW_CLASS:, REVIEW_DEPTH: (depth, runtime lines, the rules hash, reasons and
 * result codes), GATE_SCAN:, TARGETED: (the money, gate, auth and secret classes, lib/review-targeted.ts),
 * FIX_RANGE: (with --range-base), REVIEW_PLAN:, one DEPTH_ERROR: per input that failed
 * the depth closed, one DISPATCH: plus DIFF_CMD: (and DIFF_EXCLUDE: none) per
 * reviewer and one SKIP: per reviewer left out. A plan that fails closed to full
 * exits 0; a diff git cannot list exits 1, and so does a base that is HEAD or already
 * contains it while the branch has commits its real base lacks (BASE_CONTAINS_HEAD,
 * lib/default-base.ts). Logic: lib/review-depth.ts.
 */
import * as fs from 'node:fs';
import * as path from 'node:path';
import { spawnSync } from '../lib/spawn-sync';
import { baseContainsHead } from '../lib/default-base';
import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
import { resultLine } from '../lib/result-codes';
import { gateOutcomeLine } from '../lib/gate-outcomes';
import { runScriptSync } from '../lib/script-invocation';
import { baseNote } from '../lib/gate-diff/git';
import { collectCommit, collectLive, consumerScanCap, reviewPlanTimeoutMs } from '../lib/review-collect';
import { excludeLines, fallbackLine, reviewExclude, type Exclusion } from '../lib/review-exclude';
import { isUnavailable } from '../lib/ship-policy';
import { reviewPolicy } from '../lib/ship-policy-review';
import { platformReviewAt } from '../lib/review-platform';
import { loadPolicyAt } from '../lib/ship-policy-at';
import { loadReaders, readersLine } from '../lib/review-fetch';
import { policySelection, selectFor } from '../lib/review-selection';
import { effectiveReaders, READERS_POLICY_DEFAULT } from '../lib/ship-policy-readers';
import { classifyDiff, diffCommand, keepCommand, planReview, reviewDepthLine, reviewPlanLine, scanNumbers, ROLE_EFFORT, SCOPED_RANGE_LINES, type Depth, type History } from '../lib/review-depth';
import { classList, targetedBriefSha, targetedClasses, targetedPatchId } from '../lib/review-targeted';
import { ruledCarries, targetedDelta } from '../lib/review-targeted-delta';
import { ownChangeSince, stampPathsSince } from '../lib/ship-receipt-depth';
import { RISK_CLASSES, type RiskClass } from '../lib/review-risk';
import { readRuledNotes, ruledEditLine, ruledEdits } from '../lib/ruled-notes';
import { readRunRecord } from '../lib/ship-run-record';
import { reviewPaths } from '../lib/ship-budget';
import { summarizeReviewLoop } from '../lib/review-scope';

const HELP = `gstack-review-plan — the review depth of the next /ship step (docs/review-policy.md#review-depth)

  --base <ref>              the base branch (merge base with HEAD is the diff base); required
  --pass <n>                full review passes this /ship run already finished (default 0), printed as PASS_COUNT:;
                            not the number of the pass about to run: plan pass 2 with --pass 1 --last full. Inside an open /ship
                            run, --last full refuses (exit 2) a --pass other than the passes this branch's review log holds for it
  --last none|full          the step that just finished (default none: plan pass 1)
  --fixed-blocking          the finished step fixed a blocking finding (raises light to standard)
  --fixed-below             the finished step fixed findings below the floor
  --blocking-open           a blocking finding is still open in fix scope
  --touched-gate            a fix touched a gate-class path
  --critical-found          a specialist reported a CRITICAL finding (Red Team on code class; raises light to standard)
  --adversarial-ran         Step 11's native adversarial pass already ran (a repeat skips it)
  --gate-tagged <n>         gate hunks the gate scan tagged (default: run gstack-gate-diff; failure means unavailable)
  --gated a,b               specialists the hit-rate stats tag GATE_CANDIDATE
  --force a,b|all           specialists forced by prompt flags (--all-specialists is all): at standard and full depth they join the
                            batched specialist's checklists, where maintainability, performance and simplification are read only when
                            forced; light runtime-0 docs dispatch them one reader each; targeted is no specialist and
                            refuses (exit 2): the plan dispatches it itself
  --reviewed-numbers <fp>   the numeric-claim fingerprint the outside voice already reviewed
  --depth-floor standard|full  raise the depth to at least this (never lowers it); /ship passes its prompt flag on every run
  --range-base <sha>        the fix range's base (this pass's PASS_HEAD): after a fixed blocker, round 2 is a full pass on the range; below full depth, a
                            committed range of at most ${SCOPED_RANGE_LINES} runtime lines now also gets a full pass (no scoped pass) that keeps
                            the Red Team and, on a range with runtime lines, the native adversarial; anything unread plans the full pass
  --no-tiers                specialists, audits and watchers at the host's default effort too (as gstack-config review_effort_tiers off does)
  --json                    the plan as JSON (depth, runtime_lines, rules, errors with input and repair, gate_scan, per-dispatch exclude)
  --pass1-depth <d>         pass 1's REVIEW_DEPTH depth: full, or absent, keeps pass 2 full
  --targeted-ran <id>       the TARGETED line's targeted_patch_id (the whole committed diff, tests included) when the targeted
                            reader last read it: the same patch skips it; any other id, none, or uncommitted edits dispatch it again.
                            With --range-base naming the commit that read happened on, a loop that is done plans NEXT: targeted
                            (one targeted reader on HEAD, TARGETED_DELTA: names the range) when the only change since is docs the
                            receipt cannot carry the record across (a money, security or numeric claim; GST-1598)
  --post-review             plan the Step 9 that /ship Step 16 stage 2.1 inserted for edits after the review bound (finish's
                            behavior STOP): they plan as a fix to a gate-class path, never a note, so below the round cap
                            it is a pass on the range, and at the cap it stops for the lane's Captain; pass --pass and --last
                            as the loop left them
  --pr <n>                  the PR whose platform review counts under review.platform on (default: this branch's PR)
  --prior-rounds <n>        R51 rounds earlier /ship runs on this PR already spent (printed as pr_rounds=)
  --prior-full <n>          the full rounds among them: with this run's full passes they count against the cap of 2, so pass 1
                            of a PR with 2 is one read-only full review (no fix round; a blocker is NEXT: stop (PR_ROUND_CAP)
                            for the lane's Captain to decide, never the owner).
                            Both come from the PR_REVIEW_FLAGS: line gstack-ship-preflight prints (gstack-ship-receipt history)
                            (docs/review-policy.md#rounds-per-pull-request; GST-2673)
  --declare-risk <classes>  risk classes the lane declares for the diff (comma list of ${RISK_CLASSES.join(', ')}): they join
                            the detected classes and only raise the depth; RISK_DECLARED: prints both (GST-1129)

Mode (R65, the base policy's review key): review.panel all (default) keeps today's panel on every class. review.panel risk
(opt-in; its one-reader shape has not passed a no-loss replay) runs lean off risk class, and review.panel off everywhere: lean runs one reader: risk class gets the merged reader on review.risk_model
(the native adversarial brief plus the checklists, the Red Team and the targeted brief), non-risk code the single reader at the
lane's reasoning (cross-family when it publishes numbers), docs the core read, tests one batched testing reader (R51); a full round 2 after fixes, never more
than 2 rounds. review.platform on (any panel): a light diff with no numeric claims whose PR
carries capy-ai[bot]'s review at HEAD plans NEXT: platform and a planned SKIP for every reader.
Depth (R51, risk not size): full on gate class, a risk class (money, auth, secret, security, data, review.risk_paths) or any DEPTH_ERROR;
standard only by --depth-floor or a raise; otherwise light. TARGETED: the money,
gate, auth and secret classes the diff touches; any class dispatches the targeted reader at every depth. NEXT: full, voices (gate class: Step 11 before any stop,
then ask again with --adversarial-ran), targeted (the targeted-only read after the loop), stop or done. A full plan
from an error exits 0; exit 1 means no plan could be built (git could not list the diff).
${exitTableHelp()}`;

const args = process.argv.slice(2);
const flag = (n: string) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : undefined; };
const has = (n: string) => args.includes(n);
const list = (n: string) => (flag(n) ?? '').split(',').map(s => s.trim()).filter(Boolean);
const git = (a: string[]) => { const r = spawnSync('git', ['-c', 'core.quotePath=false', ...a], { encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 }); return r.status === 0 ? r.stdout : null; };

/**
 * The full passes the checkout's open /ship run already logged, counted the way the receipt counts them: gstack-review-scope's
 * summarizeReviewLoop over this branch's review log since the run record started. Null when no run is open or the log cannot be read.
 */
function loggedPasses(root: string): { passes: number; run: string } | null {
  const read = readRunRecord(root);
  if (read.kind !== 'record' || read.record.state !== 'open') return null;
  let text = '';
  try { text = fs.readFileSync(reviewPaths(root, process.env).reviewLog, 'utf8'); } catch (e: any) { if (e?.code !== 'ENOENT') return null; }
  const rows = text.split('\n').flatMap(line => { try { return [JSON.parse(line) as Record<string, any>]; } catch { return []; } });
  return { passes: summarizeReviewLoop(rows, read.record.started_at).passes, run: read.record.run };
}

function main(): number {
  if (has('--help') || has('-h')) { process.stdout.write(HELP + '\n'); return EXIT.ok; }
  const base = flag('--base');
  if (!base) { process.stderr.write(`gstack-review-plan: --base <ref> is required\n${HELP}\n`); return EXIT.usage; }
  const last = (flag('--last') ?? 'none') as History['last'];
  if (!['none', 'full'].includes(last)) { process.stderr.write(`gstack-review-plan: --last must be none or full${last === 'fix-check' ? ' (fix-checks and their grants were removed in GST-3562 part 4; docs/troubleshooting.md#pr-round-cap)' : ''}\n`); return EXIT.usage; }
  const pass1Depth = (flag('--pass1-depth') ?? 'full') as Depth;
  if (!['light', 'standard', 'full'].includes(pass1Depth)) { process.stderr.write('gstack-review-plan: --pass1-depth must be light, standard or full\n'); return EXIT.usage; }
  const pass = Number(flag('--pass') ?? '0');
  if (!Number.isInteger(pass) || pass < 0) { process.stderr.write('gstack-review-plan: --pass needs an integer >= 0\n'); return EXIT.usage; }
  const floor = flag('--depth-floor') as Depth | undefined;
  if (has('--depth-floor') && floor !== 'standard' && floor !== 'full') { process.stderr.write('gstack-review-plan: --depth-floor must be standard or full (a floor only raises the depth)\n'); return EXIT.usage; }
  const rangeBase = flag('--range-base');
  if (has('--range-base') && (!rangeBase || rangeBase.startsWith('-'))) { process.stderr.write('gstack-review-plan: --range-base needs the fix range\'s base commit (this pass\'s PASS_HEAD)\n'); return EXIT.usage; }
  if (list('--force').includes('targeted')) { process.stderr.write('gstack-review-plan: --force targeted: the targeted reader is no specialist; the plan dispatches it whenever the diff has a targeted class, and after a finished loop for a docs claim added since its read: pass --range-base <the commit it read> --targeted-ran <the targeted_patch_id it read> (docs/review-policy.md#targeted-only-read-after-the-loop)\n'); return EXIT.usage; }
  const declared = list('--declare-risk');
  if (has('--declare-risk') && (!declared.length || declared.some(c => !(RISK_CLASSES as readonly string[]).includes(c)))) { process.stderr.write(`gstack-review-plan: --declare-risk ${flag('--declare-risk') ?? ''}: each class is one of ${RISK_CLASSES.join(', ')} (a declaration only raises the depth)\n`); return EXIT.usage; }
  const root = git(['rev-parse', '--show-toplevel'])?.trim();
  if (!root) { process.stderr.write('gstack-review-plan: run it inside a git checkout\n'); return EXIT.fail; }
  process.chdir(root);
  const retired = ['--grant', '--fix-checks', '--round-grant', '--stop', '--fix-check-prompt'].filter(has);
  if (retired.length) { process.stderr.write(`gstack-review-plan: ${retired.join(', ')}: fix-checks, round grants and owner grants were removed in GST-3562 part 4; a PR at its round cap goes to the lane's Captain (docs/troubleshooting.md#pr-round-cap)\n`); return EXIT.usage; }
  const priorRounds = Number(flag('--prior-rounds') ?? '0');
  const priorFull = Number(flag('--prior-full') ?? '0');
  if (![priorRounds, priorFull].every(n => Number.isInteger(n) && n >= 0)) { process.stderr.write('gstack-review-plan: --prior-rounds and --prior-full need integers >= 0 (PR_REVIEW_FLAGS: from gstack-ship-preflight)\n'); return EXIT.usage; }
  const logged = last === 'full' ? loggedPasses(root) : null;
  if (logged && logged.passes !== pass) { process.stderr.write(`gstack-review-plan: --pass ${pass} says ${pass} full pass${pass === 1 ? '' : 'es'} finished, but the review log holds ${logged.passes} for /ship run ${logged.run}; --pass counts the passes already finished, not the pass about to run, so rerun with --pass ${logged.passes} (GSTA-891)\n`); return EXIT.usage; }
  const collected = collectLive(root, base);
  if (collected.errors.length) {
    for (const e of collected.errors) process.stderr.write(`gstack-review-plan: git could not list the diff (${e.input}: ${e.detail}); fix: ${e.repair}; no plan is safer than a plan for an empty diff\n`);
    return EXIT.fail;
  }
  const note = collected.base && baseNote(base, collected.base);
  if (note) process.stderr.write(`gstack-review-plan: ${note}\n`);
  const ref = collected.base?.ref ?? base;
  const head = git(['rev-parse', 'HEAD'])?.trim() ?? 'unknown';
  const self = collected.mergeBase === head ? baseContainsHead(root, ref) : null;
  if (self) { process.stderr.write(`${resultLine('gstack-review-plan', 'BASE_CONTAINS_HEAD', self)}; no plan is safer than a plan for a diff compared with itself\n`); return EXIT.fail; }
  const binDir = path.dirname(Bun.fileURLToPath(import.meta.url));
  const scopeOf = (args: string[]): Record<string, string> => {
    const run = runScriptSync(path.join(binDir, 'gstack-diff-scope'), args, { encoding: 'utf8', timeout: 60_000 });
    const s: Record<string, string> = {};
    for (const l of (run.stdout ?? '').split('\n')) { const m = /^(SCOPE_[A-Z_]+)=(.*)$/.exec(l); if (m) s[m[1]!] = m[2]!; }
    if (run.status !== 0 && !s.SCOPE_ERROR) s.SCOPE_ERROR = `exit ${run.status}`;
    return s;
  };
  const runGateDiff = (args: string[]) => runScriptSync(path.join(binDir, 'gstack-gate-diff'), args, { encoding: 'utf8', timeout: 120_000, maxBuffer: 64 * 1024 * 1024 });
  const tagCount = (stdout: string | undefined, status: number | null): number | null => {
    const m = /GATE_SUMMARY: .*?tagged=\{([^}]*)\}/.exec(stdout ?? '');
    return status === 0 && m ? m[1]!.split(',').reduce((n, kv) => n + (Number(kv.split(':')[1]) || 0), 0) : null;
  };
  const gateTagsOf = (args: string[]): number | null => { const g = runGateDiff(args); return tagCount(g.stdout, g.status); };
  const diffBase = collected.mergeBase ?? base;
  const scope = scopeOf([diffBase]);
  const baseSha = collected.registry.sha ?? git(['rev-parse', '--verify', '-q', `${ref}^{commit}`])?.trim() ?? '';
  const policy = baseSha ? loadPolicyAt(root, baseSha, ref) : null;
  const declares = !!policy && !isUnavailable(policy) && policy.policy.review_exclude_paths.length > 0;
  const readersLoad = baseSha ? loadReaders(root, baseSha, ref, head) : null;
  if (readersLoad?.state === 'refused') { for (const l of readersLoad.lines) process.stderr.write(l + '\n'); return EXIT.refused; }
  const readers = readersLoad?.state === 'ok' ? readersLoad.readers : effectiveReaders(READERS_POLICY_DEFAULT, null);
  const review = reviewPolicy(policy && !isUnavailable(policy) ? policy.policy : null);
  const riskPaths = review.risk_paths.length ? { riskPaths: review.risk_paths } : {};
  const platform = review.platform === 'on' ? platformReviewAt(root, head, { pr: flag('--pr') }) : null;
  let tagged: Set<string> | null = null;
  let gateTagged: number | null;
  if (declares) {
    const g = runGateDiff([diffBase, '--format', 'jsonl']);
    gateTagged = tagCount(g.stdout, g.status);
    tagged = gateTagged === null ? null : new Set((g.stdout ?? '').split('\n').slice(1).flatMap(l => { try { const h = JSON.parse(l) as { path?: string; tags?: unknown[] }; return h.path && h.tags?.length ? [h.path] : []; } catch { return []; } }));
    if (flag('--gate-tagged') !== undefined) gateTagged = Number(flag('--gate-tagged'));
  } else gateTagged = flag('--gate-tagged') !== undefined ? Number(flag('--gate-tagged')) : gateTagsOf([diffBase]);
  if (gateTagged !== null && !Number.isFinite(gateTagged)) gateTagged = null;
  const exclusion: Exclusion = !baseSha || !collected.mergeBase ? { state: 'none' } : reviewExclude({ root, baseSha, ref, mergeBase: collected.mergeBase, perPath: collected.perPath, added: collected.added, classRoot: root, gateTagged: tagged, context: 'gstack-review-plan', vendoredFetch: true });
  if (exclusion.state === 'refused') { for (const l of exclusion.lines) process.stderr.write(l + '\n'); return exclusion.code === 'REVIEW_DIFF_UNREADABLE' ? EXIT.fail : EXIT.refused; }
  if (exclusion.state === 'fallback') process.stderr.write(`gstack-review-plan: ${fallbackLine(exclusion, base)}\n`);
  const active = exclusion.state === 'active' ? exclusion : null;
  const kept = <T,>(rec: Record<string, T>) => (active ? Object.fromEntries(Object.entries(rec).filter(([p]) => !active.excluded.has(p))) : rec);
  const exclusionInput = active ? { excluded: active.excluded, exclusion: { specs: active.specs, keep: active.keep } } : {};
  const force = flag('--force') === 'all' ? 'all' as const : list('--force');
  const tiersSetting = runScriptSync(path.join(binDir, 'gstack-config'), ['get', 'review_effort_tiers'], { encoding: 'utf8', timeout: 15_000 });
  const auditEffort = has('--no-tiers') || (tiersSetting.stdout ?? '').trim() === 'off' ? 'host' : 'light';
  const { added, diffLines, paths, deleted, stampOnly, perPath, registry } = collected;
  let fixRange: { base: string; runtime_lines: number | null; error?: string; touched_gate?: true; ruled?: string[] } | undefined;
  let routed: ReturnType<typeof ruledEdits> | null = null;
  let ruledAll = false;
  let stamps = new Set<string>();
  let own: string | null = null;
  if (rangeBase) {
    const unread = (error: string) => ({ base: rangeBase, runtime_lines: null, error });
    const resolved = git(['rev-parse', '--verify', '--quiet', `${rangeBase}^{commit}`])?.trim();
    if (!resolved) fixRange = unread('not a commit in this repository');
    else if (git(['merge-base', '--is-ancestor', resolved, 'HEAD']) === null) fixRange = unread('not an ancestor of HEAD');
    else if (git(['diff', '--quiet', 'HEAD', '--']) === null || collected.untracked.length) fixRange = unread('uncommitted or untracked edits: commit the fixes first');
    else if (!(own = ownChangeSince(root, ref, resolved, 'HEAD'))) fixRange = unread('git could not build the PR\'s own change since the range base');
    else {
      const commit = collectCommit(root, resolved, own);
      const range = classifyDiff({ ...commit, registry, scope: scopeOf([resolved, '--head', own]), gateTagged: gateTagsOf(['--commit', own]), ...riskPaths, ...(active ? { excluded: active.excluded } : {}) });
      const edits = readRuledNotes(root).filter(n => n.finding.startsWith('edit:'));
      stamps = edits.length ? new Set(stampPathsSince(root, ref, resolved, own, head)) : stamps;
      const toRule = commit.paths.filter(p => !stamps.has(p));
      routed = edits.length && toRule.length && !range.errors.length ? ruledEdits(root, toRule, head, edits) : null;
      const tagsBeyond = (ruled: ReadonlyMap<string, unknown>) => { const g = runGateDiff(['--commit', own!, '--format', 'jsonl']);
        return g.status !== 0 || (g.stdout ?? '').split('\n').slice(1).some(l => { try { const h = JSON.parse(l) as { path?: string; tags?: unknown[] }; return !!h.tags?.length && !ruled.has(h.path ?? '') && !stamps.has(h.path ?? ''); } catch { return false; } }); };
      ruledAll = !!routed && routed.ruled.size === toRule.length && !tagsBeyond(routed.ruled);
      fixRange = range.errors.length ? unread([...range.errors.slice(0, 5).map(e => `${e.code} ${e.input}`), ...(range.errors.length > 5 ? [`+${range.errors.length - 5} more`] : [])].join('; '))
        : !commit.paths.length ? unread('the fix range is empty: commit the fix after the range base (a base merge alone is not the PR\'s own change)')
        : ruledAll ? { base: rangeBase, runtime_lines: 0, ruled: [...routed!.ruled.keys()].sort() }
        : { base: rangeBase, runtime_lines: range.runtimeLines, ...(range.class === 'gate' ? { touched_gate: true as const } : {}) };
    }
  }
  const targeted = targetedClasses({ ...collected, scope, gateTagged, ...(active ? { excluded: active.excluded } : {}) });
  const patch = collected.mergeBase ? targetedPatchId(process.cwd(), collected.mergeBase) : 'none';
  const brief = targetedBriefSha();
  const ran = !['uncommitted', 'none'].includes(patch) && flag('--targeted-ran') === patch;
  const postReview = has('--post-review');
  const fixedPost = !ruledAll && postReview && pass > 0;
  const plan = planReview({
    ...collected, ...exclusionInput, ...riskPaths, declared: declared as RiskClass[], shape: { panel: review.panel, readerModel: review.reader_model, platform: review.platform, head, platformReview: platform?.ok ? platform.review : null }, scope, gateTagged, targeted: { classes: targeted.classes, ran }, numbers: scanNumbers(kept(added)), force, gated: list('--gated'), floor, tiers: auditEffort !== 'host',
    criticalFound: has('--critical-found'), adversarialRan: has('--adversarial-ran'), reviewedNumbers: flag('--reviewed-numbers'),
    history: { priorRounds, priorFull, fullPasses: pass, last, fixedBlocking: has('--fixed-blocking'), fixedBelow: !ruledAll && (has('--fixed-below') || fixedPost), blockingOpen: has('--blocking-open'), touchedGate: !ruledAll && (has('--touched-gate') || !!fixRange?.touched_gate || fixedPost), pass1Depth, rangeRuntimeLines: fixRange?.runtime_lines, postReview },
  });
  if (ruledAll) plan.next.reason = `every edit since --range-base is ruled a note (RULED_EDIT), so the range plans as no fix (docs/ship-policy.md#ruled-edits): ${plan.next.reason}`;
  if (fixedPost) plan.next.reason = `edits after the review bound (Step 16 stage 2.1) plan as a fix to a gate-class path, never a note: ${plan.next.reason}`;
  if (postReview && plan.next.step === 'stop') {
    const status = rangeBase ? git(['diff', '-z', '--name-status', '--no-renames', rangeBase, own ?? head])?.split('\0').filter(Boolean) : undefined;
    const pairs = status ? Array.from({ length: status.length >> 1 }, (_, i) => [status[2 * i]!, status[2 * i + 1]!] as const) : undefined;
    const changed = pairs?.map(([, p]) => p);
    const spaced = changed?.filter(p => /\s/.test(p)) ?? [];
    const rulable = changed?.filter(p => !spaced.includes(p) && !routed?.ruled.has(p) && !stamps.has(p));
    const quote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
    const rule = (finding: string) => `gstack-approvals rule --finding ${finding} --head ${head} --reason '<why it ships as a note>' --by '<the owner>' --words '<their exact words>' --owner-ref <thread code>:<message id>`;
    plan.next.reason += `; if the owner rules instead that the edit ships as a disclosed note, record that ruling once per changed path, a deleted path too and both paths of a rename (each path shell-quoted; the owner-ref is the relay this open /gstack-ship run needs): ${rulable?.length ? rulable.map(p => rule(quote(`edit:${p}`))).join(' && ') : rule("'edit:<path>'")}, then rerun finish, which routes each ruled path at the ruled bytes as RULED_EDIT${spaced.length ? `; ${spaced.map(quote).join(', ')} cannot be ruled (a finding holds no whitespace), so a change there keeps the fix and runs /gstack-ship again` : ''}`;
  }
  const ranArg = flag('--targeted-ran');
  const delta = plan.next.step !== 'done' || !targeted.classes.length || ran ? null
    : rangeBase && ranArg ? targetedDelta(root, ref, rangeBase, ranArg) : null;
  const ruledCarry = ruledAll && plan.next.step === 'done' && targeted.classes.length > 0 && !ran && !!rangeBase && !!ranArg && ruledCarries(root, ref, rangeBase, ranArg, active?.excluded);
  const ruledRead = ruledAll && plan.next.step === 'done' && targeted.classes.length > 0 && !ran && !(delta?.state === 'skip' && delta.carried) && !ruledCarry;
  if (ruledCarry) plan.skipped.push(`targeted-only read (every edit since --range-base is ruled a note and none carries a targeted class, so the record read at ${rangeBase!.slice(0, 12)} carries with the rulings; gstack-ship-receipt write records them)`);
  if (delta?.state === 'dispatch' || ruledRead) {
    const why = delta?.state === 'dispatch' ? `the only change since is docs whose claim the record cannot carry (${delta.paths.join(', ')}) after the targeted read at ${delta.range_base.slice(0, 12)}`
      : 'every edit since --range-base is ruled a note, but no targeted record covers the ruled bytes';
    plan.next = { step: 'targeted', reason: `the loop is done and ${why}: one targeted reader reads HEAD for ${classList(targeted.classes)}; it is not a review round` };
    plan.dispatches.push({ role: 'targeted', name: 'targeted', effort: ROLE_EFFORT.targeted, exclude: active ? [...active.specs] : [], classes: [...targeted.classes], ...(active?.keep.length ? { keep: [...active.keep] } : {}) });
  } else if (delta) plan.skipped.push(`targeted-only read (${delta.reason})`);
  if (last === 'full' && plan.next.step === 'done' && fixRange && !ruledAll && fixRange.runtime_lines !== null && !ran && !(delta?.state === 'skip' && delta.carried) && !postReview && !['--fixed-blocking', '--fixed-below', '--blocking-open', '--touched-gate'].some(has)) {
    process.stderr.write(`${gateOutcomeLine('gstack-review-plan', 'review_required_no_readers', `--pass ${pass} --last ${last} names no fix, but the PR's own change since --range-base ${fixRange.base.slice(0, 12)} has ${fixRange.runtime_lines} runtime line${fixRange.runtime_lines === 1 ? '' : 's'}`)} (review_required_no_readers)\n`);
    return EXIT.refused;
  }
  const targetedDeltaOut = delta?.state === 'dispatch' ? { range_base: delta.range_base, paths: delta.paths, classes: targeted.classes } : null;
  const selection = policySelection(active && { state: 'active', specs: active.specs, keep: active.keep, excerpt: active.excerpt }, readers);
  plan.dispatches.forEach((d, i) => { plan.dispatches[i] = selectFor(d, selection); });
  const gateScan = { tagged: gateTagged, head };
  if (has('--json')) {
    const { runtimeLines, stepDepth, depthReasons, ...rest } = plan;
    process.stdout.write(JSON.stringify({ ...rest, review_policy: review, platform_review: platform ? (platform.ok ? platform.review : { none: platform.reason }) : null, readers, targeted: { ...targeted, brief, targeted_patch_id: patch }, step_depth: stepDepth, runtime_lines: runtimeLines, depth_reasons: depthReasons, depth_floor: floor ?? null, gate_scan: gateScan, fix_range: fixRange ?? null, targeted_delta: targetedDeltaOut, registry: { sha: registry.sha, outputs: registry.outputs }, per_path: perPath, diff_lines: diffLines, base: collected.base, pass, audit_effort: auditEffort, scope, gate_tagged: gateTagged, paths, deleted, stamp_only: stampOnly, consumed: collected.consumed, drawings: collected.drawings, executables: collected.executables,
      ...(exclusion.state === 'head-only' || exclusion.state === 'fallback' ? { review_exclude: exclusion } : active ? { review_exclude: { state: 'active', ...active.record, specs: active.specs, keep: active.keep, excerpt: active.excerpt, kept_files: active.kept, content: active.content, references: active.references, ...(active.vendored ? { vendored_selection: active.vendored } : {}) } } : {}) }) + '\n');
    return EXIT.ok;
  }
  const out = [`REVIEW_CLASS: ${plan.class} (${plan.reasons.slice(0, 3).join('; ') || 'no signals'})`, reviewDepthLine(plan), `GATE_SCAN: ${gateTagged === null ? 'unavailable' : `tagged=${gateTagged}`} head=${head}`, `REVIEW_BASE: ${ref} ${baseSha.slice(0, 12)}`,
    `TARGETED: classes=${classList(targeted.classes)} rules=${targeted.rules} brief=${brief} targeted_patch_id=${patch}${targeted.reasons.length ? ` reasons=${targeted.reasons.join('; ')}` : ''}`];
  out.push(...excludeLines(exclusion, base), readersLine(readers));
  if (collected.consumed === 'all' && collected.mergeBase) out.push(`CONSUMER_SCAN: skipped: more than ${consumerScanCap()} data files changed, so each counts as code for review depth; fix: set GSTACK_REVIEW_CONSUMER_SCAN_CAP above that count, or move the data into its own PR (review_exclude_paths still leaves matched files out of the readers' diffs)`);
  out.push(`REVIEW_MODE: ${plan.mode} panel=${review.panel} reader_model=${review.reader_model} platform=${review.platform}`);
  if (declared.length) out.push(`RISK_DECLARED: classes=${plan.declared.join(',')} detected=${plan.detected.join(',') || 'none'}`);
  if (platform) out.push(platform.ok ? `PLATFORM_REVIEW: ${platform.review.id} reviewer=${platform.review.reviewer} head=${platform.review.head}` : `PLATFORM_REVIEW: none (${platform.reason})`);
  if (fixRange) out.push(`FIX_RANGE: ${fixRange.runtime_lines === null ? `unread (${fixRange.error})` : `runtime_lines=${fixRange.runtime_lines}`} base=${fixRange.base}${fixRange.ruled ? ` ruled=${fixRange.ruled.length}` : ''}`);
  for (const [p, n] of routed?.ruled ?? []) out.push(ruledEditLine(p, n));
  for (const x of routed?.refused ?? []) out.push(`RULED_EDIT_REFUSED: ${x}`);
  if (targetedDeltaOut) out.push(`TARGETED_DELTA: range_base=${targetedDeltaOut.range_base} paths=${targetedDeltaOut.paths.join(',')} classes=${classList(targetedDeltaOut.classes)}`);
  const another = plan.next.step === 'full' || plan.next.step === 'scoped';
  out.push(reviewPlanLine(plan, pass + (another ? 1 : 0), priorRounds), `NEXT: ${plan.next.step} (${plan.next.reason})`);
  out.push(`PASS_COUNT: finished=${pass}${another ? ` next_pass=${pass + 1} (after pass ${pass + 1} finishes, plan again with --pass ${pass + 1} --last full)` : ''}`);
  for (const e of plan.errors) out.push(`DEPTH_ERROR: ${e.code} input=${e.input} detail=${e.detail}; fix: ${e.repair}${e.result ? ` (${e.result})` : ''}`);
  for (const d of plan.dispatches) {
    const key = d.name.split(' ')[0];
    out.push(`DISPATCH: ${d.role} ${d.name} effort=${d.effort}${d.model ? ` model=${d.model}` : ''}${d.checklists ? ` checklists=${d.checklists.join(',')}` : ''}${d.classes ? ` classes=${d.classes.join(',')}` : ''}${d.reason ? ` reason=${d.reason}` : ''}`, `DIFF_CMD: ${key} ${diffCommand(d)}`);
    if (!d.exclude.length) out.push(`DIFF_EXCLUDE: ${key} none`);
    const keepCmd = keepCommand({ ...d, keep: d.keep?.filter(k => !d.excerpt?.includes(k)) });
    if (keepCmd) out.push(`DIFF_KEEP: ${key} ${keepCmd}`);
  }
  for (const s of plan.skipped) out.push(`SKIP: ${s}`);
  out.push(`AUDIT_EFFORT: ${auditEffort} (coverage, plan-completion and docs audits, decision-trail reviewers, watchers; reviewers above run at their effort=)`);
  process.stdout.write(out.join('\n') + '\n');
  return EXIT.ok;
}

/**
 * One plan's bound (GST-1855): the plan runs in a child under reviewPlanTimeoutMs, and a child that does not finish prints
 * REVIEW_PLAN_STOPPED and exits 1 with no plan, so /ship stops on a named line instead of waiting for minutes. A caller that
 * bounds the run itself (gstack-review-dispatch pass) sets GSTACK_REVIEW_PLAN_BOUNDED=1 and the plan runs in place.
 */
function bounded(): number {
  if (process.env.GSTACK_REVIEW_PLAN_BOUNDED === '1') return main();
  const timeoutMs = reviewPlanTimeoutMs();
  const args = process.argv.slice(2);
  const r = runScriptSync(Bun.fileURLToPath(import.meta.url), args, { stdio: 'inherit', timeout: timeoutMs, env: { ...process.env, GSTACK_REVIEW_PLAN_BOUNDED: '1' } });
  if (r.status !== null) return r.status;
  const reason = (r.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT' ? 'timeout' : r.signal ? 'signal' : 'spawn';
  process.stderr.write(`${resultLine('gstack-review-plan', 'REVIEW_PLAN_STOPPED', `step="gstack-review-plan ${args.join(' ')}" reason=${reason} timeout_ms=${timeoutMs} signal=${r.signal ?? 'none'}`)}\n`);
  return EXIT.fail;
}

process.exitCode = bounded();