Land checks a PR whose base moved in a separate clone, then with full CI, before merging (GST-1766) (#4649)

When main has moved since a PR's last CI run, `gstack-ship-queue land`
now runs its local merge checks in a throwaway clone and can then run
the full CI suite on the merged code before it merges.

Why: the old checks shared the checkout's git directory, so a PR's own
test commands could plant a hook that later ran with land's tokens, and
a PR could reach main on a base its full suite never saw.

Nothing to do: gstack's own policy turns the CI run on; other repos opt
in with `land.merged_ci`.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p1/specialist-batched#1 reader=security
Review-Finding: p1/red-team#2 reader=red-team
Review-Finding: p1/red-team#3 reader=red-team
Review-Finding: p2/specialist-batched#1 reader=security
Review-Finding: p2/red-team#1 reader=red-team
Review-Finding: p2/red-team#2 reader=red-team
Review-Finding: p2/outside-voice#1 reader=outside-voice
Review-Finding: p2/outside-voice#2 reader=outside-voice
Review-Finding: p2/adversarial-native#1 reader=adversarial-native
Review-Finding: p2/adversarial-native#2 reader=adversarial-native
Review-Finding: p2/adversarial-native#3 reader=adversarial-native
Review-Finding: p2/adversarial-native#4 reader=adversarial-native
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-22 01:27:38 +00:00
1 parent d8abe59096
commit abdc09dad1
12 files changed
+649 -60

No files matched your search

+3 -1
View File
@@ -23,6 +23,7 @@
*/
import type { SpawnSyncOptionsWithStringEncoding, SpawnSyncReturns } from 'node:child_process';
import { spawnSync } from './spawn-sync';
import { pathWithGit, toolPath } from './tool-path';
import type { GhResult, GhRunner } from './ci-gate';
export const MIN_POLL_MS = 60_000;
@@ -113,7 +114,8 @@ export const syncLimitEnv: LimitEnv = {
export function ghSpawnSync(args: string[], options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string> {
let last: SpawnSyncReturns<string> | undefined;
const run = withRateLimit(a => {
const r = spawnSync('gh', a, options);
const env = options.env ?? process.env;
const r = spawnSync(toolPath('gh', env.PATH), a, { ...options, env: { ...env, PATH: pathWithGit(env.PATH) } });
if (a === args) last = r;
return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '', ...(r.error ? { error: String(r.error.message) } : {}) };
}, syncLimitEnv);
+133 -31
View File
@@ -1,7 +1,8 @@
/**
* The `land` block of .gstack/ship-policy.json and its merged-tree run (docs/ship-policy.md#land-direct, GST-1316).
* When the base moved past a pin's merge base, `gstack-ship-queue land --pin` builds the pin merged onto the base
* tip in a throwaway worktree and runs `land.merged_checks` there; it lands only when every command passes. A
* tip in a fresh clone outside the checkout (its own .git and a copy of the checkout's node_modules, GST-1766) and runs
* `land.merged_checks` there; it lands only when every command passes. A
* conflict or a failing command refuses; with no key, land warns and merges as before. The commands are repo commands
* (the merged tree's package.json decides what `bun run` does), so they run only under --allow-repo-commands, never
* under --dry-run, with an environment that keeps PATH and locale only and a throwaway HOME. Validated here so
@@ -16,6 +17,17 @@
* with setsid or a double fork is reparented to land, which kills every child it has after each check. When either
* fails the checks do not run. macOS has no /proc but `ps -E` (KERN_PROCARGS2) shows a same-uid process's exec-time
* environment and has no per-process opt-out, so there the land process's environment stays readable to the checks.
* The checks also run as land's user. In the clone, what a check writes to .git, its hooks or node_modules stays in the
* clone, which land deletes. A check can still write outside it by absolute path, to files land's later git and gh
* calls (the lock push, the merge, the merge check) read with land's environment. Land records, before the checks: the
* config and hooks of the checkout's git directories, the commondir and gitdir files and the checkout's `.git` that say
* where git finds them, every config file git loads in the checkout (includes and the global file among them), gh's
* config and hosts files, the git and gh binaries lib/tool-path.ts pinned before the first repo command, and every hop
* of a symlink among them. When any changed it refuses, makes no further git or gh call and leaves the land lock held
* for a person to inspect. No git call land makes runs a hook (crew/lib/ship-queue-gate's queueHooksOff), which also skips the
* managed pre-push guard: land pushes only the lock and notes it writes and the merged commit of already-pushed commits,
* and a hook run after the checks is the opening this closes. Land's own git calls in the clone run with the checks'
* environment.
*/
import { dlopen, FFIType } from 'bun:ffi';
import { spawnSync } from './spawn-sync';
@@ -23,10 +35,12 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import type { PolicyError } from './ship-policy';
import { pinnedFirst, toolPath } from './tool-path';
/** A local git (crew/lib/ship-queue-gate's shape) so this module, which lib/ship-policy imports, pulls in no queue code. */
function git(cwd: string, args: string[], env?: NodeJS.ProcessEnv): { ok: boolean; out: string; err: string; status: number | null } {
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 120_000, env: env ?? process.env, maxBuffer: 64 * 1024 * 1024 });
const use = env ?? process.env;
const r = spawnSync(toolPath('git', use.PATH), args, { cwd, encoding: 'utf8', timeout: 120_000, env: use, maxBuffer: 64 * 1024 * 1024 });
return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: (r.stderr ?? '').trim(), status: r.status };
}
@@ -35,6 +49,8 @@ export interface LandPolicy {
merged_checks?: string[];
/** Git glob pathspecs: a PR that changes one lands as a merge commit, not a squash, so commits a receipt points to stay on the base (lib/squash-message.ts). */
merge_commit_paths?: string[];
/** A workflow land dispatches on the merged commit and the run profile its run must pass (lib/land-merged-ci.ts). */
merged_ci?: { workflow: string; profile: string };
}
const MAX_CHECKS = 16, MAX_COMMAND = 512, CHECK_TIMEOUT_MS = 900_000;
@@ -42,10 +58,60 @@ const KEPT_ENV = ['PATH', 'LANG', 'LC_ALL', 'TERM', 'TMPDIR'];
/** No hook or fsmonitor from the repository's config or the merged tree runs in the git calls around the checks. */
const NO_HOOKS = ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false'];
export const LAND_EXPLANATION = '{ merged_checks, docs_only_skip? } or null, read from the base revision only: under merge: direct, when the base moved past a pin\'s merge base, `land --pin` builds the pin merged onto the base tip in a throwaway worktree (the checkout\'s node_modules linked in) and runs each merged_checks command there (at most 16, 512 characters each, 15 minutes each); it lands only when every one exits 0, and refuses on a conflict (QUEUE_LAND_NOT_CLEAN) or a failure (QUEUE_LAND_MERGED_CHECKS). They are repo commands: land runs them only with --allow-repo-commands (else REPO_COMMANDS_NOT_ALLOWED), never under --dry-run, with PATH and locale as the only environment and a throwaway HOME. null lands a stale base unchecked with a STALE_BASE: warn line. docs_only_skip names merged_checks commands land skips for a pin lib/docs-only.ts calls human docs only (docs/pregate.md#docs-only) and needs min_gstack_version at its own introducing release. merge_commit_paths lists git glob pathspecs (at most 64, 256 characters each, no `..`): a PR that changes one lands as a merge commit instead of a squash, so an eval results PR keeps the commits its run receipts point to (docs/writing-prs.md#the-commit-on-main); it needs min_gstack_version at its own introducing release, and with it merged_checks may be left out. An unknown key under land is a warning, ignored.';
/** The paths in a git directory that decide what programs git runs or where it reads them: config, hooks, commondir, gitdir. */
const GIT_GUARDED = ['config', 'config.worktree', 'hooks', 'commondir', 'gitdir'];
type GitEntry = { mode: number; link?: string; data?: Buffer };
/** The guarded paths: the checkout's `.git`, each git directory's GIT_GUARDED entries, the files in `extra`, and every hop of a guarded symlink. */
function gitTops(root: string, dirs: string[], extra: string[]): string[] {
const tops = [...dirs.flatMap(d => GIT_GUARDED.map(n => path.join(d, n))), ...extra];
for (let p of [...tops]) {
for (let hop = 0; hop < 40; hop++) {
try { p = path.resolve(fs.realpathSync(path.dirname(p)), fs.readlinkSync(p)); } catch { break; }
tops.push(p);
}
}
return [path.join(root, '.git'), ...new Set(tops)];
}
/** Every path under `tops` with its mode (type bits included) and bytes or symlink target; the checkout's `.git` directory is recorded without its contents, and a FIFO, socket or device is never read. */
function gitState(root: string, tops: string[]): Map<string, GitEntry> {
const state = new Map<string, GitEntry>();
const walk = (p: string, deep: boolean) => {
let st: fs.Stats;
try { st = fs.lstatSync(p); } catch { return; }
const entry: GitEntry = { mode: st.mode };
state.set(p, entry);
try {
if (st.isSymbolicLink()) entry.link = fs.readlinkSync(p);
else if (st.isFile()) entry.data = fs.readFileSync(p);
else if (st.isDirectory() && deep) for (const name of fs.readdirSync(p)) walk(path.join(p, name), true);
} catch {}
};
for (const top of tops) walk(top, top !== path.join(root, '.git'));
return state;
}
/** Files outside the git directories that land's later git and gh calls read: every config file git loads in the checkout, the global and XDG git config files (so creating one counts), gh's config and hosts files, and the pinned git and gh. */
function landReadFiles(root: string): string[] {
const home = process.env.HOME || os.homedir();
const xdg = process.env.XDG_CONFIG_HOME || path.join(home, '.config');
const gh = process.env.GH_CONFIG_DIR || path.join(xdg, 'gh');
const origins = git(root, ['config', '--list', '--show-origin', '--name-only']).out.split('\n').map(l => l.split('\t')[0] ?? '').filter(o => o.startsWith('file:')).map(o => path.resolve(root, o.slice(5)));
const tools = (['git', 'gh'] as const).map(t => toolPath(t)).filter(t => path.isAbsolute(t));
return [...origins, ...(process.env.GIT_CONFIG_GLOBAL ? [path.resolve(process.env.GIT_CONFIG_GLOBAL)] : []), path.join(home, '.gitconfig'), path.join(xdg, 'git', 'config'), path.join(gh, 'config.yml'), path.join(gh, 'hosts.yml'), ...tools];
}
/** The guarded paths whose entry `after` differs from `before` (added, removed, retyped, rewritten, repointed or re-moded). */
function changedGitPaths(before: Map<string, GitEntry>, after: Map<string, GitEntry>): string[] {
const same = (a?: GitEntry, b?: GitEntry) => !!a && !!b && a.mode === b.mode && a.link === b.link && (a.data && b.data ? a.data.equals(b.data) : a.data === b.data);
return [...new Set([...before.keys(), ...after.keys()])].filter(p => !same(before.get(p), after.get(p))).sort();
}
export const LAND_EXPLANATION = '{ merged_checks, docs_only_skip? } or null, read from the base revision only: under merge: direct, when the base moved past a pin\'s merge base, `land --pin` builds the pin merged onto the base tip in a fresh clone outside the checkout (its own .git, a copy of the checkout\'s node_modules) and runs each merged_checks command there (at most 16, 512 characters each, 15 minutes each); it lands only when every one exits 0, and refuses on a conflict (QUEUE_LAND_NOT_CLEAN) or a failure (QUEUE_LAND_MERGED_CHECKS). They are repo commands: land runs them only with --allow-repo-commands (else REPO_COMMANDS_NOT_ALLOWED), never under --dry-run, with PATH and locale as the only environment and a throwaway HOME. null lands a stale base unchecked with a STALE_BASE: warn line. docs_only_skip names merged_checks commands land skips for a pin lib/docs-only.ts calls human docs only (docs/pregate.md#docs-only) and needs min_gstack_version at its own introducing release. merge_commit_paths lists git glob pathspecs (at most 64, 256 characters each, no `..`): a PR that changes one lands as a merge commit instead of a squash, so an eval results PR keeps the commits its run receipts point to (docs/writing-prs.md#the-commit-on-main); it needs min_gstack_version at its own introducing release, and with it merged_checks may be left out. merged_ci { workflow, profile } runs CI on the tree that would land, after any merged_checks pass: land pushes the merged commit to the scratch branch gstack-land/<pr>, dispatches the workflow there, waits up to 45 minutes, and lands only when lib/run-evidence.ts accepts that run under the named run profile of the base\'s .gstack/pregate.json with the merged tree as its tested tree (a red run refuses with QUEUE_LAND_MERGED_CHECKS; a run that cannot start, finish or be proved refuses with QUEUE_NOT_READY); it runs on CI, so it needs no --allow-repo-commands, never runs under --dry-run, and the branch is deleted whatever the outcome; with it merged_checks may be left out, and an older gstack ignores it with a warning. An unknown key under land is a warning, ignored.';
/** The keys this gstack reads under land; any other is a warning (lib/ship-policy.ts policyWarnings), never an error. */
export const LAND_KEYS: readonly string[] = ['merged_checks', 'docs_only_skip', 'merge_commit_paths'];
export const LAND_KEYS: readonly string[] = ['merged_checks', 'docs_only_skip', 'merge_commit_paths', 'merged_ci'];
export function landPolicyErrors(raw: unknown): PolicyError[] {
const l = raw as Record<string, unknown> | null;
@@ -53,8 +119,10 @@ export function landPolicyErrors(raw: unknown): PolicyError[] {
const out: PolicyError[] = [];
const paths = l.merge_commit_paths;
if (paths !== undefined && (!Array.isArray(paths) || !paths.length || paths.length > 64 || paths.some(p => typeof p !== 'string' || !p.trim() || p.length > 256 || /[\0\r\n]/.test(p) || p.startsWith('/') || p.split(/[\\/]+/).includes('..')))) out.push({ code: 'POLICY_INVALID', path: 'land.merge_commit_paths', message: 'must list 1 to 64 relative git glob pathspecs of at most 256 characters, with no `..`' });
const ci = l.merged_ci as Record<string, unknown> | undefined;
if (ci !== undefined && (!ci || typeof ci !== 'object' || Array.isArray(ci) || Object.keys(ci).some(k => k !== 'workflow' && k !== 'profile') || typeof ci.workflow !== 'string' || !/^[A-Za-z0-9_.-]+\.ya?ml$/.test(ci.workflow) || typeof ci.profile !== 'string' || !/^[A-Za-z0-9_.\/-]{1,128}$/.test(ci.profile))) out.push({ code: 'POLICY_INVALID', path: 'land.merged_ci', message: 'must be { workflow, profile }: a workflow file name under .github/workflows and a run_profiles name in .gstack/pregate.json' });
const c = l.merged_checks;
if (c === undefined && paths !== undefined && l.docs_only_skip === undefined) return out;
if (c === undefined && (paths !== undefined || ci !== undefined) && l.docs_only_skip === undefined) return out;
if (!Array.isArray(c) || !c.length || c.length > MAX_CHECKS) return [...out, { code: 'POLICY_INVALID', path: 'land.merged_checks', message: `must list 1 to ${MAX_CHECKS} commands` }];
const skip = l.docs_only_skip;
if (skip !== undefined && (!Array.isArray(skip) || skip.some(s => !c.includes(s)) || skip.length >= c.length)) out.push({ code: 'POLICY_INVALID', path: 'land.docs_only_skip', message: 'must list merged_checks commands, leaving at least one to run' });
@@ -65,8 +133,11 @@ export function landPolicyErrors(raw: unknown): PolicyError[] {
return out;
}
/** `setup`: land could not run the checks at all (git failed, or the merged tree's dependencies differ from the linked node_modules): the lane's code is not at fault. */
export type MergedRun = { ok: true; tree: string } | { ok: false; conflict: boolean; setup?: boolean; tree?: string; detail: string };
/** `setup`: land could not run the checks at all (git failed, or the merged tree's dependencies differ from the checkout's node_modules): the lane's code is not at fault. `tampered`: the checks changed a file land's later git or gh calls read, so land holds for a person to inspect. */
export type MergedRun = { ok: true; tree: string; commit: string } | { ok: false; conflict: boolean; setup?: boolean; tampered?: boolean; tree?: string; detail: string };
type MergedFailure = Extract<MergedRun, { ok: false }>;
/** Checkouts where land.merged_checks changed a guarded path: land makes no further git call there, so ship-queue-land-direct skips the lock release. */
export const changedCheckouts = new Set<string>();
const LOCKFILES = ['bun.lock', 'bun.lockb', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
const DEP_KEYS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies', 'workspaces', 'overrides'];
const read = (file: string): string | null => { try { return fs.readFileSync(file, 'utf8'); } catch { return null; } };
@@ -102,47 +173,78 @@ function killStrays(): boolean {
}
const deps = (file: string): string => { try { const p = JSON.parse(read(file) ?? 'null') ?? {}; return JSON.stringify(DEP_KEYS.map(k => p[k] ?? null)); } catch { return 'unreadable'; } };
/** Run `checks` on a throwaway commit of `pin` merged onto `base` (HEAD is that commit), in a worktree of `root` that is always removed, with a scrubbed environment; a check that does not finish (its whole process group is killed), moves HEAD or changes a tracked file fails, and a merged tree whose dependencies differ from the checkout's is refused before any check runs. */
export function runMergedChecks(root: string, base: string, pin: string, checks: string[], timeoutMs = CHECK_TIMEOUT_MS): MergedRun {
/** The pin merged onto `base` as a throwaway commit in `root`: its tree and commit, or the conflict or git failure that stopped it. */
export function mergedCommit(root: string, base: string, pin: string): { ok: true; tree: string; commit: string } | MergedFailure {
const mt = git(root, ['merge-tree', '--write-tree', '--name-only', base, pin]);
const [tree = '', ...rest] = mt.out.split('\n');
if (!mt.ok) return { ok: false, conflict: mt.status === 1, setup: mt.status !== 1, detail: mt.status === 1 ? `the pin conflicts with ${base.slice(0, 12)} in ${rest.slice(0, rest.indexOf('') < 0 ? undefined : rest.indexOf('')).join(', ') || 'files git did not name'}` : `git merge-tree failed: ${mt.err.split('\n')[0]}` };
const who = { GIT_AUTHOR_NAME: 'gstack land', GIT_AUTHOR_EMAIL: 'land@gstack.invalid', GIT_COMMITTER_NAME: 'gstack land', GIT_COMMITTER_EMAIL: 'land@gstack.invalid' };
const commit = git(root, ['commit-tree', tree, '-p', base, '-p', pin, '-m', 'gstack land: merged-tree check'], { ...process.env, ...who });
return commit.ok ? { ok: true, tree, commit: commit.out } : { ok: false, conflict: false, setup: true, tree, detail: `cannot build the merged tree ${tree.slice(0, 12)}: ${commit.err.split('\n')[0]}` };
}
/** Run `checks` on a throwaway commit of `pin` merged onto `base` (HEAD is that commit), in a fresh clone of `root` with a copy of its node_modules, deleted afterwards, with a scrubbed environment; a check that does not finish (its whole process group is killed), moves HEAD or changes a tracked file fails, one that changes a file land's later git or gh calls read fails as tampered, and a merged tree whose dependencies differ from the checkout's is refused before any check runs. */
export function runMergedChecks(root: string, base: string, pin: string, checks: string[], timeoutMs = CHECK_TIMEOUT_MS): MergedRun {
const merged = mergedCommit(root, base, pin);
if (!merged.ok) return merged;
const { tree } = merged;
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-land-merged-'));
const dir = path.join(scratch, 'tree'), home = path.join(scratch, 'home');
fs.mkdirSync(home);
const env: NodeJS.ProcessEnv = { HOME: home, ...Object.fromEntries(KEPT_ENV.filter(k => process.env[k] !== undefined).map(k => [k, process.env[k]])) };
try {
const who = { GIT_AUTHOR_NAME: 'gstack land', GIT_AUTHOR_EMAIL: 'land@gstack.invalid', GIT_COMMITTER_NAME: 'gstack land', GIT_COMMITTER_EMAIL: 'land@gstack.invalid' };
const commit = git(root, ['commit-tree', tree, '-p', base, '-p', pin, '-m', 'gstack land: merged-tree check'], { ...process.env, ...who });
const add = commit.ok ? git(root, [...NO_HOOKS, 'worktree', 'add', '-q', '--detach', dir, commit.out]) : commit;
const clone = git(root, [...NO_HOOKS, 'clone', '-q', '--no-checkout', '--no-hardlinks', '--', root, dir]);
const unlinked = clone.ok ? git(dir, [...NO_HOOKS, 'remote', 'remove', 'origin']) : clone;
const add = unlinked.ok ? git(dir, [...NO_HOOKS, 'checkout', '-q', '--detach', merged.commit]) : unlinked;
if (!add.ok) return { ok: false, conflict: false, setup: true, tree, detail: `cannot build the merged tree ${tree.slice(0, 12)}: ${add.err.split('\n')[0]}` };
const drift = [...LOCKFILES.filter(l => read(path.join(root, l)) !== read(path.join(dir, l))), ...(deps(path.join(root, 'package.json')) !== deps(path.join(dir, 'package.json')) ? ['package.json dependencies'] : [])];
if (drift.length) return { ok: false, conflict: false, setup: true, tree, detail: `the merged tree's ${drift.join(', ')} differ from this checkout's, so its node_modules cannot vouch for the merged tree` };
const modules = path.join(root, 'node_modules');
if (fs.existsSync(modules) && !fs.existsSync(path.join(dir, 'node_modules'))) fs.symlinkSync(modules, path.join(dir, 'node_modules'));
if (fs.existsSync(modules) && !fs.existsSync(path.join(dir, 'node_modules'))) {
try { fs.cpSync(fs.realpathSync(modules), path.join(dir, 'node_modules'), { recursive: true, verbatimSymlinks: true }); }
catch (e) { return { ok: false, conflict: false, setup: true, tree, detail: `cannot copy the checkout's node_modules into the merged tree ${tree.slice(0, 12)}: ${(e as Error).message}` }; }
}
const linux = process.platform === 'linux';
const open = linux ? closeLandProc() : null;
if (open) return { ok: false, conflict: false, setup: true, tree, detail: `cannot close land's /proc environment to the checks (${open}), so they did not run` };
for (const cmd of checks) {
const group = process.platform !== 'win32';
const log = path.join(scratch, 'check.log');
const fd = fs.openSync(log, 'w');
const opts = { cwd: dir, env, stdio: ['ignore', fd, fd] as ['ignore', number, number], timeout: timeoutMs, killSignal: 'SIGKILL' as const, detached: group };
const r = spawnSync('sh', ['-c', cmd], opts);
fs.closeSync(fd);
if (group && r.pid) try { process.kill(-r.pid, 'SIGKILL'); } catch {}
if (linux && !killStrays()) return { ok: false, conflict: false, tree, detail: `\`${cmd}\` left processes running that land could not stop on the merged tree ${tree.slice(0, 12)}` };
if (r.status === 0 && !r.error) continue;
const tail = fs.readFileSync(log, 'utf8').trim().split('\n').slice(-6).join('\n');
return { ok: false, conflict: false, tree, detail: `\`${cmd}\` ${r.error ? `did not finish (${r.error.message})` : `exited ${r.status ?? r.signal}`} on the merged tree ${tree.slice(0, 12)}${tail ? `:\n${tail}` : ''}` };
const gitDirs = [...new Set(git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir', '--git-dir']).out.split('\n').filter(Boolean))];
if (!gitDirs.length) return { ok: false, conflict: false, setup: true, tree, detail: 'cannot find the checkout\'s git directory, so the checks did not run' };
const tops = gitTops(root, gitDirs, landReadFiles(root));
const saved = gitState(root, tops);
process.env.PATH = pinnedFirst();
let failed = '', setup = false;
let touched: string[] = [];
try {
for (const cmd of checks) {
const group = process.platform !== 'win32';
const log = path.join(scratch, 'check.log');
const fd = fs.openSync(log, 'w');
const opts = { cwd: dir, env, stdio: ['ignore', fd, fd] as ['ignore', number, number], timeout: timeoutMs, killSignal: 'SIGKILL' as const, detached: group };
const r = spawnSync('sh', ['-c', cmd], opts);
fs.closeSync(fd);
if (group && r.pid) try { process.kill(-r.pid, 'SIGKILL'); } catch {}
if (linux && !killStrays()) { failed = `\`${cmd}\` left processes running that land could not stop on the merged tree ${tree.slice(0, 12)}`; break; }
if (r.status === 0 && !r.error) continue;
const tail = fs.readFileSync(log, 'utf8').trim().split('\n').slice(-6).join('\n');
failed = `\`${cmd}\` ${r.error ? `did not finish (${r.error.message})` : `exited ${r.status ?? r.signal}`} on the merged tree ${tree.slice(0, 12)}${tail ? `:\n${tail}` : ''}`;
break;
}
if (!failed && git(dir, [...NO_HOOKS, 'rev-parse', 'HEAD'], env).out !== merged.commit) failed = `the checks moved HEAD off the merged commit ${merged.commit.slice(0, 12)}, so it was not the tree they passed`;
const status = failed ? null : git(dir, [...NO_HOOKS, 'status', '--porcelain', '--untracked-files=no'], env);
if (status && !status.ok) { setup = true; failed = `git status failed on the merged tree ${tree.slice(0, 12)}: ${status.err.split('\n')[0]}`; }
else if (status?.out) failed = `the checks changed tracked files on the merged tree ${tree.slice(0, 12)}, so it was not the tree they passed: ${status.out.split('\n').slice(0, 6).join(', ')}`;
if (linux && !killStrays()) failed ||= `git on the merged tree ${tree.slice(0, 12)} left processes running that land could not stop`;
} finally {
touched = changedGitPaths(saved, gitState(root, tops));
if (touched.length) changedCheckouts.add(root);
}
if (git(dir, [...NO_HOOKS, 'rev-parse', 'HEAD']).out !== commit.out) return { ok: false, conflict: false, tree, detail: `the checks moved HEAD off the merged commit ${commit.out.slice(0, 12)}, so it was not the tree they passed` };
const changed = git(dir, [...NO_HOOKS, 'status', '--porcelain', '--untracked-files=no']);
if (!changed.ok) return { ok: false, conflict: false, setup: true, tree, detail: `git status failed on the merged tree ${tree.slice(0, 12)}: ${changed.err.split('\n')[0]}` };
if (changed.out) return { ok: false, conflict: false, tree, detail: `the checks changed tracked files on the merged tree ${tree.slice(0, 12)}, so it was not the tree they passed: ${changed.out.split('\n').slice(0, 6).join(', ')}` };
return { ok: true, tree };
if (touched.length) {
const named = touched.slice(0, 20).map(p => p.startsWith(root + path.sep) ? path.relative(root, p) : p).join(', ') + (touched.length > 20 ? ` and ${touched.length - 20} more` : '');
return { ok: false, conflict: false, tampered: true, tree, detail: `the checks changed ${named}, which land's later git and gh calls read, on the merged tree ${tree.slice(0, 12)}, so land made no further git or gh call and left the land lock held; inspect each path and restore it from a trusted copy (delete a hook the checks added) before any git command in this checkout, then release the lock as the LOCK line says` };
}
if (failed) return { ok: false, conflict: false, setup, tree, detail: failed };
return { ok: true, tree, commit: merged.commit };
} finally {
git(root, [...NO_HOOKS, 'worktree', 'remove', '--force', dir]);
fs.rmSync(scratch, { recursive: true, force: true });
}
}
+95
View File
@@ -0,0 +1,95 @@
/**
* land.merged_ci (docs/ship-policy.md#land-direct): CI on the tree that would land. When the base moved past a pin's
* merge base, the pin's own pull_request runs never tested the merged tree, and land.merged_checks runs only what land's
* machine can afford. So land pushes the merged commit to a scratch branch, gstack-land/<pr>, dispatches the policy's
* workflow there, waits for that run, and lands only when lib/run-evidence.ts verifyRun accepts it under the named run
* profile from the base's .gstack/pregate.json, with the merged commit as its head and the merged tree as its tested
* tree. The scratch branch is deleted whatever the outcome. The run executes on CI runners, so no repo command runs on
* land's machine and it needs no --allow-repo-commands.
*/
import { git, type QueueFailure } from '../crew/lib/ship-queue-gate';
import { repoSlug } from '../crew/lib/ship-queue-train-github';
import { MIN_POLL_MS, pollDelayMs, syncLimitEnv } from './gh-poll';
import { ghRunDeps, runProfileErrors, verifyRun, type ApiRun, type RunProfile } from './run-evidence';
import type { QueueContext } from './ship-queue';
export const CI_TIMEOUT_MS = 45 * 60_000;
export interface MergedCi { workflow: string; profile: string }
export interface CiDeps {
/** Push the commit to the branch, replacing a leftover one; an error message, or null. */
push(commit: string, branch: string): string | null;
remove(branch: string): void;
dispatch(workflow: string, branch: string): string | null;
/** The workflow's workflow_dispatch runs at the commit, newest first. */
runsAt(workflow: string, commit: string): ApiRun[];
run(id: number): ApiRun;
verify(id: number): { ok: true; head: string; tree: string } | { ok: false; detail: string };
sleep(ms: number): void;
now(): number;
url(id: number): string;
}
export type CiResult = { ok: true; line: string } | { ok: false; red: boolean; detail: string };
/** One dispatch of `ci.workflow` on the merged commit and its verdict; red when the run itself failed, else land could not run or prove it. */
export function runMergedCi(deps: CiDeps, o: { pr: string; commit: string; tree: string; ci: MergedCi; timeoutMs?: number }): CiResult {
const branch = `gstack-land/${o.pr}`;
const pushed = deps.push(o.commit, branch);
if (pushed) return { ok: false, red: false, detail: `cannot push the merged commit ${o.commit.slice(0, 12)} to ${branch}: ${pushed}` };
try {
const started = deps.now();
const sent = deps.dispatch(o.ci.workflow, branch);
if (sent) return { ok: false, red: false, detail: `gh workflow run ${o.ci.workflow} --ref ${branch} failed: ${sent}` };
let run: ApiRun | undefined;
for (;;) {
run = run ? deps.run(run.id) : deps.runsAt(o.ci.workflow, o.commit)[0];
if (run?.status === 'completed') break;
if (deps.now() - started >= (o.timeoutMs ?? CI_TIMEOUT_MS)) return { ok: false, red: false, detail: run ? `${o.ci.workflow} run ${deps.url(run.id)} is still ${run.status} after ${Math.round((deps.now() - started) / 60_000)} minutes` : `no ${o.ci.workflow} run appeared on ${branch} at ${o.commit.slice(0, 12)}` };
deps.sleep(pollDelayMs(MIN_POLL_MS));
}
const at = `${o.ci.workflow} run ${deps.url(run.id)} on the merged tree ${o.tree.slice(0, 12)}`;
if (run.conclusion !== 'success') return { ok: false, red: true, detail: `${at} concluded ${run.conclusion ?? 'unknown'}` };
const v = deps.verify(run.id);
if (!v.ok) return { ok: false, red: false, detail: `${at} passed, but it does not prove the tree under ${o.ci.profile}: ${v.detail}` };
if (v.head !== o.commit || v.tree !== o.tree) return { ok: false, red: false, detail: `${at} tested ${v.head.slice(0, 12)} (tree ${v.tree.slice(0, 12)}), not the merged commit ${o.commit.slice(0, 12)}` };
return { ok: true, line: `MERGED_CI: pass ${at} (profile ${o.ci.profile})` };
} finally {
deps.remove(branch);
}
}
/** land's real dependencies: git on the checkout, gh through the queue context, and the run profile read from the base tip. */
export function ghCiDeps(ctx: QueueContext, remote: string, tip: string, ci: MergedCi): CiDeps | { error: string } {
const root = ctx.repoRoot;
const slug = repoSlug(ctx);
if (!slug) return { error: 'cannot read the repository name through gh' };
let profile: RunProfile | undefined;
try { profile = JSON.parse(git(root, ['show', `${tip}:.gstack/pregate.json`]).out).run_profiles?.[ci.profile]; } catch {}
if (!profile || runProfileErrors({ [ci.profile]: profile }, undefined).length) return { error: `.gstack/pregate.json at ${tip.slice(0, 12)} has no valid run profile ${ci.profile}` };
const evidence = ghRunDeps(slug, root);
const api = <T>(p: string): T => { const r = ctx.gh(['api', p]); if (!r.ok) throw new Error((r.err ?? r.out).trim().slice(0, 160)); return JSON.parse(r.out) as T; };
return {
push: (commit, branch) => { const r = git(root, ['push', '-q', remote, `+${commit}:refs/heads/${branch}`]); return r.ok ? null : r.err.split('\n')[0] || 'git push failed'; },
remove: branch => { git(root, ['push', '-q', remote, `:refs/heads/${branch}`]); },
dispatch: (workflow, branch) => { const r = ctx.gh(['workflow', 'run', workflow, '--ref', branch]); return r.ok ? null : (r.err ?? r.out).trim().slice(0, 160) || 'no output'; },
runsAt: (workflow, commit) => { try { return api<{ workflow_runs?: ApiRun[] }>(`repos/${slug}/actions/workflows/${workflow}/runs?head_sha=${commit}&event=workflow_dispatch&per_page=20`).workflow_runs ?? []; } catch { return []; } },
run: id => { try { return api<ApiRun>(`repos/${slug}/actions/runs/${id}`); } catch { return { id, run_attempt: 1, status: 'unknown', conclusion: null, event: 'workflow_dispatch', head_sha: '' }; } },
verify: id => {
const v = verifyRun(evidence, { repo: slug, runRef: String(id), profileName: ci.profile, profile: profile!, now: new Date() });
return v.ok ? { ok: true, head: v.evidence.head_sha, tree: v.evidence.tree } : { ok: false, detail: `${v.reason}: ${v.detail}` };
},
sleep: syncLimitEnv.sleep,
now: () => Date.now(),
url: id => `https://github.com/${slug}/actions/runs/${id}`,
};
}
/** The land step: the dispatch, its verdict and the failure land refuses with. */
export function landMergedCi(ctx: QueueContext, o: { remote: string; tip: string; pr: string; pin: string; commit: string; tree: string; ci: MergedCi; moved: string }): { line: string } | { failure: QueueFailure } {
const deps = ghCiDeps(ctx, o.remote, o.tip, o.ci);
if ('error' in deps) return { failure: { code: 'QUEUE_NOT_READY', message: `${o.moved}, and land cannot run land.merged_ci: ${deps.error}; nothing merged`, fix: 'fix what the message names, then rerun land' } };
const r = runMergedCi(deps, o);
if (r.ok) return { line: r.line };
if (r.red) return { failure: { code: 'QUEUE_LAND_MERGED_CHECKS', message: `${o.moved}; on the pin merged onto it, ${r.detail}`, fix: `read the failed job in that run; a flaky case gets one rerun of land; a real failure goes back to the lane, which merges the base into the branch, fixes it, runs /ship and gstack-ship-queue ready --pr ${o.pr} at the new head` } };
return { failure: { code: 'QUEUE_NOT_READY', message: `${o.moved}, and land.merged_ci could not run or prove CI on the pin merged onto it: ${r.detail}; nothing merged`, fix: `fix what the message names, then rerun gstack-ship-queue land --pr ${o.pr} --pin ${o.pin}` } };
}
+28 -10
View File
@@ -18,13 +18,14 @@
*/
import { MIN_POLL_MS, pollDelayMs } from './gh-poll';
import { mergedChecksFor } from './land-docs-only';
import { runMergedChecks } from './land-merged-checks';
import { landMergedCi } from './land-merged-ci';
import { changedCheckouts, mergedCommit, runMergedChecks, type MergedRun } from './land-merged-checks';
import { landPlan } from './plan-record';
import { classifyRelease, RELEASE_BRANCH } from './release-stamp';
import { versionAtRef } from './restamp';
import type { ShipPolicy } from './ship-policy';
import { ciAtHead, loadBasePolicy, type QueueContext, type StepOutput } from './ship-queue';
import { git, type QueueFailure } from '../crew/lib/ship-queue-gate';
import { git, queueHooksOff, type QueueFailure } from '../crew/lib/ship-queue-gate';
import { acquireLandLock, lockLabel, ownsLock, readLock, type HeldLandLock, type LandLock } from '../crew/lib/ship-queue-land-lock';
import * as os from 'node:os';
import { activeFreeze, loadReady, persist, rebuildFromNotes, repoIdentity, type FreezeRecord } from '../crew/lib/ship-queue-train-record';
@@ -159,6 +160,7 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput {
const run = 'none';
const now = o.now ?? (() => new Date());
const fail = (lines: string[], failure: QueueFailure): StepOutput => ({ ok: false, lines, failure, run });
queueHooksOff();
if (!git(root, ['fetch', '-q', 'origin', ctx.base]).ok) return fail([], { code: 'QUEUE_NOT_READY', message: `cannot fetch origin/${ctx.base}; land reads the policy and the required checks from the current base`, fix: 'fix the fetch, then rerun land' });
const loaded = loadBasePolicy(ctx);
if ('message' in loaded) return fail([], loaded);
@@ -172,6 +174,7 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput {
if (info.baseRefName && info.baseRefName !== ctx.base) return fail(lines, { code: 'QUEUE_NOT_READY', message: `#${o.pr} targets ${info.baseRefName}, not ${ctx.base}`, fix: `retarget it to ${ctx.base}, or land its parent first` });
const remote = ctx.remote ?? 'origin';
const journal = `land-pin:${o.pin}`;
const unlock = `LOCK: warn land.merged_checks changed the checkout's git directory, so land pushed no lock release and the land lock stays held; once every path it names is restored from a trusted copy, release the lock without running the checks: gstack-ship-queue land --pr ${o.pr} --pin ${o.pin} (without --allow-repo-commands)`;
const takeLock = () => acquireLandLock({
root, remote, holder: `${os.hostname()}:${process.pid}`, owner: { pr: o.pr }, journal, now, phase: () => 'merging', breakLock: o.breakLock,
takeover: (held: LandLock) => !held.train && held.pr === o.pr && held.journal.startsWith('land-pin:') ? `LOCK: taking over #${o.pr}'s land lock that an earlier land --pin run left (${held.journal}, since ${held.started_at})` : null,
@@ -180,6 +183,7 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput {
lines.push(`#${o.pr} is already merged as ${info.mergeCommit!.oid.slice(0, 12)}; checking the tree`);
if (o.dryRun) return { ok: true, run, lines: [...lines, 'DRY-RUN: nothing verified (a rerun without --dry-run runs the tree check and writes the land note)'] };
const out = verifyMerge(ctx, root, o.pr, o.pin, info.mergeCommit!.oid, lines, run, now(), RELEASE_BRANCH.test(info.headRefName) ? 'pin-parent' : undefined, { checks: mergedChecksFor(root, policy.land, `origin/${ctx.base}`, o.pin), allow: o.allowRepoCommands });
if (changedCheckouts.has(root)) return { ...out, lines: [...out.lines, unlock] };
const left = readLock(root, remote);
if (left.state !== 'held' || !ownsLock(left.lock, { pr: o.pr }, journal)) return out;
const got = takeLock();
@@ -255,14 +259,27 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput {
if (staleRelease) return fail(lines, staleRelease);
if (mergeBase !== tip) {
const moved = `origin/${ctx.base} moved to ${tip.slice(0, 12)} since the pin's merge base ${mergeBase.slice(0, 12)}, so the checks at the pin never ran on the tree that would land`;
if (!checks.length) lines.push(`STALE_BASE: warn ${moved}; no land.merged_checks configured, so land merges it untested`);
else if (o.dryRun) lines.push(`DRY-RUN: land.merged_checks not run (repo commands never run under --dry-run); a real land with --allow-repo-commands runs ${checks.length} on the pin merged onto ${tip.slice(0, 12)}`);
else if (!o.allowRepoCommands) return fail(lines, { code: 'REPO_COMMANDS_NOT_ALLOWED', message: `${moved}, so land must run land.merged_checks on the pin merged onto it; they are repo commands (the merged tree's package.json decides what they run), so nothing ran and nothing merged`, fix: `rerun gstack-ship-queue land --pr ${o.pr} --pin ${o.pin} --allow-repo-commands` });
const ci = current.policy.land?.merged_ci;
const refuse = (mc: Extract<MergedRun, { ok: false }>): StepOutput => {
if (mc.setup) return fail(lines, { code: 'QUEUE_NOT_READY', message: `${moved}, and land could not run land.merged_checks on the pin merged onto it: ${mc.detail}; nothing merged`, fix: `if the checkout is the problem, fix it and rerun land; if the dependencies changed, the lane merges origin/${ctx.base} into the branch, waits for the required checks, runs /ship and ready at the new head` });
if (mc.conflict) return fail(lines, { code: 'QUEUE_LAND_NOT_CLEAN', message: `${moved}: ${mc.detail}`, fix: `the lane merges origin/${ctx.base} into the branch, resolves, runs /ship and ready at the new head` });
if (mc.tampered) return fail(lines, { code: 'QUEUE_LAND_MERGED_CHECKS', message: `${moved}; on the pin merged onto it, ${mc.detail}`, fix: 'hold and inspect: a person restores every path named from a trusted copy before any git command in this checkout and releases the land lock as the LOCK line says; nothing goes back to the lane until then, and the PR does not land until its checks are understood' });
return fail(lines, { code: 'QUEUE_LAND_MERGED_CHECKS', message: `${moved}; on the pin merged onto it, ${mc.detail}`, fix: `merge the base into the branch (git merge origin/${ctx.base}), fix what the failing check names, push, wait for the required checks at the new head, run /ship and gstack-ship-queue ready --pr ${o.pr} there, then land the new pin` });
};
if (!checks.length && !ci) lines.push(`STALE_BASE: warn ${moved}; no land.merged_checks configured, so land merges it untested`);
else if (o.dryRun) {
if (checks.length) lines.push(`DRY-RUN: land.merged_checks not run (repo commands never run under --dry-run); a real land with --allow-repo-commands runs ${checks.length} on the pin merged onto ${tip.slice(0, 12)}`);
if (ci) lines.push(`DRY-RUN: land.merged_ci not dispatched; a real land runs ${ci.workflow} on the pin merged onto ${tip.slice(0, 12)} and waits for it`);
} else if (checks.length && !o.allowRepoCommands) return fail(lines, { code: 'REPO_COMMANDS_NOT_ALLOWED', message: `${moved}, so land must run land.merged_checks on the pin merged onto it; they are repo commands (the merged tree's package.json decides what they run), so nothing ran and nothing merged`, fix: `rerun gstack-ship-queue land --pr ${o.pr} --pin ${o.pin} --allow-repo-commands` });
else {
const mc = runMergedChecks(root, tip, o.pin, checks);
if (!mc.ok && mc.setup) return fail(lines, { code: 'QUEUE_NOT_READY', message: `${moved}, and land could not run land.merged_checks on the pin merged onto it: ${mc.detail}; nothing merged`, fix: `if the checkout is the problem, fix it and rerun land; if the dependencies changed, the lane merges origin/${ctx.base} into the branch, waits for the required checks, runs /ship and ready at the new head` });
if (!mc.ok) return fail(lines, mc.conflict ? { code: 'QUEUE_LAND_NOT_CLEAN', message: `${moved}: ${mc.detail}`, fix: `the lane merges origin/${ctx.base} into the branch, resolves, runs /ship and ready at the new head` } : { code: 'QUEUE_LAND_MERGED_CHECKS', message: `${moved}; on the pin merged onto it, ${mc.detail}`, fix: `merge the base into the branch (git merge origin/${ctx.base}), fix what the failing check names, push, wait for the required checks at the new head, run /ship and gstack-ship-queue ready --pr ${o.pr} there, then land the new pin` });
lines.push(`MERGED_CHECKS: pass tree=${mc.tree} base=${tip} pin=${o.pin.slice(0, 12)} checks: ${checks.join('; ')}`);
const built = checks.length ? runMergedChecks(root, tip, o.pin, checks) : mergedCommit(root, tip, o.pin);
if (!built.ok) return refuse(built);
if (checks.length) lines.push(`MERGED_CHECKS: pass tree=${built.tree} base=${tip} pin=${o.pin.slice(0, 12)} checks: ${checks.join('; ')}`);
if (ci) {
const r = landMergedCi(ctx, { remote, tip, pr: o.pr, pin: o.pin, commit: built.commit, tree: built.tree, ci, moved });
if ('failure' in r) return fail(lines, r.failure);
lines.push(r.line);
}
}
}
const msg = landMessage(root, { pr: o.pr, title: info.title ?? '', prBody: info.body ?? '', mergeBase, pin: o.pin, tip, policy, override: o.body ?? (release ? sectionText(info.body ?? '', 'Release notes') || undefined : undefined) });
@@ -298,6 +315,7 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput {
};
let out: StepOutput;
let released = true;
try { out = locked(); } finally { if (held) released = held.release(); }
try { out = locked(); } finally { if (held) released = !changedCheckouts.has(root) && held.release(); }
if (changedCheckouts.has(root)) return { ...out, lines: [...out.lines, unlock] };
return released ? out : { ...out, lines: [...out.lines, `LOCK: warn the land lock release push failed, so the lock stays held; rerun gstack-ship-queue land --pr ${o.pr} --pin ${o.pin} to resume and release it`] };
}
+37
View File
@@ -0,0 +1,37 @@
/**
* The absolute git and gh a gstack process runs, resolved once per PATH value, at its first git or gh call (GST-1766).
* `gstack-ship-queue land` runs repo commands (land.merged_checks) as its own user between its own git and gh calls, and
* a check can drop a `git` or `gh` into a writable directory early on PATH; a name looked up again after the checks
* would run that file with land's environment. lib/land-merged-checks.ts records the resolved files before the checks
* and refuses when one changed, and before the checks it puts the pinned files' directories first on its own PATH, so
* every later `git` or `gh` any module starts by name runs them. gh runs `git` by name, so its PATH starts with
* the pinned git's directory.
*/
import * as path from 'node:path';
const pinned = new Map<string, string>();
/** The file `name` resolves to on PATH the first time this process asks; the bare name when PATH has none, so the spawn fails as before. */
export function toolPath(name: 'git' | 'gh', PATH = process.env.PATH ?? ''): string {
const key = `${name}\0${PATH}`;
let found = pinned.get(key);
if (found === undefined) {
found = Bun.which(name, { PATH }) ?? name;
pinned.set(key, found);
}
return found;
}
/** PATH with the pinned git's directory first, for a child such as gh that runs `git` by name. */
export function pathWithGit(PATH = process.env.PATH ?? ''): string {
const git = toolPath('git', PATH);
return path.isAbsolute(git) ? `${path.dirname(git)}${path.delimiter}${PATH}` : PATH;
}
/** PATH with the pinned git's and gh's directories first, with those files pinned for it too: land sets it on its own process before the checks, so a module that starts `git` or `gh` by name after them runs the files pinned before them. */
export function pinnedFirst(PATH = process.env.PATH ?? ''): string {
const files = (['git', 'gh'] as const).map(t => [t, toolPath(t, PATH)] as const);
const next = [...new Set(files.filter(([, f]) => path.isAbsolute(f)).map(([, f]) => path.dirname(f))), PATH].join(path.delimiter);
for (const [t, f] of files) pinned.set(`${t}\0${next}`, f);
return next;
}