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
Make /ship's preflight honor the repo's CI rerun time limit and name the install command in a fresh worktree (GST-3360) (#4608)
Garry Tandf4d0bd0b159
diff --git a/changelog.d/ship-preflight-ci-rerun-limit-and-install-check.md b/changelog.d/ship-preflight-ci-rerun-limit-and-install-check.mdnew file mode 100644index 000000000..a3aa697d5--- /dev/null+++ b/changelog.d/ship-preflight-ci-rerun-limit-and-install-check.md@@ -0,0 +1 @@+- **/ship's preflight now honors your repository's time limit for rerunning CI-skipped tests, and tells you when a fresh worktree needs its packages installed.** When preflight reuses a CI run and reruns the test files CI skipped, it now stops that rerun at the base branch's `ci_record_timeout_s` (it used 600 s even when the repository set 900 s; accept already honored the setting), and prints the limit it used as `CI_RECORD_TIMEOUT:`. And when the checkout's `package.json` declares packages but there is no `node_modules`, as in a fresh worktree for a second /ship run on the same machine, preflight's test step stops with `STOP: DEPS_MISSING` and the exact install command for the lockfile (for example `bun install --frozen-lockfile`) instead of running checks that can't find the repository's own tools. An installed Yarn Plug'n'Play checkout, which has no `node_modules`, is not stopped. (GST-3360)diff --git a/docs/pregate.md b/docs/pregate.mdindex dafdea5a6..3b5adfa46 100644--- a/docs/pregate.md+++ b/docs/pregate.md@@ -1408,7 +1408,8 @@ them (`ci_carried=<lane>:<run>/<attempt>`). A run whose `tree.json` listsfrom its job log adds `tree_source: "job-log"` to its entries and`tree_source=job-log` after them ([tree_log_step](#tree-log-step)). Each `record-ci` gets the basepolicy's [`ci_record_timeout_s`](ship-policy.md#ci-record-timeout) (600 s by-default, 3600 s at most), and accept prints it as `CI_RECORD_TIMEOUT:`.+default, 3600 s at most), in preflight's Step 5 and finish as well as in accept, and accept and+preflight print it as `CI_RECORD_TIMEOUT:`.<a id="record-ci-reuse"></a>**record-ci reuses its own row at the same tree (GST-1795).** Step 5'scarry and accept both call `record-ci`, so at an unchanged pushed tree thediff --git a/docs/ship-policy.md b/docs/ship-policy.mdindex e94bf19b2..059694176 100644--- a/docs/ship-policy.md+++ b/docs/ship-policy.md@@ -88,7 +88,7 @@ branch that changes the policy.| `mechanical_retake` | `[{ path, template, fields, regen }]` | `[]` | A version or rules constant a branch may have to retake after a base merge, next to `bookkeeping`'s bounded kind: `path` is one literal file, `template` the whole line with one `{n}` (`const RULE_NUMBERS := {n}`), `fields` the `{ glob, field }` fixture fields that carry the same value, and `regen` the [`.gstack/generated.json`](pregate.md#generated) entry ids whose command regenerates its goldens. A post-review edit finish proves to be only that retake routes as `mechanical=`, with no reader and no review round; see [mechanical retakes](#mechanical-retake). At most 8 constants and 16 fields or ids each; no glob, `..`, `.gstack/` or `.github/` path. Read from the base revision only. Needs `min_gstack_version`. || `test_code` | glob list | `[]` | Root-anchored globs of test code the built-in test names miss, never under `.gstack/` or `.github/`, and never matching a file there (`["tests/**/*.gd"]` for GDScript checks). A matching file changed after review routes as test code, one scoped reader of its test hunks, instead of behavior, beside the built-in globs; shared `helpers/` and `fixtures/` files stay behavior. See [test code and Godot UID sidecars](#test-code). Read from the base revision only. Needs `min_gstack_version`. || `plan_record` | `off` \| `warn` \| `require` | `off` | <a id="plan-record"></a>Whether `gstack-ship-queue ready` and `land` (direct, stamp and train land) and `/ship`'s `gstack-ship-release finish --plan "<line>"` check the PR body's `Plan:` line (GST-1751). The line is the brief's (`Plan: approved: <run id or row id>`, `Plan: exempt: <reason>` or `Plan: required`), written under `## Approvals` by `gstack-approvals render --plan`. `ready` resolves it with lib/plan-record.ts against every branch's approval rows on the lane machine: a run id needs the newest gate revision's plan approval answered `approved`, in the owner's words, with no decision of that revision left unanswered; a row id needs an approved row that is not a ruling or grant, and a row from an autoplan run stands for that run's gate the same way; a broken or unreadable store refuses (`PLAN_STORE_UNAVAILABLE`) and never throws, and under `off` changes nothing; an exemption must be one crew/docs/captain.md lists or `crew:<rule>`; a diff of changelog fragments only needs no line. `finish` resolves the brief's line the same way before its first stage. `ready` (train ready included) prints `PLAN:` and writes the resolved record into the READY note; `land` checks that the note carries the PR body's current line and never reads the store. `warn` prints and continues; `require` refuses (`PLAN_RECORD_MISSING`, `PLAN_UNRESOLVED`, `PLAN_NOT_APPROVED`, `PLAN_EXEMPT_UNKNOWN`, `PLAN_STORE_UNAVAILABLE`, `QUEUE_PLAN_MISMATCH`). When this key is `off` or absent, the mode comes from `GSTACK_PLAN_RECORD` (a crew's opt-in), then `plan_record` in `<state root>/config.yaml` (`gstack-config set plan_record off|warn|require`: the untracked source for a repo that commits no `.gstack/`; a typo is rejected, and the `PLAN:` line names the file), then `warn` in a Capy session (`GSTACK_CAPY=1`), then `off`; a machine's key never loosens a tracked `warn` or `require`. A repo with no tracked policy gets the check at `ready` and `finish` only: ready writes no READY note there and `land` refuses before its plan step. Capy's state root does not survive a fresh machine, so a Capy crew that wants more than `warn` sets `GSTACK_PLAN_RECORD` in its project env. On a public or unknown-visibility repository `render --plan` writes `Plan: approved (record r-<12 hex>)`, an opaque id of the approval row (opaque, not secret), so no run id, row id or path reaches the PR body or the READY note pushed to origin; `ready` resolves it by hashing every row id it reads and then applies the row-id rules, and render refuses with no output when an approved line does not resolve. gstack never infers a feature from the diff, title or changelog. Read from the base revision only. Needs `min_gstack_version`. |-| `ci_record_timeout_s` | integer seconds, at least 60 | `600` | <a id="ci-record-timeout"></a>How long `gstack-ship-release accept` lets one `gstack-evidence record-ci` run before it stops that lane. A value over 3600 is clamped to 3600. accept prints the bound it used as `CI_RECORD_TIMEOUT: <n>s (default)`, `(origin/<base> ci_record_timeout_s)` or `(… <value> is over the 3600s ceiling)`. Raise it when record-ci runs long, for example when it reruns a per_file remainder of CI-skipped files here (harness-evals #271 needed about 745 s). Read from the base revision only, so a branch can't raise its own bound. Needs `min_gstack_version`. |+| `ci_record_timeout_s` | integer seconds, at least 60 | `600` | <a id="ci-record-timeout"></a>How long one `gstack-evidence record-ci` may run before it stops that lane, in `gstack-ship-release accept` and finish and in `gstack-ship-preflight`'s Step 5. A value over 3600 is clamped to 3600. accept and preflight print the bound they used as `CI_RECORD_TIMEOUT: <n>s (default)`, `(origin/<base> ci_record_timeout_s)` or `(… <value> is over the 3600s ceiling)`. Raise it when record-ci runs long, for example when it reruns a per_file remainder of CI-skipped files here (harness-evals #271 needed about 745 s). Read from the base revision only, so a branch can't raise its own bound. Needs `min_gstack_version`. || `base_red` | `{ setup, select, timeout_sec }` or `null` | `null` | How `/ship` Step 5 proves a failure is the base branch's own before pausing on it; see [base_red](#base-red). Read from the base revision only. Needs `min_gstack_version`. || `changelog_fragments` | `{ dir, required_checks? }` or `null` | `null` | PRs carry unversioned [CHANGELOG fragments](#changelog-fragments) in `dir` (one flat, repo-relative directory, no `..`) and the merge step ([`land`](#land)) assigns the version (under `merge: direct`, the [release PR](#release-stamp) does). `required_checks` (up to 50 distinct names) are the checks [`train land`](#stamped-trains-under-changelog_fragments-train-land) requires present and green on a stamp commit. `null` keeps `[Unreleased]` sections and per-PR stamps. Needs `min_gstack_version`. |diff --git a/lib/ship-bin-common.ts b/lib/ship-bin-common.tsindex 8dca0ba43..d659e45f9 100644--- a/lib/ship-bin-common.ts+++ b/lib/ship-bin-common.ts@@ -202,7 +202,7 @@ export function mappedLanes(cwd: string, base: string, list: { label: string; co* and records the CI-sourced ledger row; or, when the lane's inventory refuses this tree, the cleared remote gate for this exact* tree stands in (`remoteGate`, lib/remote-gate-stand-in.ts, GST-1688); or why neither held (`carryNone`), so the caller runs it.*/-export function carryLane(cwd: string, base: string, l: { label: string; command: string }, timeoutS = DEFAULT_POLICY.ci_record_timeout_s): LaneResult {+export function carryLane(cwd: string, base: string, l: { label: string; command: string }, timeoutS = recordCiTimeout(shipPolicy(cwd, base), base).seconds): LaneResult {const rec = bin(cwd, 'gstack-evidence', ['record-ci', '--label', l.label, '--base', base, '--remote-gate-stands-in', '--', l.command], timeoutS * 1000);const got = recordCiResult(rec.stderr);if (rec.status === 0 && got.remoteGate) return { label: l.label, exit: 0, testsRan: got.tests!, log: '-', remoteGate: got.remoteGate, standIn: got.standIn ?? 'not carried' };@@ -210,7 +210,7 @@ export function carryLane(cwd: string, base: string, l: { label: string; commandreturn { label: l.label, exit: null, testsRan: 'unknown', log: '-', carryNone: got.none ?? `record_failed: ${firstLine(rec.stderr)}`, ...(got.diagnosis ? { diagnosis: got.diagnosis } : {}) };}-/** accept's bound on one record-ci (GST-1606): the base policy's `ci_record_timeout_s`, 600 s by default, clamped to 3600 s. */+/** The bound on one record-ci, in accept, finish and preflight alike (GST-1606, GST-3360): the base policy's `ci_record_timeout_s`, 600 s by default, clamped to 3600 s. */export function recordCiTimeout(policy: Record<string, any> | null, base: string): { seconds: number; line: string } {const set = policy?.ci_record_timeout_s;if (typeof set !== 'number' || set === DEFAULT_POLICY.ci_record_timeout_s) return { seconds: DEFAULT_POLICY.ci_record_timeout_s, line: `CI_RECORD_TIMEOUT: ${DEFAULT_POLICY.ci_record_timeout_s}s (default)` };@@ -227,15 +227,16 @@ export function recordCiTimeout(policy: Record<string, any> | null, base: string* per_file remainder or exception preflight here; only the refused lanes go to record-ci, for a cleared remote gate. Every other* lane runs through gstack-evidence run --reuse (a pass at this tree, command and runtime is reused; `reuse: false` forces a run).*/-export async function runLanes(cwd: string, list: { label: string; command: string }[], concurrency = Infinity, opts: { base?: string; reuse?: boolean; hold?: boolean } = {}): Promise<LaneResult[]> {+export async function runLanes(cwd: string, list: { label: string; command: string }[], concurrency = Infinity, opts: { base?: string; reuse?: boolean; hold?: boolean; recordCiTimeoutS?: number } = {}): Promise<LaneResult[]> {const out: LaneResult[] = [];const mapped = opts.base ? mappedLanes(cwd, opts.base, list) : new Map<string, ShipLaneMapping>();+ const bound = mapped.size ? opts.recordCiTimeoutS ?? recordCiTimeout(shipPolicy(cwd, opts.base!), opts.base!).seconds : 0;const refused = list.map(l => !!opts.hold && mapped.has(l.label) && bin(cwd, 'gstack-ci-carry', ['find', '--base', opts.base!, '--command', l.command, '--allow-repo-commands']).status !== 0);- const carries = list.map((l, i) => (refused[i] ? carryLane(cwd, opts.base!, l) : null));+ const carries = list.map((l, i) => (refused[i] ? carryLane(cwd, opts.base!, l, bound) : null));const done = (c: LaneResult | null) => !!(c?.carried || c?.remoteGate);const held = () => list.map((l, i) => { const c = carries[i]; return c && done(c) ? c : { ...(c ?? { label: l.label, exit: null, testsRan: 'unknown', log: '-' }), held: true as const }; });if (opts.hold && carries.some(c => c && !done(c))) return held();- for (const [i, l] of list.entries()) if (!carries[i] && mapped.has(l.label)) carries[i] = carryLane(cwd, opts.base!, l);+ for (const [i, l] of list.entries()) if (!carries[i] && mapped.has(l.label)) carries[i] = carryLane(cwd, opts.base!, l, bound);if (opts.hold && carries.some(c => c && !done(c))) return held();let next = 0;const worker = async () => {diff --git a/lib/ship-policy.ts b/lib/ship-policy.tsindex 325cc3074..ba70f9049 100644--- a/lib/ship-policy.ts+++ b/lib/ship-policy.ts@@ -240,7 +240,7 @@ export const POLICY_EXPLANATIONS: Record<PolicyKey, string> = {bookkeeping: 'Root-anchored globs of bookkeeping tables, each ending in .tsv, .csv or .txt and never under .gstack/ or .github/, for example ["scripts/*-baseline.tsv"]. An edit of at most 20 lines to a matching file after review binds, first touched or not, takes /ship finish\'s scoped reader instead of Steps 5–11.5; the reader still reads every changed row. Read from the base branch only. Empty (default) declares none.',mechanical_retake: MECHANICAL_EXPLANATION,test_code: 'Root-anchored globs of test code the built-in test names miss, never under .gstack/ or .github/, for example ["tests/**/*.gd"] for GDScript checks. /ship finish routes a matching file changed after review as test code (one scoped reader of its test hunks) instead of behavior, beside the built-in globs; shared helpers and fixtures stay behavior. Read from the base branch only. Empty (default) declares none.',- ci_record_timeout_s: 'Seconds `gstack-ship-release accept` lets one `gstack-evidence record-ci` run before it stops that lane, an integer of at least 60 (default 600). A value over 3600 is clamped to 3600, and accept prints the bound it used (`CI_RECORD_TIMEOUT:`). Raise it when record-ci runs long, for example a per_file remainder of CI-skipped files. Read from the base branch only.',+ ci_record_timeout_s: 'Seconds one `gstack-evidence record-ci` may run before it stops that lane (gstack-ship-release accept and finish, gstack-ship-preflight Step 5), an integer of at least 60 (default 600). A value over 3600 is clamped to 3600, and accept prints the bound it used (`CI_RECORD_TIMEOUT:`). Raise it when record-ci runs long, for example a per_file remainder of CI-skipped files. Read from the base branch only.',plan_record: 'off (default) | warn | require. Whether `gstack-ship-queue ready` and `land` check the PR body\'s `Plan:` line (approved: <run id or row id> | exempt: <reason>) against the approval store (docs/ship-policy.md#plan-record). warn prints the PLAN: line and continues; require refuses a missing, unresolved or agent-approved plan. This key is read from the base branch only; with it off, GSTACK_PLAN_RECORD, then plan_record in <state root>/config.yaml (gstack-config set plan_record warn, for a repo that commits no .gstack/), then warn in a Capy session decide. On a public repo render --plan writes Plan: approved (record r-<id>) instead of the run id.',docs_only: '{ allow, deny?, tests? } or null, read from the base revision only (docs/pregate.md#repo-docs-paths). allow (1 to 16) adds human-docs globs to the docs-only allowlist (README.md, docs/**.md, changelog.d/*.md): each ends in .md, starts with a literal directory or file name and passes through no hidden, code, test or agent directory ("wiki/board/**.md"). deny (up to 64 globs) removes paths, built-in ones included. tests (up to 16 test file paths) are the repository\'s checks for those directories: the docs lane runs them, and a non-docs file that names an allowed directory ("wiki/", \'wiki\') refuses the change unless it is one of them, names one, or one names it. The built-in deny list (agent instructions, templates, prompts, preferences, tool configuration, pinned results, preregistrations, generated outputs) always wins, a path a script or test names stays pinned, and a pull request that edits this file is never docs-only. An unknown key under docs_only is a warning, and the classifier then ignores allow. Needs min_gstack_version.',merge: 'train (default) | direct. direct: the Captain lands each READY PR at its own green head with `gstack-ship-queue land --pr <n> --pin <sha>` (no train, no stamp commit; the PR leaves VERSION, the manifest version and the CHANGELOG at the base and the release stamps them), and train build refuses. train: merge trains as before (docs/ship-policy.md#land-direct).',diff --git a/lib/ship-preflight.ts b/lib/ship-preflight.tsindex d1cf0eb00..4d66cf861 100644--- a/lib/ship-preflight.ts+++ b/lib/ship-preflight.ts@@ -17,7 +17,7 @@ import { classifyDiff } from './review-depth';import { wtreeFingerprint } from './script-invocation';import { audit } from './ship-audit';import { withGateLock } from './gate-dispositions';-import { bin, carryNoneLines, firstLine, flagReader, gh, git, hostedOrigin, laneConcurrency, laneLine, lanes, mappedLanes, Report, runLanes, shipPolicy, shipRunMarker, short } from './ship-bin-common';+import { bin, carryNoneLines, firstLine, flagReader, gh, git, hostedOrigin, laneConcurrency, laneLine, lanes, mappedLanes, recordCiTimeout, Report, runLanes, shipPolicy, shipRunMarker, short } from './ship-bin-common';export const PREFLIGHT_HELP = `gstack-ship-preflight — /ship Steps 1-3 and Step 5's pregate and lanes in one call (ship/SKILL.md)@@ -45,7 +45,7 @@ export const PREFLIGHT_HELP = `gstack-ship-preflight — /ship Steps 1-3 and Ste(CONTEXT, TODOS, COVERAGE_MAP, Coverage, PLAN_*, READER: coverage=needed|none plan=needed|none)Prints at most 30 lines: BRANCH, STATUS, DIFF, PR/CARRY, APPLE, SCOPE, MERGE, DISTRIBUTION, POLICY,-RUNTIME_LINES, PREGATE (with up to three PREGATE_DETAIL lines when it does not pass), LANES, one LANE line per lane+RUNTIME_LINES, PREGATE (with up to three PREGATE_DETAIL lines when it does not pass), LANES, CI_RECORD_TIMEOUT (when a lane is mapped), one LANE line per lane(a lane the base maps in .gstack/pregate.json ship_lanes_from is carried from a verified CI run at this exact clean tree:LANE: <label> carried run=<id>/<attempt> tests_ran=<n>, else CI_CARRY: none (<reason>) and STOP: SHIP_LANE_NOT_CARRIED, or with--run-uncarried-here it runs here; any other lane that@@ -202,7 +202,27 @@ function merge(cwd: string, base: string, r: Report): boolean {return true;}+/**+ * GST-3360: Step 5's pregate and lanes run the repository's own tools, which a fresh worktree lacks until its packages are+ * installed (tsc exits 127, bun test cannot resolve imports). The install command for the checkout's lockfile, or null when+ * package.json declares no packages, node_modules exists, or Yarn Plug'n'Play's .pnp.cjs / .pnp.loader.mjs (Yarn Classic: .pnp.js)+ * marks an install that never creates node_modules. Preflight names the command and never runs it.+ */+function depsInstall(root: string): string | null {+ let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };+ try { pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); } catch { return null; }+ const has = (f: string) => fs.existsSync(path.join(root, f));+ if (!Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }).length || has('node_modules') || has('.pnp.cjs') || has('.pnp.loader.mjs') || has('.pnp.js')) return null;+ return has('bun.lock') || has('bun.lockb') ? 'bun install --frozen-lockfile' : has('pnpm-lock.yaml') ? 'pnpm install --frozen-lockfile' : has('yarn.lock') ? 'yarn install --frozen-lockfile' : has('package-lock.json') || has('npm-shrinkwrap.json') ? 'npm ci' : 'bun install';+}+async function tests(cwd: string, base: string, list: { label: string; command: string }[], policyFrom: string, timeout: string | undefined, step: { seconds: number; source: string }, run: { concurrency: number; line: string; hold: boolean; testsOnly: boolean }, r: Report): Promise<void> {+ const root = git(cwd, ['rev-parse', '--show-toplevel']).stdout.trim() || cwd;+ const install = depsInstall(root);+ if (install) {+ r.stop(`DEPS_MISSING: ${root}/package.json declares packages but there is no node_modules (a fresh worktree), so Step 5's pregate and lanes cannot run: cd '${root.replace(/'/g, `'\\''`)}' && ${install}, then ${run.testsOnly ? 'rerun this command' : `rerun with --tests-only --base ${base} and the same --lane flags`}`);+ return;+ }const pg = bin(cwd, 'gstack-pregate', ['--allow-repo-commands', '--base', base, '--policy-from', policyFrom, ...(timeout ? ['--timeout', timeout] : [])], step.seconds * 1000);if (pg.timedOut) {r.add(`PREGATE: time limit hit (Step 5's whole pregate ran past its ${step.seconds} s budget, ${step.source}, and was stopped with exit ${pg.status ?? 'none'}; no verdict)`);@@ -219,7 +239,9 @@ async function tests(cwd: string, base: string, list: { label: string; command:}if (/uncleared/.test(verdict)) r.next('pregate requires-remote: gstack-pregate clear, or --remote --spend-cap <usd> under a user cap, before Step 18');r.add(run.line);- const ran = await runLanes(cwd, list, run.concurrency, { base, hold: run.hold });+ const recordCi = mappedLanes(cwd, base, list).size ? recordCiTimeout(shipPolicy(cwd, base), base) : undefined;+ if (recordCi) r.add(recordCi.line);+ const ran = await runLanes(cwd, list, run.concurrency, { base, hold: run.hold, recordCiTimeoutS: recordCi?.seconds });const results = ran.map(laneLine);for (const [i, l] of results.entries()) { for (const none of carryNoneLines(ran[i]!)) r.add(none); r.add(l.line); }const refused = ran.filter(l => l.held && l.carryNone);diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.tsindex f00510c1c..b2f5046d3 100644--- a/scripts/lib/windows-curation.ts+++ b/scripts/lib/windows-curation.ts@@ -416,6 +416,10 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }>file: 'test/ship-preflight-carry-stop.test.ts',reason: 'drives bin/gstack-ship-preflight, gstack-ci-carry, gstack-evidence and gstack-pregate (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-ci-carry.test.ts, which windows-latest fails at the first bin spawn (windows-scoped-shard, run 41607840098)',},+ {+ file: 'test/ship-preflight-carry-bound-and-deps.test.ts',+ reason: 'drives bin/gstack-ship-preflight, gstack-ship-release, gstack-ci-carry, gstack-evidence and gstack-pregate (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-preflight-carry-stop.test.ts, which windows-latest fails at the first bin spawn (windows-scoped-shard, run 41607840098)',+ },{file: 'test/ship-rereview-triggers.test.ts',reason: 'drives bin/gstack-ship-release, gstack-docs-candidate and gstack-wtree (shebangs) through test/helpers/ship-bin-fixture.ts like test/ship-release.test.ts; windows-latest fails every bin case at the first spawn (windows-free-shard 6, run 41193336209)',diff --git a/test/ship-preflight-carry-bound-and-deps.test.ts b/test/ship-preflight-carry-bound-and-deps.test.tsnew file mode 100644index 000000000..fcf5328cf--- /dev/null+++ b/test/ship-preflight-carry-bound-and-deps.test.ts@@ -0,0 +1,106 @@+/**+ * GST-3360, from several /ship runs on one machine (HARN-120): gstack-ship-preflight's Step 5 bounds each CI carry's+ * record-ci by the base policy's ci_record_timeout_s and says which bound it used, as accept does (harness-evals sets 900 s;+ * preflight kept the 600 s default), and it stops with the install command when a fresh worktree has no node_modules instead of+ * running a pregate and lanes that cannot resolve the repository's own tools.+ */+import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';+import * as fs from 'node:fs';+import * as path from 'node:path';+import { CI_RECORD_TIMEOUT_KEY_VERSION } from '../lib/ship-policy';+import { fakeGhScript, type FakeWorld } from './helpers/fake-gh-runs';+import { lineOf, PREFLIGHT, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture';++setDefaultTimeout(120_000);+const fixtures: ShipFx[] = [];+afterEach(() => { while (fixtures.length) fixtures.pop()!.cleanup(); });++const FREE = "printf x >> ../free-runs; printf ' 3 pass\\n 0 fail\\nRan 3 tests across 1 file. [1.00ms]\\n' >&2";+const HOST_OS = ({ darwin: 'macOS', win32: 'Windows' } as Record<string, string>)[process.platform] ?? 'Linux';+const PROFILE = { workflow: 'free.yml', events: ['pull_request', 'workflow_dispatch'], jobs: ['suite'], artifact: 'tested-tree', os: HOST_OS };+const TESTS = ['test/a.test.ts'];+const BASE = {+ '.gstack/pregate.json': JSON.stringify({ run_profiles: { 'ci/free': PROFILE }, ship_lanes_from: { [FREE]: { profiles: ['ci/free'], inventory: `printf '${TESTS.join('\\n')}\\n'` } }, dependencies: { 'src/a.ts': ['test/a.test.ts'], 'src/b.ts': ['test/a.test.ts'], 'test/**': [], '.gstack/ship-policy.json': [] } }, null, 2) + '\n',+ '.github/workflows/free.yml': 'name: Free\non: [pull_request, workflow_dispatch]\njobs:\n suite:\n runs-on: ubuntu-latest\n steps:\n - run: bun test\n',+ 'test/a.test.ts': "import { expect, test } from 'bun:test';\ntest('ok', () => expect(1).toBe(1));\n",+};+const freeRuns = (f: ShipFx) => { const p = path.join(f.root, 'free-runs'); return fs.existsSync(p) ? fs.readFileSync(p, 'utf8').length : 0; };++/** A fixture whose HEAD has one green workflow_dispatch run of free.yml at its pushed tree, so the mapped lane carries. */+function carried(base: Record<string, string>): ShipFx {+ const f = shipFixture({ ...BASE, ...base });+ fixtures.push(f);+ const sha = f.git('rev-parse', 'HEAD').stdout.trim();+ const tree = f.git('rev-parse', 'HEAD^{tree}').stdout.trim();+ const at = (m: number) => new Date(Date.now() - m * 60_000).toISOString();+ const run = { id: 7, run_attempt: 1, status: 'completed', conclusion: 'success', event: 'workflow_dispatch', head_sha: sha, path: '.github/workflows/free.yml', created_at: at(20), run_started_at: at(20), updated_at: at(5), repository: { full_name: 'fx/fx' }, head_repository: { full_name: 'fx/fx' } };+ const w: FakeWorld = { runs: [run] as FakeWorld['runs'], jobs: { 7: [{ name: 'suite', conclusion: 'success', completed_at: at(5) }] }, trees: { 7: { run_id: 7, run_attempt: 1, event: 'workflow_dispatch', sha, tree, files: TESTS, tests: 1, os: HOST_OS } } };+ fs.writeFileSync(path.join(f.root, 'world.json'), JSON.stringify(w));+ f.gh(fakeGhScript(path.join(f.root, 'world.json')));+ expect(f.run(RELEASE, ['push', '--branch', 'feat', '--early', '--base', 'main'], { GSTACK_SESSION_KIND: 'unattended' }).status).toBe(0);+ return f;+}+const testsOnly = (f: ShipFx) => f.run(PREFLIGHT, ['--tests-only', '--base', 'main', '--lane', `free=${FREE}`]);++describe('preflight Step 5: the record-ci bound comes from the base policy (GST-3360)', () => {+ // Value: protects=a repo that raised ci_record_timeout_s (harness-evals: 900 s, for a per_file rerun of CI-skipped files) gets that+ // bound in preflight's carry too, and the line says so; fails_when=preflight's carry keeps the 600 s default or prints no bound;+ // seam=bin/gstack-ship-preflight --tests-only, runLanes, carryLane+ test('the base sets 900 s: preflight carries the lane under it and says so', () => {+ const out = testsOnly(carried({ '.gstack/ship-policy.json': JSON.stringify({ ci_record_timeout_s: 900, min_gstack_version: CI_RECORD_TIMEOUT_KEY_VERSION }) + '\n' }));+ expect([out.status, lineOf(out.stdout, 'CI_RECORD_TIMEOUT')], out.stdout + out.stderr).toEqual([0, 'CI_RECORD_TIMEOUT: 900s (origin/main ci_record_timeout_s)']);+ expect(out.stdout).toMatch(/^LANE: free .*carried/m);+ });++ // Value: protects=with no policy key the bound stays 600 s and is still named; fails_when=the default changes or goes unsaid;+ // seam=bin/gstack-ship-preflight --tests-only+ test('no key on the base: the 600 s default, named', () => {+ const out = testsOnly(carried({}));+ expect([out.status, lineOf(out.stdout, 'CI_RECORD_TIMEOUT')], out.stdout + out.stderr).toEqual([0, 'CI_RECORD_TIMEOUT: 600s (default)']);+ });+});++describe('preflight Step 5: a worktree with no installed packages stops with the install command (GST-3360)', () => {+ // Value: protects=a fresh worktree (one per /ship run on a shared machine) gets one STOP naming the exact install command before+ // the pregate and lanes run without the repo's tools (tsc exit 127, unresolved imports); fails_when=Step 5 runs anyway, the stop+ // names no command, the lockfile's tool is ignored, or a checkout with node_modules or no declared packages is stopped;+ // seam=bin/gstack-ship-preflight --tests-only, depsInstall+ test('package.json declares packages and node_modules is missing: stop before anything runs; installed, it goes on', () => {+ const f = shipFixture({ 'package.json': '{"name":"fx","version":"1.0.0","devDependencies":{"left-pad":"1.3.0"}}\n', 'bun.lock': '{}\n' });+ fixtures.push(f);+ const held = testsOnly(f);+ expect(held.status, held.stdout + held.stderr).toBe(3);+ expect(lineOf(held.stdout, 'STOP')).toBe(`STOP: DEPS_MISSING: ${f.work}/package.json declares packages but there is no node_modules (a fresh worktree), so Step 5's pregate and lanes cannot run: cd '${f.work}' && bun install --frozen-lockfile, then rerun this command`);+ expect(held.stdout).not.toMatch(/^PREGATE: /m);+ expect(freeRuns(f)).toBe(0);+ fs.mkdirSync(path.join(f.work, 'node_modules'));+ const ran = testsOnly(f);+ expect(ran.stdout).not.toContain('DEPS_MISSING');+ expect(ran.stdout).toMatch(/^PREGATE: /m);+ });++ test('a package-lock.json names npm ci, and a package.json with no packages never stops', () => {+ const f = shipFixture({ 'package.json': '{"name":"fx","version":"1.0.0","dependencies":{"left-pad":"1.3.0"}}\n', 'package-lock.json': '{}\n' });+ fixtures.push(f);+ expect(lineOf(testsOnly(f).stdout, 'STOP')).toContain(`&& npm ci, then rerun this command`);+ const shrink = shipFixture({ 'package.json': '{"name":"fx","version":"1.0.0","dependencies":{"left-pad":"1.3.0"}}\n', 'npm-shrinkwrap.json': '{}\n' });+ fixtures.push(shrink);+ expect(lineOf(testsOnly(shrink).stdout, 'STOP')).toContain(`&& npm ci, then rerun this command`);+ const plain = shipFixture();+ fixtures.push(plain);+ expect(testsOnly(plain).stdout).not.toContain('DEPS_MISSING');+ });++ // Value: protects=an installed Yarn Plug'n'Play checkout, which never has node_modules, runs Step 5 instead of stopping on an+ // install that cannot clear the stop; fails_when=depsInstall checks node_modules alone; seam=bin/gstack-ship-preflight --tests-only+ test('a Yarn PnP checkout (.pnp.cjs, no node_modules) never stops on DEPS_MISSING', () => {+ const f = shipFixture({ 'package.json': '{"name":"fx","version":"1.0.0","dependencies":{"left-pad":"1.3.0"}}\n', 'yarn.lock': '\n', '.pnp.cjs': '\n' });+ fixtures.push(f);+ const out = testsOnly(f);+ expect(out.stdout).not.toContain('DEPS_MISSING');+ expect(out.stdout).toMatch(/^PREGATE: /m);+ const classic = shipFixture({ 'package.json': '{"name":"fx","version":"1.0.0","dependencies":{"left-pad":"1.3.0"}}\n', 'yarn.lock': '\n', '.pnp.js': '\n' });+ fixtures.push(classic);+ expect(testsOnly(classic).stdout).not.toContain('DEPS_MISSING');+ });+});