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

Let a repo keep server-backed Playwright tests out of the local pre-merge run (GST-3553) (#4885)

Garry Tan942a12c6188e
diff --git a/changelog.d/capy-skip-server-playwright-tests-locally.md b/changelog.d/capy-skip-server-playwright-tests-locally.md
new file mode 100644
index 000000000..ac4495a74
--- /dev/null
+++ b/changelog.d/capy-skip-server-playwright-tests-locally.md
@@ -0,0 +1 @@
+**A repo can now keep browser end-to-end tests that need running servers out of the pre-merge test run, wherever the tests live.** List the folder in `.gstack/pregate.json` as `"local_skip": ["apps/web/e2e/**"]` on your main branch. /gstack-ship then leaves the Playwright tests under it out of the run on your machine, prints how many it left out, and still expects them from your CI or remote test gate. Any test under that folder that isn't a Playwright test still runs, so a folder glob that's too wide can't quietly stop your unit tests. Before this, only folders under `test/`, `tests/`, `spec/` or `__tests__/` could be set aside, so a suite at a path like `apps/web/e2e/` failed a green branch while it waited for a server that never started (#4709).
diff --git a/docs/pregate.md b/docs/pregate.md
index e7d44dbfe..0f46279f0 100644
--- a/docs/pregate.md
+++ b/docs/pregate.md
@@ -92,7 +92,8 @@ the byte-pinned `/gstack-ship` renders in `test/fixtures/golden/`).
| Key | Meaning |
|---|---|
| `runner` | the local test command with `{files}` (gstack: `bun test --timeout=30000 {files}`, the 30 s per-test timeout CI uses); set, the local lane gives it only the selected files its tool runs, judged by extension (JS/TS files for `bun test`, `node --test`, `deno test`, vitest, jest, mocha, ava or playwright; `.py` files for pytest; each matched as a whole word, so `npx vitest run` counts and `tests/node/run.sh` does not; every file for any other command, such as a `node scripts/run-tests.js` dispatcher, or one naming both), and the lanes detail names each file it cannot run as not run and not counted as covered, so a `*_test.py` never reaches a local `bun test` (no Python lane runs beside a declared runner; the remote gate and `test_backend` commands still receive the whole selection, a declared test tree's tests included, since that exclusion is local-only); unset, it is detected (bun, vitest or jest for JS/TS files, pytest when python3 can import it (else `pytest` or `python3` is named missing), `node --test`, and `flutter test`/`dart test` per Dart package root, through fvm when that package or an ancestor pins it with `.fvmrc` or `.fvm/fvm_config.json` and fvm is on PATH; `cargo test -p <name>` per Rust crate, run from the root of the workspace the crate is a member of (Cargo's `members` globs, `exclude` and `package.workspace`), else the crate directory; a JS/TS test whose nearest package.json is a nested package declaring vitest or jest (a dependency or its `test` script) runs from that package, with package-relative paths, through the package manager its `packageManager` field or the nearest lockfile up to the repo root names: `pnpm exec`, `yarn`, `bun x`, else `npx`; a JS/TS test file that imports `@playwright/test` at the start of a line, or takes `test` from a repo module that takes `test` from it (Playwright's fixtures pattern, followed through named and `export *` re-exports and `index` modules up to 8 deep, never outside the repo; only the module `test` comes from), runs as `playwright test --reporter=list` from its nearest package through that same package manager, whatever the unit runner is, a type-only import (`import type …`, or one whose every specifier is `type X`) does not count, file arguments are passed as escaped regexes anchored to the path (Playwright reads them as regexes), and a run where every test fails and Playwright says its browser is not installed is `PREGATE_ENVIRONMENT` (a partial install, where some tests pass, stays the diff's failure); a `.js`, `.mjs` or `.cjs` test that loads `node:test` in a statement starting a line, and loads neither vitest nor `@jest/globals`, runs through `node --test` from the repo root even when the repo or its package declares vitest or jest (which find no suite in such a file), while a bun repo keeps `bun test` for it; every other test keeps the root detection, split by language when no one runner fits them all, so `.mjs` and `.py` root tests each get their own runner); nothing detected, a Dart SDK, cargo or package manager missing from PATH, a `.dart` file with no `pubspec.yaml` above it, a `.rs` file outside any crate, or one in a crate whose name Cargo would reject (anything but letters, digits, `_` and `-`), is `incomplete` (the runnable groups still run, so a real failure still fails) |
-| `dependencies` | glob → test files for subprocess targets, runtime reads and generated inputs the import graph cannot see; `[]` declares "no lane needed" (docs, licences). A `[]` on a folder inside a test directory (`test/`, `tests/`, `spec/` or `__tests__/`, as in `"tests/live/**": []`; never the whole directory, so `"test/**": []` changes nothing) is the repo's statement that the tests under it run in their own tier, not in /gstack-ship's local lane: pregate keeps every selected test under that glob out of the local lane, whether touched or picked through an import (a test `.gstack/always-run.json` names still runs; the remote side is unchanged: the remote gate, `test_backend` and any remote platform lane that selects the test still owe it; and only a base-branch or user-owned policy's `[]` counts, never a bootstrap head file read under `--policy-from` head when neither exists), and prints `declared test tree <glob>: N test file(s) not run in the local lane` in the `lanes` lines it records; tests outside the glob still run, and a `[]` on any other glob never skips a test. A `[]` that matches a deleted test does not skip it: the deleted test still runs its owning suite, and a file naming it that `[]` covers (a durations list) counts as covered. With this key present, even empty, the policy [declares lanes](#lane-requirements) |
+| `dependencies` | glob → test files for subprocess targets, runtime reads and generated inputs the import graph cannot see; `[]` declares "no lane needed" (docs, licences). A `[]` on a folder inside a test directory (`test/`, `tests/`, `spec/` or `__tests__/`, as in `"tests/live/**": []`; never the whole directory, so `"test/**": []` changes nothing) is the repo's statement that the tests under it run in their own tier, not in /gstack-ship's local lane: pregate keeps every selected test under that glob out of the local lane, whether touched or picked through an import (a test `.gstack/always-run.json` names still runs; the remote side is unchanged: the remote gate, `test_backend` and any remote platform lane that selects the test still owe it; and only a base-branch or user-owned policy's `[]` counts, never a bootstrap head file read under `--policy-from` head when neither exists), and prints `declared test tree <glob>: N test file(s) not run in the local lane` in the `lanes` lines it records; tests outside the glob still run, and a `[]` on any other glob never skips a test. A `[]` that matches a deleted test does not skip it: the deleted test still runs its owning suite, and a file naming it that `[]` covers (a durations list) counts as covered. With this key present, even empty, the policy [declares lanes](#lane-requirements). For a test tree outside those four folders, such as a Playwright suite that needs servers, see `local_skip` |
+| `local_skip` | folder globs whose Playwright specs stay out of the local lane, for an end-to-end tree outside `test/`, `tests/`, `spec/` and `__tests__/` that needs servers only CI starts (as in `"local_skip": ["apps/web/e2e/**"]`; #4709). Each entry ends in `/**` and names at least one literal folder, so `**`, `*/**` and a file glob such as `apps/web/e2e/*.spec.ts` are refused. Only a file Playwright plainly owns is left out: a JS/TS file under a `package.json` whose own `test` comes from `@playwright/test` (an `import`, or a repo fixture module that takes it from there) and that loads no unit runner (vitest, `@jest/globals`, `bun:test`, `node:test`); an import written inside a template string or a comment does not count. Every other test under the glob keeps its runner and is named on a `local_skip <glob>: N selected test file(s) under it are not Playwright specs, so local_skip keeps them in the local lane` line, so an over-wide glob such as `apps/web/**`, or a unit test that borrows a Playwright helper such as `expect`, never skips a unit test, and the key stays Playwright-only (a wider skip would be a new key). A spec that takes `test` through `require` or a tsconfig path alias is not recognised and still runs. Skipped specs print `declared test tree <glob>: N test file(s) not run in the local lane (listed in local_skip in <policy>; …)`; a test `.gstack/always-run.json` names still runs, a glob that is also a `[]` test tree keeps that wording, and `--explain` names a glob matching no test file. The remote side is unchanged: the remote gate, `test_backend` and any remote platform lane that selects the spec still owe it, and with none of those the repo's own CI is what runs it. The key does not [declare lanes](#lane-requirements), and only a base-branch or user-owned policy's `local_skip` counts: under `--policy-from head` a branch that adds or changes it is refused as loosening, and a bootstrap head file's drops nothing. Older gstack refuses the unknown key, so a repo adopting it should set `min_gstack_version` in `.gstack/ship-policy.json` (an older install then says to upgrade) |
| `empty_lanes` | extra globs for the docs/no-tests empty lane. Any Markdown file already qualifies with no pin file when no test depends on it (the same import graph as other files: a quoted path, a `join()` of path segments, an import, or a `dependencies` entry). reStructuredText and AsciiDoc count as Markdown here. README, CHANGELOG, CONTRIBUTING, LICENSE, AGENTS and CLAUDE qualify even without `.md`, and so does licence text under any vendored name (`roboto-LICENSE.txt`, `LICENSE-MIT`, `licenses/*.txt`). Source code and files under a test directory never qualify. A test that reads the file still selects that test |
| `selection` | `workflow.yml/job` → a command printing the lane's file list, for matrices a planner computes (gstack: `scripts/test-free-shards.ts --list`) |
| `warn` | check ids downgraded to warn; `secrets` and required lanes never. `"lanes"` downgrades only a touched file with no lane: the selected tests still run, a red lane stays `fail` (`PREGATE_LANE_FAILED`) and an unfinished one `incomplete`; a green run is `warn` `PREGATE_NO_LANE` naming the unmapped files |
diff --git a/lib/pregate/checks/lanes.ts b/lib/pregate/checks/lanes.ts
index cc4fe4b75..8f737125d 100644
--- a/lib/pregate/checks/lanes.ts
+++ b/lib/pregate/checks/lanes.ts
@@ -38,6 +38,7 @@ import { starterPolicy } from '../starter';
import { isDeviceDart, listRepoFiles, readRepoFile } from '../import-graph';
import { docsOnlyLane } from '../docs-only-lane';
import { selectLanes, type Selection } from '../lane-selection';
+import { playwrightSpec } from '../playwright-spec';
import { launchRuntime } from '../runtime';
import { cargoModel, type CargoModel } from '../rust';
import { adapterFor, PIPEFAIL, readRange, STALL_IDLE, supervise, type Counter, type Supervised } from '../supervise';
@@ -184,50 +185,6 @@ function packageRunner(repoRoot: string, dir: string, env: NodeJS.ProcessEnv): {
return { runner: `${PM_EXEC[pm]} ${tool} {files}` };
}
-/**
- * Whether a JS/TS test imports a value from Playwright's runner in a statement that starts a line: `import … from '@playwright/test'`
- * (one line or several), a bare import, or `require`. A type-only import (`import type …`, or every specifier `type X`) and a string or
- * fixture body that mentions the import mid-line do not count.
- */
-function importsPlaywright(text: string): boolean {
- const code = text.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '');
- if (/^[\t ]*(?:import[\t ]*|(?:const|let|var)\b[^=\n]*=[\t ]*require\([\t ]*)['"]@playwright\/test['"]/m.test(code)) return true;
- for (const m of code.matchAll(/^[\t ]*import(?=[\s{*])([^'"`;]*?)\bfrom[\t ]*['"]@playwright\/test['"]/gm)) {
- const spec = m[1]!.trim();
- if (!/^type(?=[\s{*])/.test(spec) && spec.replace(/[{}]/g, '').split(',').some(s => s.trim() && !/^type\s/.test(s.trim()))) return true;
- }
- return false;
-}
-/** Where a file takes the value `test` from: a relative module or `@playwright/test`, by `import { test } from …` (aliased or not), `export { test } from …` or `export * from …`. */
-function testSources(text: string): string[] {
- const code = text.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '');
- return [...code.matchAll(/^[\t ]*(?:(?:import|export)[\t ]*\{([^}]*)\}|export[\t ]*\*)[\t ]*from[\t ]*['"](\.{1,2}\/[^'"]+|@playwright\/test)['"]/gm)].filter(m => m[1] === undefined || m[1].split(',').some(s => /^test(?:\s+as\s+[\w$]+)?$/.test(s.trim()))).map(m => m[2]!);
-}
-/**
- * Whether a JS/TS test is a Playwright spec: it imports a value from `@playwright/test`, or takes `test` from a repo module that does and doesn't take
- * `test` from a unit runner, directly or through further such modules, up to 8 deep (Playwright's fixtures pattern: `base.extend(…)`, `mergeTests(…)`).
- * Only the modules `test` comes from are followed, so a unit test whose helper or vitest fixture uses other Playwright APIs keeps its runner (#4347).
- */
-function playwrightSpec(repoRoot: string, file: string): boolean {
- const exts = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
- const seen = new Set<string>();
- let level = [file];
- for (let depth = 0; level.length && depth <= 8; depth++) {
- const next: string[] = [];
- for (const mod of level.filter(m => !seen.has(m))) {
- seen.add(mod);
- const text = readRepoFile(repoRoot, mod) ?? '', sources = testSources(text);
- if (depth === 0 ? importsPlaywright(text) : sources.includes('@playwright/test') || (importsPlaywright(text) && !/^[\t ]*import\b[^;]*\btest\b[^;]*\bfrom[\t ]*['"](?:vitest|@jest\/globals|bun:test|node:test)['"]/m.test(text))) return true;
- for (const base of sources.filter(s => s.startsWith('.')).map(spec => path.posix.normalize(path.posix.join(path.posix.dirname(mod), spec))).filter(b => b !== '..' && !b.startsWith('../'))) {
- const stem = base.replace(/\.[cm]?jsx?$/, '');
- const hit = [base, ...exts.map(e => stem + e), ...exts.map(e => `${base}/index${e}`)].find(c => readRepoFile(repoRoot, c) !== null);
- if (hit) next.push(hit);
- }
- }
- level = next;
- }
- return false;
-}
/** Whether a JS test is a node:test file: it loads `node:test` in a statement that starts a line (`import … from 'node:test'`, a bare import, or `require`) and loads neither vitest nor `@jest/globals`, whose runner owns it. Text that mentions a module mid-line, in a comment or in a template literal does not count. */
function importsNodeTest(text: string): boolean {
const code = text.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*|`(?:\\[\s\S]|[^\\`])*`/g, '');
@@ -520,7 +477,8 @@ function describe(ctx: PregateContext, sel: Selection, mode: NoLaneMode): string
for (const r of sel.removed) lines.push(`removed (no lane owed): ${r.file} — ${r.note}`);
if (sel.emptyLane.length) lines.push(`docs/no-tests (empty lane): ${sel.emptyLane.join(' ')}`);
if (sel.inert.length) lines.push(`no-tests (assets and tool config): ${sel.inert.join(' ')}`);
- for (const d of sel.declaredTier) lines.push(`declared test tree ${d.glob}: ${d.tests.length} test file(s) not run in the local lane (declared [] in ${ctx.configLabel}; the repo runs them in their own tier)`);
+ for (const d of sel.declaredTier) lines.push(`declared test tree ${d.glob}: ${d.tests.length} test file(s) not run in the local lane (${d.source === 'local_skip' ? 'listed in local_skip' : 'declared []'} in ${ctx.configLabel}; the repo runs them in their own tier)`);
+ for (const k of sel.localSkipKept) lines.push(`local_skip ${k.glob}: ${k.tests.length} selected test file(s) under it are not Playwright specs, so local_skip keeps them in the local lane (${k.tests.slice(0, 8).join(' ')}${k.tests.length > 8 ? ' …' : ''})`);
if (sel.stampOnly.length) lines.push(`version-stamp-only (no lane needed): ${sel.stampOnly.join(' ')} — only version values changed against the merge base; a manifest whose other content changed still needs a lane`);
for (const r of sel.remote) lines.push(`requires-remote ${r.lane} (${r.platform}): ${r.tests.length} test(s) — ${r.tests.slice(0, 8).join(' ')}${r.tests.length > 8 ? ' …' : ''}`);
lines.push(`Tiers ran: ${sel.tiersRan.join(' ') || '(none)'}; requires-remote: ${[...new Set(sel.remote.map(r => r.platform))].join(' ') || 'none'}`);
diff --git a/lib/pregate/config.ts b/lib/pregate/config.ts
index b7214baa9..f7f189511 100644
--- a/lib/pregate/config.ts
+++ b/lib/pregate/config.ts
@@ -112,15 +112,17 @@ export interface PregateConfig {
run_profiles: Record<string, RunProfile>;
remote_gate_runs: RemoteGateRuns | null;
ship_lanes_from: Record<string, ShipLaneMapping>;
+ /** Folder globs whose Playwright specs stay out of the local lane (#4709); never another test. */
+ local_skip: string[];
}
export interface Guard { id: string; when: string[]; command: string; fix?: string; timeout_s?: number }
export interface AllowlistEntry { finding: string; paths?: string[]; pattern?: string; reason: string }
-export const DEFAULT_CONFIG: PregateConfig = { runner: null, dependencies: {}, empty_lanes: [], selection: {}, warn: [], strays: { allow: [] }, local: [], guards: [], serial_patterns: DEFAULT_SERIAL_PATTERNS, price_file: null, stall_timeout_s: null, timeout_s: null, remote_gate: null, allowlist: [], run_profiles: {}, remote_gate_runs: null, ship_lanes_from: {} };
+export const DEFAULT_CONFIG: PregateConfig = { runner: null, dependencies: {}, empty_lanes: [], selection: {}, warn: [], strays: { allow: [] }, local: [], guards: [], serial_patterns: DEFAULT_SERIAL_PATTERNS, price_file: null, stall_timeout_s: null, timeout_s: null, remote_gate: null, allowlist: [], run_profiles: {}, remote_gate_runs: null, ship_lanes_from: {}, local_skip: [] };
export interface ConfigError { code: ResultCodeName; path: string; message: string }
export const MAX_LIST = 256;
const MAX_COMMAND = 512;
-const KEYS = ['runner', 'dependencies', 'empty_lanes', 'selection', 'warn', 'strays', 'local', 'guards', 'serial_patterns', 'price_file', 'sealed', 'stall_timeout_s', 'timeout_s', 'remote_gate', 'allowlist', 'run_profiles', 'remote_gate_runs', 'ship_lanes_from'];
+const KEYS = ['runner', 'dependencies', 'empty_lanes', 'selection', 'warn', 'strays', 'local', 'guards', 'serial_patterns', 'price_file', 'sealed', 'stall_timeout_s', 'timeout_s', 'remote_gate', 'allowlist', 'run_profiles', 'remote_gate_runs', 'ship_lanes_from', 'local_skip'];
const LANE_ID = /^[A-Za-z0-9_.-]+\.ya?ml\/[A-Za-z0-9_-]+$/;
const MAX_GUARDS = 32;
const GUARD_KEYS = ['id', 'when', 'command', 'fix', 'timeout_s'];
@@ -227,6 +229,15 @@ export function validateConfig(raw: unknown, knownChecks: readonly string[] = []
if (!Array.isArray(list) || list.some(g => typeof g !== 'string')) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'empty_lanes', message: 'must be an array of globs (extra docs/no-tests paths; source files and test trees never qualify)' });
else (list as string[]).forEach((g, i) => { const why = globError(g); if (why) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: `empty_lanes[${i}]`, message: `${JSON.stringify(g)} ${why}` }); });
}
+ if ('local_skip' in obj) {
+ const list = obj.local_skip;
+ if (!Array.isArray(list) || list.some(g => typeof g !== 'string')) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'local_skip', message: 'must be an array of folder globs whose Playwright specs the local lane leaves out' });
+ else if (list.length > MAX_LIST) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'local_skip', message: `more than ${MAX_LIST} entries` });
+ else (list as string[]).forEach((g, i) => {
+ const why = globError(g) ?? (!g.endsWith('/**') || !g.split('/').some(s => s && !/[*?[\]{}]/.test(s)) ? 'must be a folder glob ending in /** that names at least one literal folder, as in apps/web/e2e/**' : list.indexOf(g) < i ? 'is listed twice' : null);
+ if (why) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: `local_skip[${i}]`, message: `${JSON.stringify(g)} ${why}` });
+ });
+ }
if ('dependencies' in obj) {
const deps = obj.dependencies;
if (!deps || typeof deps !== 'object' || Array.isArray(deps)) errors.push({ code: 'PREGATE_CONFIG_INVALID', path: 'dependencies', message: 'must be an object of glob → test file list' });
@@ -285,7 +296,7 @@ export function parseConfig(text: string, knownChecks: readonly string[] = []):
const errors = validateConfig(raw, knownChecks);
if (errors.length) return { config: DEFAULT_CONFIG, errors, declaresLanes: false };
const o = raw as Partial<PregateConfig>;
- return { declaresLanes: LANE_KEYS.some(k => k in o), config: { $schema: o.$schema, runner: o.runner ?? null, dependencies: o.dependencies ?? {}, empty_lanes: o.empty_lanes ?? [], selection: o.selection ?? {}, warn: o.warn ?? [], strays: { allow: o.strays?.allow ?? [] }, local: o.local ?? [], guards: o.guards ?? [], serial_patterns: o.serial_patterns ?? DEFAULT_SERIAL_PATTERNS, price_file: o.price_file ?? null, stall_timeout_s: o.stall_timeout_s ?? null, timeout_s: o.timeout_s ?? null, remote_gate: o.remote_gate ?? null, allowlist: o.allowlist ?? [], run_profiles: o.run_profiles ?? {}, remote_gate_runs: o.remote_gate_runs ?? null, ship_lanes_from: o.ship_lanes_from ?? {} }, errors: [] };
+ return { declaresLanes: LANE_KEYS.some(k => k in o), config: { $schema: o.$schema, runner: o.runner ?? null, dependencies: o.dependencies ?? {}, empty_lanes: o.empty_lanes ?? [], selection: o.selection ?? {}, warn: o.warn ?? [], strays: { allow: o.strays?.allow ?? [] }, local: o.local ?? [], guards: o.guards ?? [], serial_patterns: o.serial_patterns ?? DEFAULT_SERIAL_PATTERNS, price_file: o.price_file ?? null, stall_timeout_s: o.stall_timeout_s ?? null, timeout_s: o.timeout_s ?? null, remote_gate: o.remote_gate ?? null, allowlist: o.allowlist ?? [], run_profiles: o.run_profiles ?? {}, remote_gate_runs: o.remote_gate_runs ?? null, ship_lanes_from: o.ship_lanes_from ?? {}, local_skip: o.local_skip ?? [] }, errors: [] };
}
export type ConfigLoad = { config: PregateConfig; errors: ConfigError[]; present: boolean; label: string; kind: 'base' | 'head' | 'user' | 'none'; /** sha256 of the user file's bytes (kind 'user' only). */ digest?: string; /** The policy has a LANE_KEYS key; absent under kind 'none'. */ declaresLanes?: boolean } | { unavailable: true; base: string; detail: string };
@@ -378,6 +389,7 @@ export function explainConfig(): string {
`warn: check ids downgraded to warn; never ${NON_DOWNGRADABLE.join(', ')}; lanes downgrades only a touched file with no lane, after the selected tests ran (a red lane stays fail)`,
`lane requirements: a policy with any of ${LANE_KEYS.join(', ')} (even empty) makes a touched file with no lane PREGATE_NO_LANE; a policy with none of them (timeout_s only, say) keeps the no-policy warning (PREGATE_NO_POLICY) and starter`,
'strays.allow: root files or new top-level directories that are intentional',
+ 'local_skip: folder globs ending in /** (apps/web/e2e/**) whose Playwright specs the local lane leaves out, for e2e trees that need servers CI starts; any other test under the glob still runs, the remote gate and test_backend still owe the specs, it does not declare lanes, and only a base-branch or user-owned policy counts',
'local: <workflow.yml>/<job> lanes a local run satisfies (platform-agnostic toolchain, or CI off); their tests run here, not requires-remote',
'guards: [{ id, when: [globs], command, fix?, timeout_s? }]: each guard whose globs match a touched file runs in its own process (--allow-repo-commands); a failure fails pregate with the guard id and fix; never downgradable',
`serial_patterns: test-file globs the lanes check runs one process per file, apart from the unit files (default ${DEFAULT_SERIAL_PATTERNS.join(', ')})`,
diff --git a/lib/pregate/head-policy.ts b/lib/pregate/head-policy.ts
index 53c15f605..e50a6deae 100644
--- a/lib/pregate/head-policy.ts
+++ b/lib/pregate/head-policy.ts
@@ -20,7 +20,7 @@ import { PREGATE_CONFIG_PATH, loadConfigFromHead, parseConfig, type ConfigLoad,
type Loaded = Exclude<ConfigLoad, { unavailable: true }>;
-const FROZEN = ['runner', 'empty_lanes', 'selection', 'warn', 'strays', 'local', 'guards', 'serial_patterns', 'price_file', 'stall_timeout_s', 'timeout_s', 'remote_gate', 'allowlist'] as const;
+const FROZEN = ['runner', 'empty_lanes', 'selection', 'warn', 'strays', 'local', 'local_skip', 'guards', 'serial_patterns', 'price_file', 'stall_timeout_s', 'timeout_s', 'remote_gate', 'allowlist'] as const;
const canonical = (v: unknown): unknown => {
if (Array.isArray(v)) return v.map(canonical).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
diff --git a/lib/pregate/lane-selection.ts b/lib/pregate/lane-selection.ts
index 0e8c69415..88d767788 100644
--- a/lib/pregate/lane-selection.ts
+++ b/lib/pregate/lane-selection.ts
@@ -16,6 +16,7 @@ import { isDocsEmptyLane, isInertNoTests, isProtectedTree } from './docs-lane';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { buildGraph, isTestFile, listRepoFiles, testsFor, type Graph } from './import-graph';
+import { playwrightOwned } from './playwright-spec';
import { stampFileKind, versionStampOnly } from './stamp-only';
import type { PregateContext, RemoteObligation } from './types';
import type { Lane } from './workflows';
@@ -57,6 +58,22 @@ export function alwaysRunTests(repoRoot: string, testFiles: Iterable<string>, ba
return { tests: [...tests].sort(), unmatched, baseOnly: [...tests].filter(t => !ownTests.has(t)).sort() };
}
+/** A declared test tree: a `[]` on a folder inside a test directory, or a `local_skip` glob, whose selected tests (only Playwright specs, for local_skip) the local lane leaves out. */
+export interface DeclaredTier { glob: string; source: 'dependencies' | 'local_skip'; tests: string[] }
+
+/**
+ * The policy's `local_skip` globs as declared tiers (none for a bootstrap head policy) and a cached test for positive evidence that
+ * Playwright owns a file (playwrightOwned, stricter than the check that routes a file to `playwright test`), so a local_skip glob never
+ * leaves out a unit test or an ambiguous file. A glob matching no test file is named in `provenance`.
+ */
+function localSkipTiers(ctx: PregateContext, testFiles: readonly string[], provenance: string[]): { tiers: DeclaredTier[]; isSpec: (t: string) => boolean } {
+ const globs = ctx.headBootstrap ? [] : ctx.config.local_skip ?? [];
+ for (const glob of globs) if (!testFiles.some(t => matchesAny([glob], t))) provenance.push(`local_skip ${glob} matches no test file`);
+ const cache = new Map<string, boolean>();
+ const isSpec = (t: string) => { if (!cache.has(t)) cache.set(t, playwrightOwned(ctx.repoRoot, t)); return cache.get(t)!; };
+ return { tiers: globs.map(glob => ({ glob, source: 'local_skip' as const, tests: [] })), isSpec };
+}
+
/** A path the branch removed (deleted, or a rename's old name) that owes no lane, with why (`note`) and the files that lost their last test. */
export interface Removed { file: string; note: string; lostCoverage: string[] }
@@ -72,7 +89,9 @@ export interface Selection {
/** Release manifests whose diff against the merge base changes only version values (lib/pregate/stamp-only.ts): waived, no lane needed. */
stampOnly: string[];
/** Local-lane tests a `[]` declaration on a folder inside a test directory (TEST_SUBTREE) kept out, per glob: the repo runs them in their own tier. Never an always-run test; they stay in `tests`, `gateTests` and any remote obligation. */
- declaredTier: Array<{ glob: string; tests: string[] }>;
+ declaredTier: DeclaredTier[];
+ /** Selected local tests under a local_skip glob that are not Playwright specs, per glob: local_skip never leaves them out, so they run. */
+ localSkipKept: Array<{ glob: string; tests: string[] }>;
/** Every test the touched files select, sorted. */
tests: string[];
/** Tests that run on this machine. */
@@ -336,8 +355,9 @@ export function selectLanes(ctx: PregateContext): Selection {
const remote: RemoteObligation[] = [];
const tiers = new Set<string>();
const selected = [...tests].sort();
- const declaredTier = ctx.headBootstrap ? [] : Object.entries(ctx.config.dependencies ?? {}).filter(([glob, list]) => list.length === 0 && TEST_SUBTREE.test(glob) && /\/\*\*?$/.test(glob)).map(([glob]) => ({ glob, tests: [] as string[] }));
- const tierOf = (t: string) => alwaysRun.has(t) ? undefined : declaredTier.find(d => matchesAny([d.glob], t));
+ const skip = localSkipTiers(ctx, [...graph.tests].filter(t => !goneSet.has(t)), provenance);
+ const declaredTier: DeclaredTier[] = [...(ctx.headBootstrap ? [] : Object.entries(ctx.config.dependencies ?? {}).filter(([glob, list]) => list.length === 0 && TEST_SUBTREE.test(glob) && /\/\*\*?$/.test(glob)).map(([glob]) => ({ glob, source: 'dependencies' as const, tests: [] as string[] }))), ...skip.tiers];
+ const tierOf = (t: string) => alwaysRun.has(t) ? undefined : declaredTier.find(d => matchesAny([d.glob], t) && (d.source === 'dependencies' || skip.isSpec(t)));
let anyLocalAll = false;
for (const lane of ctx.lanes.filter(l => l.runsTests && !l.manual)) {
const set = laneFileSet(ctx, lane);
@@ -360,10 +380,12 @@ export function selectLanes(ctx: PregateContext): Selection {
if (!tier) continue;
tier.tests.push(t);
local.delete(t);
- provenance.push(`${t}: not run in the local lane; ${tier.glob} is declared [] in ${PREGATE_CONFIG_PATH} (its own tier)`);
+ provenance.push(tier.source === 'local_skip' ? `${t}: not run in the local lane; ${tier.glob} is listed in local_skip in ${ctx.configLabel} (a Playwright spec, its own tier)` : `${t}: not run in the local lane; ${tier.glob} is declared [] in ${PREGATE_CONFIG_PATH} (its own tier)`);
}
+ const kept = skip.tiers.length ? [...local].filter(t => !alwaysRun.has(t)) : [];
+ const localSkipKept = skip.tiers.map(d => ({ glob: d.glob, tests: kept.filter(t => matchesAny([d.glob], t)) })).filter(k => k.tests.length);
if (local.size && tiers.size === 0) tiers.add('unit');
- return { noLane: noLane.sort(), removed: removed.sort((a, b) => a.file.localeCompare(b.file)), emptyLane: emptyLane.sort(), inert: inert.sort(), stampOnly: stampOnly.sort(), declaredTier: declaredTier.filter(d => d.tests.length), tests: selected, localTests: [...local].sort(), gateTests, remote, tiersRan: [...tiers].sort(), laneSets, provenance };
+ return { noLane: noLane.sort(), removed: removed.sort((a, b) => a.file.localeCompare(b.file)), emptyLane: emptyLane.sort(), inert: inert.sort(), stampOnly: stampOnly.sort(), declaredTier: declaredTier.filter(d => d.tests.length), localSkipKept, tests: selected, localTests: [...local].sort(), gateTests, remote, tiersRan: [...tiers].sort(), laneSets, provenance };
}
export function isTest(file: string): boolean { return isTestFile(file); }
diff --git a/lib/pregate/playwright-spec.ts b/lib/pregate/playwright-spec.ts
new file mode 100644
index 000000000..09babf5d6
--- /dev/null
+++ b/lib/pregate/playwright-spec.ts
@@ -0,0 +1,69 @@
+/**
+ * pregate/playwright-spec — whether a JS/TS test file is a Playwright spec, the one predicate that routes a test to
+ * `playwright test` in the lanes check and lets a policy's `local_skip` leave it out of the local lane (#4709).
+ */
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { readRepoFile } from './import-graph';
+
+/**
+ * Whether a JS/TS test imports a value from Playwright's runner in a statement that starts a line: `import … from '@playwright/test'`
+ * (one line or several), a bare import, or `require`. A type-only import (`import type …`, or every specifier `type X`) and a string or
+ * fixture body that mentions the import mid-line do not count.
+ */
+function importsPlaywright(text: string): boolean {
+ const code = text.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '');
+ if (/^[\t ]*(?:import[\t ]*|(?:const|let|var)\b[^=\n]*=[\t ]*require\([\t ]*)['"]@playwright\/test['"]/m.test(code)) return true;
+ for (const m of code.matchAll(/^[\t ]*import(?=[\s{*])([^'"`;]*?)\bfrom[\t ]*['"]@playwright\/test['"]/gm)) {
+ const spec = m[1]!.trim();
+ if (!/^type(?=[\s{*])/.test(spec) && spec.replace(/[{}]/g, '').split(',').some(s => s.trim() && !/^type\s/.test(s.trim()))) return true;
+ }
+ return false;
+}
+/** Where a file takes the value `test` from: a relative module or `@playwright/test`, by `import { test } from …` (aliased or not), `export { test } from …` or `export * from …`. */
+function testSources(text: string): string[] {
+ const code = text.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '');
+ return [...code.matchAll(/^[\t ]*(?:(?:import|export)[\t ]*\{([^}]*)\}|export[\t ]*\*)[\t ]*from[\t ]*['"](\.{1,2}\/[^'"]+|@playwright\/test)['"]/gm)].filter(m => m[1] === undefined || m[1].split(',').some(s => /^test(?:\s+as\s+[\w$]+)?$/.test(s.trim()))).map(m => m[2]!);
+}
+/**
+ * Whether a JS/TS test is a Playwright spec: it imports a value from `@playwright/test`, or takes `test` from a repo module that does and doesn't take
+ * `test` from a unit runner, directly or through further such modules, up to 8 deep (Playwright's fixtures pattern: `base.extend(…)`, `mergeTests(…)`).
+ * Only the modules `test` comes from are followed, so a unit test whose helper or vitest fixture uses other Playwright APIs keeps its runner (#4347).
+ */
+export function playwrightSpec(repoRoot: string, file: string, owned = false): boolean {
+ const exts = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];
+ const seen = new Set<string>();
+ let level = [file];
+ for (let depth = 0; level.length && depth <= 8; depth++) {
+ const next: string[] = [];
+ for (const mod of level.filter(m => !seen.has(m))) {
+ seen.add(mod);
+ const raw = readRepoFile(repoRoot, mod) ?? '', text = owned ? raw.replace(TEMPLATE_LITERAL, '') : raw, sources = testSources(text);
+ if (depth === 0 ? (owned ? sources.includes('@playwright/test') : importsPlaywright(text)) : sources.includes('@playwright/test') || (importsPlaywright(text) && !/^[\t ]*import\b[^;]*\btest\b[^;]*\bfrom[\t ]*['"](?:vitest|@jest\/globals|bun:test|node:test)['"]/m.test(text))) return true;
+ for (const base of sources.filter(s => s.startsWith('.')).map(spec => path.posix.normalize(path.posix.join(path.posix.dirname(mod), spec))).filter(b => b !== '..' && !b.startsWith('../'))) {
+ const stem = base.replace(/\.[cm]?jsx?$/, '');
+ const hit = [base, ...exts.map(e => stem + e), ...exts.map(e => `${base}/index${e}`)].find(c => readRepoFile(repoRoot, c) !== null);
+ if (hit) next.push(hit);
+ }
+ }
+ level = next;
+ }
+ return false;
+}
+
+const TEMPLATE_LITERAL = /`(?:\\[\s\S]|[^\\`])*`/g;
+const UNIT_RUNNER = /^[\t ]*(?:import\b[^;'"`]*?\bfrom[\t ]*|import[\t ]*|(?:const|let|var)\b[^=\n]*=[\t ]*require\([\t ]*)['"](?:vitest|@jest\/globals|bun:test|node:test)['"]/m;
+/**
+ * Whether a policy's `local_skip` may leave a test out of the local lane (#4709): positive evidence that Playwright owns it, stricter than
+ * playwrightSpec so an ambiguous file keeps running. A JS/TS file under a package.json whose own `test` comes from `@playwright/test`,
+ * directly or through repo fixture modules, and that loads no unit runner; import-shaped text in a template literal or comment does not count.
+ */
+export function playwrightOwned(repoRoot: string, file: string): boolean {
+ if (!/\.[cm]?[jt]sx?$/.test(file)) return false;
+ const code = (readRepoFile(repoRoot, file) ?? '').replace(TEMPLATE_LITERAL, '').replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, '');
+ if (UNIT_RUNNER.test(code)) return false;
+ for (let d = path.posix.dirname(file); ; d = path.posix.dirname(d)) {
+ if (fs.existsSync(path.join(repoRoot, d === '.' ? '' : d, 'package.json'))) return playwrightSpec(repoRoot, file, true);
+ if (d === '.' || d === '/' || d === '') return false;
+ }
+}
diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.ts
index b326b9292..437f76385 100644
--- a/scripts/lib/windows-curation.ts
+++ b/scripts/lib/windows-curation.ts
@@ -79,6 +79,7 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }>
{ file: 'test/pregate-docs-lane-review.test.ts', reason: 'spawns bin/gstack-pregate through test/helpers/pregate-fixture.ts runBin (shebang via CreateProcess); the docs-lane selection rules it drives are POSIX-run like the other pregate fixtures' },
{ file: 'test/pregate-dart.test.ts', reason: 'its dart, flutter and fvm stand-ins are bash scripts on a colon-joined PATH, which Bun.which and CreateProcess cannot use on Windows, and its containment case needs a POSIX symlink; the Dart lane code it drives is POSIX-run like the other pregate fixtures' },
{ file: 'test/pregate-non-js.test.ts', reason: 'spawns bin/gstack-pregate through test/helpers/pregate-fixture.ts runBin and expects the Linux-host lanes verdict, like test/pregate-docs-lane-review.test.ts and test/pregate-selection.test.ts' },
+ { file: 'test/pregate-local-skip.test.ts', reason: 'spawns bin/gstack-pregate through test/helpers/pregate-fixture.ts runBin with a POSIX sh npx/pnpm shim on PATH and BASH_ENV, and expects the Linux-host lanes verdict, like test/pregate-declared-test-tree.test.ts' },
{ file: 'test/pregate-declared-test-tree.test.ts', reason: 'spawns bin/gstack-pregate through test/helpers/pregate-fixture.ts runBin and expects the Linux-host lanes verdict (the outside test runs in the local lane), like test/pregate-selection.test.ts' },
{ file: 'test/pregate-remote-gbrain.test.ts', reason: 'spawns bin/gstack-pregate through test/helpers/pregate-fixture.ts runBin (shebang via CreateProcess) and runs the gbrain-shaped ci:ubicloud package script through the POSIX lane runner, like test/pregate-remote.test.ts' },
{ file: 'test/pregate-remote-stamp-only.test.ts', reason: 'expects the Linux-host lanes verdict like test/pregate-remote.test.ts (on Windows the fixture\'s Linux lane is a requires-remote obligation) and skips itself on win32 (describe.skipIf), so the curated lane would run an empty file (#3485, #3486)' },
diff --git a/test/pregate-local-skip.test.ts b/test/pregate-local-skip.test.ts
new file mode 100644
index 000000000..3b790ef52
--- /dev/null
+++ b/test/pregate-local-skip.test.ts
@@ -0,0 +1,181 @@
+/**
+ * #4709 (GST-3553): a base-branch policy's local_skip names folder globs whose Playwright specs stay out of the local lane, the way a
+ * [] test-tree declaration does for a folder inside test/, tests/, spec/ or __tests__/. Only files pregate itself would hand to
+ * "playwright test" are left out: any other test under the glob still runs. Fixture code only; every runner is a shim on PATH.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { EXIT } from '../lib/headless-artifacts';
+import { lanesCheck } from '../lib/pregate/checks/lanes';
+import { parseConfig } from '../lib/pregate/config';
+import { buildContext } from '../lib/pregate/context';
+import { lanesOnlyHeadPolicy } from '../lib/pregate/head-policy';
+import { BASE_PREGATE, cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture';
+
+const SPEC = "import { test, expect } from '@playwright/test';\ntest('signs in', async ({ page }) => { await page.goto('/'); });\n";
+const UNIT = "const test = require('node:test');\ntest('a unit test beside the specs', () => { throw new Error('unit test ran ' + 'here'); });\n";
+const APP = { 'apps/web/package.json': JSON.stringify({ name: 'web', devDependencies: { '@playwright/test': '^1.48.0' } }) + '\n', 'apps/web/e2e/login.spec.ts': SPEC };
+const { runner: _runner, ...NO_RUNNER } = BASE_PREGATE;
+const policy = (extra: Record<string, unknown> = {}) => ({ ...NO_RUNNER, ...extra });
+const LINE = /declared test tree apps\/web\/e2e\/\*\*: 1 test file\(s\) not run in the local lane \(listed in local_skip in origin\/main@[0-9a-f]{12}:\.gstack\/pregate\.json; the repo runs them in their own tier\)/;
+
+const repos: FixtureRepo[] = [];
+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });
+const fixture = (pregate: Record<string, unknown> | null, files: Record<string, string> = {}) => {
+ const repo = makeFixtureRepo({ pregate, baseFiles: { ...APP, ...files } });
+ repos.push(repo);
+ return repo;
+};
+/** An npx (and pnpm) first on PATH, and again through BASH_ENV, that logs its arguments and fails like a Playwright run with no server. */
+const shim = (repo: FixtureRepo) => {
+ const dir = path.join(repo.root, 'npx-shim');
+ fs.mkdirSync(dir, { recursive: true });
+ const body = "#!/bin/sh\necho \"$@\" >> '" + path.join(dir, 'calls.log') + "'\necho 'TimeoutError: apiRequestContext.post: Timeout 30000ms exceeded.'\necho ' 1 failed'\nexit 1\n";
+ for (const bin of ['npx', 'pnpm']) fs.writeFileSync(path.join(dir, bin), body, { mode: 0o755 });
+ fs.writeFileSync(path.join(dir, 'path.sh'), "PATH='" + dir + "':\"$PATH\"\n");
+ return { env: { PATH: dir + ':' + (process.env.PATH ?? ''), BASH_ENV: path.join(dir, 'path.sh') }, calls: () => { try { return fs.readFileSync(path.join(dir, 'calls.log'), 'utf8'); } catch { return ''; } } };
+};
+const lanes = (repo: FixtureRepo, env: Record<string, string>, extra: string[] = []) => runBin(repo, 'gstack-pregate', ['--base', 'main', '--allow-repo-commands', '--only', 'lanes', '--explain', ...extra], env);
+const recorded = (repo: FixtureRepo): string[] => JSON.parse(fs.readFileSync(path.join(repo.work, '.gstack', 'tmp', 'pregate.json'), 'utf8')).checks.find((c: { id: string }) => c.id === 'lanes').lines;
+
+describe('local_skip: server-backed Playwright specs outside a test folder', () => {
+ // Value: protects=a green tree whose diff selects a Playwright spec under a local_skip glob passes without starting playwright;
+ // fails_when=the spec reaches playwright under CI=1 again (#4709); why_new=a [] only worked inside test/ tests/ spec/ __tests__/; seam=lane selection
+ test('a touched spec under a local_skip glob is not run, and the drop is printed and recorded', () => {
+ const repo = fixture(policy({ local_skip: ['apps/web/e2e/**'] }));
+ commit(repo, { 'apps/web/e2e/login.spec.ts': SPEC + '// touched\n' });
+ const s = shim(repo);
+ const r = lanes(repo, s.env);
+ expect(s.calls()).toBe('');
+ expect(r.status).toBe(EXIT.ok);
+ expect(r.out).toMatch(LINE);
+ expect(recorded(repo).join('\n')).toMatch(LINE);
+ expect(r.out).toContain('no local lane; 0 requires-remote obligation(s); 1 test file(s) in declared test trees not run here');
+ });
+
+ test('without local_skip the same spec is routed to playwright (negative control)', () => {
+ const repo = fixture(policy());
+ commit(repo, { 'apps/web/e2e/login.spec.ts': SPEC + '// touched\n' });
+ const s = shim(repo);
+ const r = lanes(repo, s.env);
+ expect(s.calls()).toContain("playwright test --reporter=list (?:^|/)e2e/login\\.spec\\.ts$");
+ expect(r.status).not.toBe(EXIT.ok);
+ expect(r.out).not.toContain('declared test tree');
+ });
+
+ test('a declared runner does not change what local_skip leaves out: the spec is still skipped', () => {
+ const repo = fixture(policy({ runner: 'node --test {files}', local_skip: ['apps/web/e2e/**'] }));
+ commit(repo, { 'apps/web/e2e/login.spec.ts': SPEC + '// touched\n' });
+ const r = lanes(repo, shim(repo).env);
+ expect(r.status).toBe(EXIT.ok);
+ expect(r.out).toMatch(LINE);
+ });
+
+ // Value: protects=a local_skip glob never skips a unit test, even an over-wide one; fails_when=local_skip drops every test under its glob
+ test('a unit test under a local_skip glob still runs and is named, even under an over-wide glob', () => {
+ for (const [glob, file] of [['apps/web/e2e/**', 'apps/web/e2e/helpers.test.js'], ['apps/web/**', 'apps/web/src/util.test.js']]) {
+ const repo = fixture(policy({ local_skip: [glob] }), { [file]: UNIT });
+ commit(repo, { [file]: UNIT + '\n' });
+ const r = lanes(repo, shim(repo).env);
+ expect(r.status).not.toBe(EXIT.ok);
+ expect(r.out).toContain('unit test ran here');
+ expect(recorded(repo).join('\n')).toContain('local_skip ' + glob + ': 1 selected test file(s) under it are not Playwright specs, so local_skip keeps them in the local lane');
+ }
+ });
+
+ // Value: protects=local_skip needs positive evidence that Playwright owns a file; fails_when=a unit test that only borrows a Playwright helper,
+ // or a fixture string shaped like a Playwright import, is skipped and pregate goes green without running it
+ test('a unit test that imports a Playwright helper, or quotes a Playwright import in a string, is not skipped', () => {
+ const files = {
+ 'apps/web/e2e/borrows-expect.test.ts': "import { test } from 'vitest';\nimport { expect } from '@playwright/test';\ntest('unit', () => { expect(1).toBe(2); });\n",
+ 'apps/web/e2e/fixture-text.spec.ts': "const FIXTURE = `\nimport { test } from '@playwright/test';\n`;\nexport default FIXTURE;\n",
+ };
+ for (const [file, text] of Object.entries(files)) {
+ const repo = fixture(policy({ local_skip: ['apps/web/e2e/**'] }), { [file]: text });
+ commit(repo, { [file]: text + '// touched\n' });
+ const r = lanes(repo, shim(repo).env);
+ expect(r.status).not.toBe(EXIT.ok);
+ expect(r.out).not.toContain('declared test tree');
+ expect(recorded(repo).join('\n')).toContain('local_skip apps/web/e2e/**: 1 selected test file(s) under it are not Playwright specs, so local_skip keeps them in the local lane');
+ }
+ });
+
+ test('an always_run spec inside the glob still runs', () => {
+ const repo = fixture(policy({ local_skip: ['apps/web/e2e/**'] }), { '.gstack/always-run.json': JSON.stringify({ tests: ['apps/web/e2e/**'] }) });
+ commit(repo, { 'apps/web/e2e/login.spec.ts': SPEC + '// touched\n' });
+ const s = shim(repo);
+ const r = lanes(repo, s.env);
+ expect(s.calls()).toContain('playwright test --reporter=list');
+ expect(r.out).not.toContain('declared test tree');
+ });
+
+ test('a glob that is also a [] test tree keeps the [] wording, and a glob matching no test file is named', () => {
+ const repo = fixture(policy({ dependencies: { ...BASE_PREGATE.dependencies, 'tests/e2e/**': [] }, local_skip: ['tests/e2e/**', 'apps/gone/**'] }), { 'tests/e2e/home.spec.ts': SPEC, 'package.json': '{"name":"root"}\n' });
+ commit(repo, { 'tests/e2e/home.spec.ts': SPEC + '// touched\n' });
+ const r = lanes(repo, shim(repo).env);
+ expect(r.status).toBe(EXIT.ok);
+ expect(r.out).toContain('declared test tree tests/e2e/**: 1 test file(s) not run in the local lane (declared [] in');
+ expect(r.out).toContain('local_skip apps/gone/** matches no test file');
+ });
+
+ test('on a small machine the remote gate still owes a skipped spec: the exclusion is local-only', async () => {
+ const repo = fixture(policy({ remote_gate: 'node scripts/remote-gate.js', local_skip: ['apps/web/e2e/**'] }));
+ commit(repo, { 'apps/web/e2e/login.spec.ts': SPEC + '// touched\n' });
+ const loaded = buildContext({ repoRoot: repo.work, base: 'main', policyFrom: 'base', allowRepoCommands: true, env: { ...process.env, ...repo.env }, progress: () => {}, cores: 4, testBackend: 'local' });
+ if (!('ctx' in loaded)) throw new Error('fixture context refused');
+ const r = await lanesCheck.run(loaded.ctx);
+ expect(r.status).toBe('requires-remote');
+ expect(r.remote?.find(o => o.lane === 'pregate.json/remote_gate')?.tests).toEqual(['apps/web/e2e/login.spec.ts']);
+ });
+});
+
+describe('local_skip and the branch policy', () => {
+ test('a local_skip the branch adds is refused under --policy-from head', () => {
+ const repo = fixture(policy());
+ commit(repo, { '.gstack/pregate.json': JSON.stringify(policy({ local_skip: ['apps/web/e2e/**'] })) + '\n', 'apps/web/e2e/login.spec.ts': SPEC + '// touched\n' });
+ const r = lanes(repo, shim(repo).env, ['--policy-from', 'head']);
+ expect(r.status).toBe(EXIT.refused);
+ expect(r.err).toContain('local_skip differs from the trusted policy');
+ expect(r.err).toContain('(PREGATE_HEAD_POLICY_LOOSENS');
+ });
+
+ test('with no base or user policy, a bootstrap head local_skip drops nothing', () => {
+ const repo = fixture(null);
+ commit(repo, { '.gstack/pregate.json': JSON.stringify(policy({ local_skip: ['apps/web/e2e/**'] })) + '\n', 'apps/web/e2e/login.spec.ts': SPEC + '// touched\n' });
+ const s = shim(repo);
+ const r = lanes(repo, s.env, ['--policy-from', 'head']);
+ expect(s.calls()).toContain('playwright test --reporter=list');
+ expect(r.out).not.toContain('declared test tree');
+ });
+
+ test('a branch that only changes local_skip gates under the base policy at /ship', () => {
+ const repo = fixture(policy({ local_skip: ['apps/web/e2e/**'] }));
+ commit(repo, { '.gstack/pregate.json': JSON.stringify(policy({ local_skip: ['apps/**'] })) + '\n' });
+ const v = lanesOnlyHeadPolicy(repo.work, 'main');
+ expect(v.head).toBe(false);
+ expect(v.line).toContain('also changes local_skip');
+ });
+});
+
+describe('local_skip in the policy schema', () => {
+ test('a policy holding only local_skip declares no lanes, so an unmapped file stays a warning', () => {
+ expect(parseConfig(JSON.stringify({ local_skip: ['apps/web/e2e/**'] })).declaresLanes).toBe(false);
+ const repo = fixture({ local_skip: ['apps/web/e2e/**'] });
+ commit(repo, { 'lib/brand-new.js': 'exports.x = 1;\n' });
+ const r = lanes(repo, shim(repo).env);
+ expect(r.out).toContain('no lane policy: lib/brand-new.js');
+ expect(r.out).not.toContain('FAIL lanes');
+ });
+
+ test('accepts folder globs and refuses everything else by path', () => {
+ for (const ok of [['apps/web/e2e/**'], ['apps/*/e2e/**', '**/e2e/**'], []]) expect(parseConfig(JSON.stringify({ local_skip: ok })).errors).toEqual([]);
+ const refused = (v: unknown) => parseConfig(JSON.stringify({ local_skip: v })).errors.map(e => [e.code, e.path]);
+ expect(refused('apps/web/e2e/**')).toEqual([['PREGATE_CONFIG_INVALID', 'local_skip']]);
+ expect(refused([1])).toEqual([['PREGATE_CONFIG_INVALID', 'local_skip']]);
+ for (const bad of ['**', '**/**', '*/**', 'apps/web/e2e/*.spec.ts', 'apps/web/e2e', '../x/**', '/abs/**']) expect(refused(['apps/ok/**', bad])).toEqual([['PREGATE_CONFIG_INVALID', 'local_skip[1]']]);
+ expect(refused(['apps/web/e2e/**', 'apps/web/e2e/**'])).toEqual([['PREGATE_CONFIG_INVALID', 'local_skip[1]']]);
+ expect(refused(Array.from({ length: 257 }, (_, i) => 'apps/a' + i + '/**'))).toEqual([['PREGATE_CONFIG_INVALID', 'local_skip']]);
+ expect(parseConfig(JSON.stringify({ local_skip: ['**'] })).errors[0]!.message).toContain('a folder glob ending in /** that names at least one literal folder');
+ });
+});