mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-01 06:24:41 +01:00
* feat(pregate): user-owned policy file and local lanes
A repo that keeps .gstack/ out of git can hold its pregate policy at
<GSTACK_HOME>/projects/<slug>/pregate.json. gstack-pregate run reads it only
under --policy-from base when the base carries no .gstack/pregate.json, so a
reviewed base copy always wins and a PR still cannot reach the policy. A
missing file falls back; any other read error, and a non-null sealed or
price_file (read only from the git copies), refuse with PREGATE_CONFIG_INVALID
and a fix that names the file.
A new `local` key lists <workflow.yml>/<job> lanes a local run satisfies: a
platform lane named there runs here (tier unit) instead of becoming a
requires-remote obligation. Lane ids share one LANE_ID check with selection.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(pregate): the user-owned policy file and local lanes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(pregate): policy fixes name the user-owned file when it is the active policy
With no .gstack/pregate.json on the base, an edit to that path is never read,
so the no-lane, runner, stall_timeout_s, remote_gate and strays fixes now name
ctx.configFile: the user-owned path when it is the active policy.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(pregate): the remote_gate, strays and stall fixes name the active policy file
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(pregate): pre-landing review fixes for the user-owned policy
Ignore a user policy path that is relative or inside the checkout, fingerprint
the active user file into check inputs, name the user file in its JSON errors
and the refusal lead, add --explain lines for an absent user file and an
unknown local id, and document the state-root location and slug lookup.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(pregate): containment edges and explain wording for the user policy
A state root under an in-repo directory named ..something passed the
inside-the-repo check, and realpath kept the caller's casing on macOS.
The unknown-local explain line now says workflow lane, and the state-root
chain in explain and docs names every source.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(pregate): a base copy git cannot read, or a dangling user symlink, refuses
Any git show failure read as no base policy, which now hands the run to
the unreviewed user file; it is absent only when cat-file says so, and a
spawn error (stdout cut at the buffer limit) counts as a failure. A user
pregate.json that is a dangling symlink refuses instead of reading as
absent.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(pregate): decide a missing base policy from the tree, and catch dangling parent links
cat-file -e checks the blob, so a missing or corrupt object still read as
no base copy; ls-tree reads the tree entry, and any failure refuses. The
dangling-symlink check now covers every path component, not just the file.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(result-codes): POLICY_SOURCE_UNAVAILABLE names an unreadable committed pin file
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(pregate): the active policy may be the user-owned file; new refusals
Guards, remote_gate, stall timeouts and lane fixes name the user-owned file
when it is the active policy; the trust boundary says run alone reads it;
the dangling-symlink and unreadable-base-copy refusals are documented, and
state-root lists the bucket's pregate.json.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(pregate): a checkout's .env cannot pick the user policy; verify re-checks it
Bun loads .env from the working directory, so a branch could set
GSTACK_PROJECT_SLUG or a state root and choose which pregate.json governs
it. The shebang now passes --no-env-file, scriptInvocation carries that
flag over when it launches the bin as bun <script>, and a bare bun launch
beside any dotenv file refuses (POLICY_SOURCE_UNAVAILABLE).
A recorded pass also outlived its policy: pregate.json now records the
user file's digest (or, under the defaults, the path that was absent), and
verify and the ship receipt treat an edited, deleted or newly present user
file as PREGATE_STALE, reading both paths from the record.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(pregate): keep the POLICY_SOURCE_UNAVAILABLE summary's pin-files wording
The added '(or .gstack/pregate.json)' broke describeRefusal's rewrite to
'the reviewed pin files cannot be read', which pregate-wtree-refusal pins.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(pregate): pick the host-foreign lane in the user-policy local-lane test
On a Windows host the windows lane is native, so it never became
requires-remote and the test failed on the Windows shards.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(pregate): Rust crate lanes and nested JS package runners
lanes reported PREGATE_NO_LANE for every touched .rs file and ran a nested
pnpm+vitest package's tests as `bun test` from the repo root.
- Rust: a .rs file of a crate (nearest Cargo.toml with [package]) is a test
under <crate>/tests/ or when it holds a #[cfg(test)]; every .rs file of a
crate and its Cargo.toml select the crate's tests and those of every crate
depending on it (lib/pregate/rust.ts). Selected tests run per crate as
`cargo test -p <name>` from the workspace root, judged on the summed
`test result:` lines (doc-tests included); zero tests stays ZERO-RUN and a
missing cargo is incomplete, like a missing Dart SDK.
- JS/TS: a test owned by a nested package.json that declares vitest or jest
runs from that package with package-relative paths, through the package
manager its packageManager field or nearest lockfile names (pnpm exec,
yarn, bun x, else npx). Root detection and a declared runner are unchanged.
- init notes that Rust tests run per crate; docs/pregate.md updated.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(pregate): parse Cargo manifests as TOML; follow workspace membership
The line scan of Cargo.toml missed dependents (a false green) and picked the
wrong workspace:
- an inherited renamed dependency (`base = { workspace = true }` with
`[workspace.dependencies] base = { package = "alpha", path = ... }`);
- dotted keys (`alpha.path = "../a"`), `[dependencies.<name>]` tables and
target-specific tables, matched by key name only;
- a crate the workspace excludes ran `cargo test -p` from the workspace root.
Manifests are now parsed with Bun.TOML. A dependency resolves by path
(relative to the manifest declaring it, or to the workspace root when
inherited), else by package name. A crate runs from the workspace it is a
member of under Cargo's rules (package.workspace, the nearest [workspace],
members globs, exclude, literal members, path dependencies of members),
else from its own directory. Nothing runs cargo.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(pregate): the Rust fixture's cargo shim wins PATH on Windows and beside a real cargo
windows-free-shard (5) failed 'a touched src file runs its crate...' and
'zero tests is ZERO-RUN...' deterministically: the shim PATH was joined with
':' so Git Bash never saw the shim dir, and the runner's real cargo ran
against the fixture (exit 1, no test result lines). On POSIX hosts where
Bun and cargo share a directory (/usr/local/bin on Capy's image), the lane
puts Bun's directory first and the real cargo wins the same way.
Join with path.delimiter, add cargo.cmd for Bun.which on Windows, and on
POSIX put the shim first again in the lane's own bash through BASH_ENV.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): quote the crate name in cargoRunner
The crate name is read from the repo's Cargo.toml and was interpolated into
'cargo test -p <name>', which the lane runs through bash. A name like
'evil;touch pwned' ran the second command. Quote it like every file and cwd
the lane already passes; a new end-to-end case checks the name reaches cargo
as one argument and runs nothing.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(pregate): the nested-package pnpm shim wins PATH beside a real pnpm
'a touched file in a nested pnpm+vitest package runs vitest there' ran the
host's real pnpm wherever Bun and pnpm share a directory (/usr/local/bin on
Capy's image): the lane puts Bun's directory first, so pnpm installed vitest
from the network, dirtied the fixture tree and the check came back
incomplete. Put the shim first again in the lane's bash through BASH_ENV,
as the Rust fixture does.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs(changelog): pregate Rust crate lanes and nested package runners (#3344)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): a crate name Cargo would reject never reaches the lane's shell
Port review (outside voice): quoting alone was not enough, because the lane
expands {files} after the runner string is built, so a crate named
'evil{files}' spliced the quoted file list into the quoted name and a file
name like tests/$(cmd).rs then ran. A name outside Cargo's grammar
(letters, digits, _ and -) now gets no runner: its files are unclaimed and
the lane is incomplete, as Cargo itself would refuse the manifest. A valid
name, Unicode included, still runs quoted.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): match Cargo members globs per path component, without a backtracking regex
Port review (outside voice): members globs went through ship-policy's
matchesAny, which escapes [...] classes (crates/[ab] matched nothing, so the
crate was no member, lost its inherited [workspace.dependencies] path and its
dependents' tests were never selected: a false green) and backtracks
exponentially on a hostile glob such as '*a*a...*ab' (over 5 s for one crate,
before any runner deadline). A small dynamic-programming matcher handles *,
?, [..] with negation and ranges, and ** across components, in
O(pattern x path).
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): a plain #[test] in src is a Rust test; bound the cfg attribute scan
Port review (outside voice): only #[cfg(test)] modules and tests/ files
counted, so a dependent crate whose tests are plain #[test] or #[tokio::test]
functions in src never ran when its dependency changed (a false green). The
cfg scan also went quadratic on a run of unclosed '#[cfg(' (about 3 s on
120 KB). Test attributes now count, and the cfg predicate and its strings are
length-bounded so the scan stays linear.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs(pregate): Rust test attributes, workspace membership and rejected crate names; changelog for the port review fixes
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): match members globs by code point in one pass, and admit every crate past a size cap
Second port review round (outside voice): the matcher counted UTF-16 units, so
'crates/?' missed a crate directory named with a supplementary character and
dropped its inherited dependencies (a false green); and each unmatched '['
rescanned the rest of the glob (5 s for one crate with a million of them).
Tokenize by code point with a precomputed next-']' table, and past 4096
characters of members globs admit every crate under the workspace: a wrong
member fails loudly in cargo, a dropped one is silent. The new supervised
probe kills a super-linear matcher at 30 s instead of hanging the file.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): scan cfg attributes once without truncating them; an unclosable one counts as a test
Second port review round (outside voice): the length bound from the first
round dropped a valid cfg(any(test, feature = "<257 chars>")), so its crate's
tests were no longer selected (a false green). Read each attribute once to
its closing ']' and resume after it, which keeps the scan linear without a
bound; an attribute the scan cannot close (an unterminated string, no ']')
counts as a test, which selects more, never fewer.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs(changelog): second port review round (code-point member globs, unbounded linear cfg scan)
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): past the members size cap, a crate's run root is undecided and its tests unclaimed
Third port review round (outside voice): admitting every crate past the cap
made a non-member run as 'cargo test -p <name>' from the workspace root,
where a same-named member answered and its passing tests stood in for the
orphan's failing one (a false green). Keep the conservative membership for
dependency edges, but leave such a crate's workspace undecided (null):
planRuns leaves its files unclaimed and the lane incomplete.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(pregate): the Rust end-to-end runs put the cargo shim under Windows' own Path key
windows-free-shard (5) still failed both end-to-end cases at fe99b200 with
the same symptom (the runner's real cargo, exit 1, no test result lines).
runBin merges process.env, whose Windows key is 'Path', with the shim's
'PATH', so the child got two path variables and read the original. Write the
shim under the key process.env actually uses, as test/helpers/unreachable-gbrain.ts
and sync-gbrain-readiness-fixture.ts do.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(pregate): run the cargo stand-in cases on POSIX only
windows-free-shard (5) still failed both end-to-end cargo-lane cases after the
delimiter, cargo.cmd and Path-key repairs: the lane's Git Bash exits 1 with an
empty log, and that log is not visible from CI. Skip the two cases that run the
bash stand-in on win32 (test.skipIf, as other POSIX-shim pregate fixtures are
handled) and drop the unproven cargo.cmd and Path-key changes. Selection,
planning and the hostile-name case still run on Windows.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* test(pregate): TODO(#3380) on the two win32-skipped cargo-lane cases
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): refuse a user policy whose link chain passes through the checkout
userConfigRejection checked the lexical path and the final realpath only. A
state root linked into the checkout, or a link hop inside it, let a branch pick
which existing out-of-repo policy governs it. Every hop of the resolution chain
is now checked. Found by the security review of #3286.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* fix(pregate): verify goes stale when a link on the way to the absent user policy dangles
A fresh run refuses a user policy path with a dangling parent link, but verify
looked only at the leaf, so the parent's ENOENT read as continued absence and
an old defaults pass stayed publishable. The loader and verify now share one
absence check. Found by the security review of #3286.
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* docs(pregate): CHANGELOG entry for #3286 and the link-chain and dangling-parent rules
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
* v1.91.206.0 stamp
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
---------
Co-authored-by: arlophoenix <arlo.phoenix@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: vilano93 <244097767+vilano93@users.noreply.github.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
258 lines
18 KiB
TypeScript
258 lines
18 KiB
TypeScript
/**
|
|
* pregate/context — what every check reads (plan C8): the base, the touched
|
|
* files (committed since the merge-base plus the working tree, renames and
|
|
* deletions kept), the reviewed `.gstack/pregate.json` and
|
|
* `.gstack/generated.json`, the workflow lanes and the starting fingerprint.
|
|
* Fingerprinting follows bin/gstack-evidence: the working-tree content hash
|
|
* (bin/gstack-wtree) before a check runs and again after; a tree that moved
|
|
* during a check makes its result `incomplete`, never `pass`.
|
|
*/
|
|
import { spawnSync } from 'node:child_process';
|
|
import { createHash } from 'node:crypto';
|
|
import * as fs from 'node:fs';
|
|
import * as os from 'node:os';
|
|
import * as path from 'node:path';
|
|
import { slugFromEnvironment } from '../bin-context';
|
|
import { isRegistryUnavailable, loadRegistryFromBase, loadRegistryFromHead, type Registry } from '../regen';
|
|
import { resolveStateRoot } from '../state-root';
|
|
import { RESULT_CODES, TROUBLESHOOTING_DOC, resultLine } from '../result-codes';
|
|
import { runScriptSync, wtreeFingerprint, type InvocationOptions, type WtreeResult } from '../script-invocation';
|
|
import { policyUnavailableLine, resolveBaseBranch } from '../ship-policy';
|
|
import { PREGATE_CONFIG_PATH, isConfigUnavailable, loadConfigFromBase, loadConfigFromHead, loadConfigFromUser, type ConfigError, type ConfigLoad, type PregateConfig } from './config';
|
|
import type { CheckResult, PregateContext, TouchedFile } from './types';
|
|
import { discoverLanes } from './workflows';
|
|
import type { RegistryError } from '../regen';
|
|
|
|
export interface BuildContextOptions {
|
|
repoRoot: string; base: string; policyFrom: 'base' | 'head'; allowRepoCommands: boolean;
|
|
timeoutMs?: number; env?: NodeJS.ProcessEnv; platform?: NodeJS.Platform; knownChecks?: readonly string[];
|
|
/** `--stall-timeout`; default the config's `stall_timeout_s`, else 300 s. */
|
|
stallTimeoutMs?: number; progress?: (line: string) => void; cores?: number; testBackend?: string; remote?: { spendCapUsd: number } | null;
|
|
/** How gstack's own bash bins launch (gstack-wtree, gstack-config); tests inject a Windows probe. */
|
|
invocation?: InvocationOptions;
|
|
/** `<state root>/projects/<slug>/pregate.json`: read only when the base carries no pregate.json, and never from a relative path or one inside the repository. */
|
|
userConfigPath?: string;
|
|
}
|
|
|
|
export const DEFAULT_STALL_TIMEOUT_S = 300;
|
|
const GSTACK_CONFIG = path.resolve(import.meta.dir, '..', '..', 'bin', 'gstack-config');
|
|
|
|
/** `gstack-config get test_backend` (local | ubicloud); `local` when unreadable. */
|
|
export function readTestBackend(env: NodeJS.ProcessEnv, invocation?: InvocationOptions): string {
|
|
const r = runScriptSync(GSTACK_CONFIG, ['get', 'test_backend'], { encoding: 'utf8', timeout: 15_000, env, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true }, invocation);
|
|
return (r.status === 0 && (r.stdout ?? '').trim()) || 'local';
|
|
}
|
|
export interface ContextRefusal {
|
|
code: 'POLICY_SOURCE_UNAVAILABLE' | 'PREGATE_CONFIG_INVALID' | 'REGEN_REGISTRY_INVALID' | 'WTREE_UNAVAILABLE';
|
|
message: string;
|
|
/** A cause-specific fix that replaces the code's own (a gstack-wtree exit names its repair; so does a `--base` that is no origin branch). */
|
|
fix?: string;
|
|
errors?: Array<ConfigError | RegistryError>;
|
|
}
|
|
export type ContextLoad = { ctx: PregateContext } | { refused: ContextRefusal };
|
|
|
|
/**
|
|
* A failed fingerprint as a refusal. A launch failure lists each Windows bash
|
|
* candidate tried with its rejection reason and keeps WTREE_UNAVAILABLE's fix
|
|
* (GSTACK_GIT_BASH); a helper exit keeps the repair gstack-wtree printed after
|
|
* its last `; ` (for example `set TMPDIR to a writable directory`).
|
|
*/
|
|
export function wtreeRefusal(fp: Extract<WtreeResult, { error: string }>): ContextRefusal {
|
|
if (fp.kind === 'launch') {
|
|
const message = fp.tried?.length ? `gstack-wtree could not start: no Git Bash found; tried ${fp.tried.map(c => `${c.source} ${c.path}: ${c.rejected}`).join('; ')}` : fp.error;
|
|
return { code: 'WTREE_UNAVAILABLE', message, fix: RESULT_CODES.WTREE_UNAVAILABLE.fix };
|
|
}
|
|
const cut = fp.error.lastIndexOf('; ');
|
|
if (cut > 0) return { code: 'WTREE_UNAVAILABLE', message: fp.error.slice(0, cut), fix: fp.error.slice(cut + 2) };
|
|
return { code: 'WTREE_UNAVAILABLE', message: fp.error, fix: 'run bin/gstack-wtree in the repository to see why it fails (it exits 1 outside a git repository, in one with no commits, or when a write fails), repair that, then rerun gstack-pregate' };
|
|
}
|
|
|
|
/**
|
|
* `origin/<base>` does not resolve, yet `<base>` names a commit here and no local
|
|
* branch: a SHA, a tag or another remote's ref (`upstream/main` in a fork clone).
|
|
* `git fetch origin <base>` never creates `origin/<base>` for those (#3269), so the
|
|
* fix names an origin branch instead. A local branch, or a name that resolves
|
|
* nowhere, keeps the code's fetch fix: that is the shallow or never-fetched
|
|
* checkout it repairs.
|
|
*/
|
|
function notAnOriginBranch(repoRoot: string, base: string): ContextRefusal | null {
|
|
if (git(repoRoot, ['rev-parse', '--verify', '--quiet', `refs/heads/${base}`]).ok) return null;
|
|
if (!git(repoRoot, ['rev-parse', '--verify', '--quiet', `${base}^{commit}`]).ok) return null;
|
|
const fallback = resolveBaseBranch(repoRoot);
|
|
const example = git(repoRoot, ['rev-parse', '--verify', '--quiet', `origin/${fallback}^{commit}`]).ok ? `, such as --base ${fallback}` : '';
|
|
return { code: 'POLICY_SOURCE_UNAVAILABLE', message: `origin/${base} is not a resolvable commit; ${base} names a commit here, but --base takes a branch name on origin`, fix: `pass a branch that exists on origin${example} (git branch -r --list 'origin/*' lists them)` };
|
|
}
|
|
|
|
export interface RefusalReport { code: ContextRefusal['code']; detail: string; fix: string; docs: string; line: string }
|
|
|
|
/**
|
|
* One context refusal as its stderr line and as the fields of the `--json` envelope.
|
|
* A cause-specific `fix` replaces the code's own. The shared POLICY_SOURCE_UNAVAILABLE
|
|
* summary names the ship policy; pregate's line says "pin files".
|
|
*/
|
|
export function describeRefusal(refused: ContextRefusal, base: string, context = 'gstack-pregate'): RefusalReport {
|
|
const { code, message } = refused;
|
|
const row = RESULT_CODES[code];
|
|
const docs = `${TROUBLESHOOTING_DOC}#${row.anchor}`;
|
|
if (code === 'POLICY_SOURCE_UNAVAILABLE' && !refused.fix) return { code, detail: message, fix: row.fix.replace('<base>', base), docs, line: policyUnavailableLine(context, base, message).replace('.gstack/ship-policy.json', 'pin files') };
|
|
if (!refused.fix) return { code, detail: message, fix: row.fix, docs, line: resultLine(context, code, message) };
|
|
return { code, detail: message, fix: refused.fix, docs, line: `${context}: ${row.summary.replace('.gstack/ship-policy.json', 'pin files')} (${message}); fix: ${refused.fix} (${code})` };
|
|
}
|
|
|
|
function git(cwd: string, args: string[], env?: NodeJS.ProcessEnv): { ok: boolean; out: string; err: string } {
|
|
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024, env });
|
|
return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: (r.stderr ?? '').trim() };
|
|
}
|
|
|
|
/** Committed changes since the merge-base (renames detected) plus every working-tree change, untracked files included. */
|
|
export function touchedFiles(repoRoot: string, mergeBase: string): TouchedFile[] {
|
|
const out = new Map<string, TouchedFile>();
|
|
const committed = git(repoRoot, ['diff', '--name-status', '-M', '-z', mergeBase, 'HEAD']).out.split('\0').filter(Boolean);
|
|
for (let i = 0; i < committed.length; i++) {
|
|
const status = committed[i]![0] as string;
|
|
if (status === 'R' || status === 'C') { const from = committed[++i]!; const to = committed[++i]!; out.set(to, { path: to, status: 'R', renamedFrom: from, uncommitted: false }); continue; }
|
|
const file = committed[++i]!;
|
|
out.set(file, { path: file, status: status === 'D' ? 'D' : status === 'A' ? 'A' : 'M', uncommitted: false });
|
|
}
|
|
const porcelain = git(repoRoot, ['status', '--porcelain', '-z', '--untracked-files=all']).out.split('\0').filter(Boolean);
|
|
for (let i = 0; i < porcelain.length; i++) {
|
|
const entry = porcelain[i]!;
|
|
const xy = entry.slice(0, 2);
|
|
const file = entry.slice(3);
|
|
if (xy.includes('R')) { const from = porcelain[++i]!; out.set(file, { path: file, status: 'R', renamedFrom: from, uncommitted: true }); continue; }
|
|
if (xy === '!!') continue;
|
|
const prior = out.get(file);
|
|
const status: TouchedFile['status'] = xy.includes('D') ? 'D' : xy === '??' || xy.includes('A') ? (prior?.status === 'M' ? 'M' : 'A') : (prior?.status ?? 'M');
|
|
out.set(file, { path: file, status, renamedFrom: prior?.renamedFrom, uncommitted: true });
|
|
}
|
|
return [...out.values()].filter(t => t.path !== 'node_modules' && !t.path.startsWith('node_modules/')).sort((a, b) => a.path.localeCompare(b.path));
|
|
}
|
|
|
|
/** The deepest existing ancestor realpathed (on-disk casing), the rest re-joined: a symlinked state root inside the checkout still counts as inside. */
|
|
function realish(p: string): string {
|
|
let head = path.resolve(p); const tail: string[] = [];
|
|
while (!fs.existsSync(head) && path.dirname(head) !== head) { tail.unshift(path.basename(head)); head = path.dirname(head); }
|
|
try { return path.join(fs.realpathSync.native(head), ...tail); } catch { return path.resolve(p); }
|
|
}
|
|
/**
|
|
* Every location the path to `p` passes through, each symlink followed one hop at a time: a link inside the checkout picks
|
|
* the file even when the last hop points back outside it. A missing component ends the walk with the rest joined lexically.
|
|
*/
|
|
function resolutionChain(p: string): string[] {
|
|
const chain: string[] = [];
|
|
let cur = path.parse(path.resolve(p)).root;
|
|
let rest = path.relative(cur, path.resolve(p)).split(path.sep).filter(Boolean);
|
|
for (let hops = 0; rest.length && hops <= 40;) {
|
|
const next = path.join(cur, rest.shift()!);
|
|
let st: fs.Stats | undefined;
|
|
try { st = fs.lstatSync(next, { throwIfNoEntry: false }); } catch { st = undefined; }
|
|
chain.push(st ? next : path.join(next, ...rest));
|
|
if (!st) break;
|
|
if (!st.isSymbolicLink()) { cur = next; continue; }
|
|
hops++;
|
|
const target = path.resolve(cur, fs.readlinkSync(next));
|
|
cur = path.parse(target).root;
|
|
rest = [...path.relative(cur, target).split(path.sep).filter(Boolean), ...rest];
|
|
}
|
|
return chain;
|
|
}
|
|
const within = (root: string, p: string) => { const rel = path.relative(root, p); return rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); };
|
|
|
|
/** Dotenv files Bun loads from the launch directory unless started with --no-env-file. */
|
|
const DOTENV_FILES = ['.env', '.env.local', '.env.development', '.env.development.local', '.env.production', '.env.production.local', '.env.test', '.env.test.local'];
|
|
|
|
/**
|
|
* The dotenv files in `cwd` that Bun loaded (no --no-env-file in `execArgv`). Any of them could set the slug or state
|
|
* root that picks the user policy, and Bun's dotenv syntax is looser than a key scan can follow, so any one refuses.
|
|
*/
|
|
export function loadedDotenvFiles(cwd: string, execArgv: readonly string[]): string[] {
|
|
if (execArgv.includes('--no-env-file')) return [];
|
|
return DOTENV_FILES.filter(f => fs.existsSync(path.join(cwd, f)));
|
|
}
|
|
|
|
/** `<state root>/projects/<slug>/pregate.json` for the repository at `root`, from the caller's environment. */
|
|
export function defaultUserConfigPath(root: string): string {
|
|
return path.join(resolveStateRoot(), 'projects', slugFromEnvironment(undefined, root), 'pregate.json');
|
|
}
|
|
|
|
/** Why a user policy path must not be read, or null: a relative path (no HOME) or one a PR could commit is never trusted. */
|
|
export function userConfigRejection(repoRoot: string, file: string): string | null {
|
|
if (!path.isAbsolute(file)) return 'not an absolute path';
|
|
const repo = path.resolve(repoRoot), real = realish(repoRoot);
|
|
if (within(repo, path.resolve(file)) || [file, ...resolutionChain(file)].some(p => within(real, realish(p)))) return 'inside the repository; a PR could supply it';
|
|
return null;
|
|
}
|
|
|
|
export function buildContext(o: BuildContextOptions): ContextLoad {
|
|
const base = o.base.replace(/^origin\//, '');
|
|
const baseRef = `origin/${base}`;
|
|
const baseSha = git(o.repoRoot, ['rev-parse', '--verify', '--quiet', `${baseRef}^{commit}`]);
|
|
if (!baseSha.ok || !baseSha.out) return { refused: notAnOriginBranch(o.repoRoot, base) ?? { code: 'POLICY_SOURCE_UNAVAILABLE', message: `${baseRef} is not a resolvable commit` } };
|
|
const head = git(o.repoRoot, ['rev-parse', 'HEAD']).out;
|
|
const mergeBase = git(o.repoRoot, ['merge-base', baseSha.out, 'HEAD']).out || baseSha.out;
|
|
let configLoad: ConfigLoad = o.policyFrom === 'head' ? loadConfigFromHead(o.repoRoot, o.knownChecks) : loadConfigFromBase(o.repoRoot, base, o.knownChecks);
|
|
const explain: string[] = [];
|
|
let absentUserPolicy: string | undefined;
|
|
if (o.policyFrom === 'base' && o.userConfigPath && !isConfigUnavailable(configLoad) && configLoad.kind === 'none') {
|
|
const rejected = userConfigRejection(o.repoRoot, o.userConfigPath);
|
|
const user = rejected ? null : loadConfigFromUser(o.userConfigPath, o.knownChecks);
|
|
if (user) configLoad = user;
|
|
else explain.push(`user policy: ${o.userConfigPath} ${rejected ? `ignored (${rejected})` : '(absent)'}`);
|
|
if (!user && !rejected) absentUserPolicy = o.userConfigPath;
|
|
}
|
|
if (isConfigUnavailable(configLoad)) return { refused: { code: 'POLICY_SOURCE_UNAVAILABLE', message: configLoad.detail } };
|
|
if (configLoad.errors.length) return { refused: { code: 'PREGATE_CONFIG_INVALID', message: `${configLoad.label}: ${configLoad.errors.map(e => `${e.message} at ${e.path}`).join('; ')}`, errors: configLoad.errors, ...(configLoad.kind === 'user' ? { fix: `edit ${o.userConfigPath} directly at each path the message names, then rerun gstack-pregate; it lives outside the repository, so a base-branch change does not reach it` } : {}) } };
|
|
const registryLoad = o.policyFrom === 'head' ? loadRegistryFromHead(o.repoRoot) : loadRegistryFromBase(o.repoRoot, base);
|
|
if (isRegistryUnavailable(registryLoad)) return { refused: { code: 'POLICY_SOURCE_UNAVAILABLE', message: registryLoad.detail } };
|
|
if (registryLoad.errors.length) return { refused: { code: 'REGEN_REGISTRY_INVALID', message: `${registryLoad.source.label}: ${registryLoad.errors.map(e => `${e.message} at ${e.path}`).join('; ')}`, errors: registryLoad.errors } };
|
|
const env = o.env ?? process.env;
|
|
const fp = wtreeFingerprint({ cwd: o.repoRoot, env, invocation: o.invocation });
|
|
if ('error' in fp) return { refused: wtreeRefusal(fp) };
|
|
const wtree = fp.tree;
|
|
const platform = o.platform ?? process.platform;
|
|
const config = configLoad.config as PregateConfig;
|
|
const lanes = discoverLanes(o.repoRoot, platform);
|
|
// A lane that exists but is not platform-tier on this host already runs here, so only an unknown id is worth a line.
|
|
for (const id of config.local) if (!lanes.some(l => l.id === id)) explain.push(`local: ${id} matches no workflow lane; ignored`);
|
|
return {
|
|
ctx: {
|
|
repoRoot: o.repoRoot, base, baseRef, baseSha: baseSha.out, mergeBase, head, wtree, touched: touchedFiles(o.repoRoot, mergeBase),
|
|
config, configLabel: configLoad.label, configFile: configLoad.kind === 'user' && o.userConfigPath ? o.userConfigPath : PREGATE_CONFIG_PATH, ...(configLoad.kind === 'user' && configLoad.digest ? { configDigest: configLoad.digest } : {}), ...(absentUserPolicy ? { absentUserPolicy } : {}), registry: registryLoad.registry as Registry, registryLabel: registryLoad.source.label,
|
|
lanes, platform, allowRepoCommands: o.allowRepoCommands, timeoutMs: o.timeoutMs ?? 600_000,
|
|
stallTimeoutMs: o.stallTimeoutMs ?? (config.stall_timeout_s ?? DEFAULT_STALL_TIMEOUT_S) * 1000,
|
|
progress: o.progress ?? (line => process.stderr.write(`${line}\n`)),
|
|
cores: o.cores ?? os.availableParallelism(), testBackend: o.testBackend ?? readTestBackend(env, o.invocation), policyFrom: o.policyFrom, remote: o.remote ?? null,
|
|
env, explain,
|
|
},
|
|
};
|
|
}
|
|
|
|
export function sha256(text: string): string { return createHash('sha256').update(text).digest('hex'); }
|
|
|
|
/** The common input identity every check records; checks add their own keys. */
|
|
export function baseInputs(ctx: PregateContext, extra: Record<string, string> = {}): Record<string, string> {
|
|
return { tree: ctx.wtree, head: ctx.head, base: `${ctx.baseRef}@${ctx.baseSha.slice(0, 12)}`, touched: sha256(ctx.touched.map(t => `${t.status} ${t.path}`).join('\n')), ...(ctx.configDigest ? { policy: ctx.configDigest } : {}), ...extra };
|
|
}
|
|
|
|
/**
|
|
* Run one check under the before/after fingerprint (bin/gstack-evidence:394):
|
|
* a tree that changed while the check ran, a thrown error or rejected promise
|
|
* or a timeout is `incomplete`. Wall time is measured here so every row
|
|
* carries `ms`.
|
|
*/
|
|
export async function withFingerprint(ctx: PregateContext, id: string, stage: CheckResult['stage'], fn: () => CheckResult | Promise<CheckResult>): Promise<CheckResult> {
|
|
const started = Date.now();
|
|
let result: CheckResult;
|
|
try { result = await fn(); }
|
|
catch (e: any) {
|
|
result = { id, stage, status: 'incomplete', detail: `threw: ${e?.message ?? e}`, code: 'PREGATE_INCOMPLETE', fix: 'read the error and rerun the check', inputs: baseInputs(ctx) };
|
|
}
|
|
const after = wtreeFingerprint({ cwd: ctx.repoRoot, env: ctx.env });
|
|
if ('error' in after) {
|
|
result = { ...result, status: 'incomplete', detail: `cannot fingerprint the working tree after the check (${after.error}); result not certified`, code: 'PREGATE_INCOMPLETE', fix: wtreeRefusal(after).fix! };
|
|
} else if (after.tree !== ctx.wtree) {
|
|
result = { ...result, status: 'incomplete', detail: `working tree changed during the check (${ctx.wtree.slice(0, 12)} → ${after.tree.slice(0, 12)}); result not certified`, code: 'PREGATE_INCOMPLETE', fix: 'keep the tree still during the run, then rerun gstack-pregate' };
|
|
}
|
|
return { ...result, ms: Date.now() - started };
|
|
}
|