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

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

Garry Tanabdc09dad16a
diff --git a/.gstack/ship-policy.json b/.gstack/ship-policy.json
index 0209af766..807e2b39b 100644
--- a/.gstack/ship-policy.json
+++ b/.gstack/ship-policy.json
@@ -21,7 +21,8 @@
"bun run typecheck",
"bun run gen:skill-docs --host all && test -z \"$(git status --porcelain -- . ':(exclude)node_modules')\"",
"bun run scripts/test-free-shards.ts --files-from test/land-merged-checks.txt --wall-timeout 600"
- ]
+ ],
+ "merged_ci": { "workflow": "free-tests.yml", "profile": "ci-reuse/free-tests" }
},
"release_gate": { "cadence_hours": 8, "gate_workflow": "evals.yml", "branch": "main", "stable_ref": "stable", "check_name": "main-backstop", "on_red": "hold-release", "bisect_spend_cap_usd": 80 },
"min_gstack_version": "1.96.0.0"
diff --git a/changelog.d/capy-keep-lands-merged-checks.md b/changelog.d/capy-keep-lands-merged-checks.md
new file mode 100644
index 000000000..f8560730d
--- /dev/null
+++ b/changelog.d/capy-keep-lands-merged-checks.md
@@ -0,0 +1,6 @@
+---
+bump: minor
+important: security
+---
+- **`gstack-ship-queue land` runs `land.merged_checks` in a fresh clone and stops when a check touches anything land's later git or gh calls read.** The merged-tree checks now run in a clone outside the checkout, with its own `.git` and a copy of `node_modules`, so what a check writes to its hooks, config or modules is thrown away with the clone. Before the checks, land pins the absolute `git` and `gh` it runs and puts their directories first on its own `PATH`, and it records the checkout's git config, hooks, `commondir` and `gitdir` files and `.git`, every config file git loads there (includes and the global file among them), gh's config and hosts files, the pinned binaries, and every symlink hop among them. When a check changed any of them, land refuses with `QUEUE_LAND_MERGED_CHECKS` naming each path and a hold-and-inspect fix, makes no further git or gh call and leaves the land lock held; after restoring the named paths, `gstack-ship-queue land --pr <n> --pin <sha>` without `--allow-repo-commands` releases the lock without running the checks. Every git call `gstack-ship-queue land` makes runs with `core.hooksPath=/dev/null` and `core.fsmonitor=false`; other queue commands keep the checkout's hooks. (GST-1747, GST-1766)
+- **`gstack-ship-queue land` can run full CI on the merged tree before it lands a PR whose base moved.** A new `land.merged_ci` key (`{ workflow, profile }`) makes land push the PR merged onto main's tip to a scratch branch, dispatch that workflow there, wait, and land only when the run passes the named run profile with the merged tree as its tested tree; a red run refuses with `QUEUE_LAND_MERGED_CHECKS`. gstack's own policy now runs the whole free suite this way, so no PR reaches main on a base its tests never saw. (GST-3303)
diff --git a/crew/lib/ship-queue-gate.ts b/crew/lib/ship-queue-gate.ts
index 586963710..f1b9a7b0e 100644
--- a/crew/lib/ship-queue-gate.ts
+++ b/crew/lib/ship-queue-gate.ts
@@ -24,6 +24,7 @@ import { mergeChangelogs } from '../../lib/changelog-check';
import { ensureTmpExcluded, restamp, versionFiles } from '../../lib/restamp';
import type { ResultCodeName } from '../../lib/result-codes';
import type { ShipPolicy } from '../../lib/ship-policy';
+import { toolPath } from '../../lib/tool-path';
export const QUEUE_DIR_REL = '.gstack/tmp/ship-queue';
export const GATE_AHEAD_DIR_REL = `${QUEUE_DIR_REL}/gate-ahead`;
@@ -39,8 +40,15 @@ export interface QueueFailure { code: ResultCodeName; message: string; fix?: str
export function sha256(buf: Buffer | string): string { return createHash('sha256').update(buf).digest('hex'); }
+let hooksOff = false;
+/** land calls this first: none of its git calls runs a hook or fsmonitor, because land.merged_checks are repo commands that can write where the checkout's hooks live (lib/land-merged-checks.ts). Other queue commands keep the checkout's hooks, the managed pre-push guard among them. */
+export function queueHooksOff(): void { hooksOff = true; }
+
export function git(cwd: string, args: string[], env?: NodeJS.ProcessEnv, input?: string | Buffer): { ok: boolean; out: string; err: string; status: number | null } {
- const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 120_000, env: env ?? process.env, input, maxBuffer: 64 * 1024 * 1024 });
+ const base = env ?? process.env;
+ const n = Number(base.GIT_CONFIG_COUNT) || 0;
+ const noHooks = hooksOff ? { GIT_CONFIG_COUNT: String(n + 2), [`GIT_CONFIG_KEY_${n}`]: 'core.hooksPath', [`GIT_CONFIG_VALUE_${n}`]: '/dev/null', [`GIT_CONFIG_KEY_${n + 1}`]: 'core.fsmonitor', [`GIT_CONFIG_VALUE_${n + 1}`]: 'false' } : {};
+ const r = spawnSync(toolPath('git', base.PATH), args, { cwd, encoding: 'utf8', timeout: 120_000, env: { ...base, ...noHooks }, input, maxBuffer: 64 * 1024 * 1024 });
return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: (r.stderr ?? '').trim(), status: r.status };
}
diff --git a/docs/ship-policy.md b/docs/ship-policy.md
index 3152f777d..161b2b1f4 100644
--- a/docs/ship-policy.md
+++ b/docs/ship-policy.md
@@ -81,7 +81,7 @@ branch that changes the policy.
| `docs` | `{ caps: [{ path, max_bytes }] }` or `null` | `null` | Documentation files with a byte cap. `/ship` Step 14.5 runs `gstack-ship-receipt docs-caps --base <base>` (the caps come from `origin/<base>`'s policy, never the branch's copy; `--policy <file>` is for a repository bootstrapping its policy) before the verification gate and prints one `DOCS_CAP: <path> <bytes>/<max> ok\|over` line per cap; any `over` (an absent file counts) exits 1 and blocks the ship until the file is trimmed or the cap raised on the base branch (`DOCS_AUDIT_BLOCKED`). At most 64 caps, each path contained. See [the ship receipt](#ship-receipt). Needs `min_gstack_version`. |
| `train` | `{ gate_workflow, free_workflow, full_gate_check, record_artifact, max_size, fill_hours, screen_selection, trial_reservation_usd, land? }`, `{ gates, land, max_size, fill_hours }` or `null` | `null` | Turns on [merge trains](#run-a-merge-train), read from the base revision only. Every field is required and an unknown field is `POLICY_INVALID`: `max_size` 1 to 6, `fill_hours` above 0 and at most 24, `screen_selection` `gstack-paid` \| `none`, `trial_reservation_usd` above 0 and at most 100. A block with `gates` ([any repository](#train-gates)) takes `max_size` 1 to 5 and needs `min_gstack_version` at least `TRAIN_GATES_KEY_VERSION`. `null` keeps the per-PR queue exactly as it is. Needs `min_gstack_version`. |
| `merge` | `train` \| `direct` | `train` | `direct` lands each READY PR at its own green head with [`land --pr <n> --pin <sha>`](#land-direct): no train and no stamp commit, and `train build` refuses. A PR then leaves VERSION, the `package.json` version and the CHANGELOG at its merge base, and the release sets them. Needs `changelog_fragments`, and the stamping `land --pr <n>` refuses under it. `train` keeps merge trains. Read from the base revision only. Needs `min_gstack_version`. |
-| `land` | `{ merged_checks?, docs_only_skip?, merge_commit_paths? }` or `null` | `null` | Under `merge: direct`, the shell commands (1 to 16, one line of at most 512 characters each, 15 minutes each) [`land --pin`](#land-direct) runs on the pin merged onto the base tip when the base moved past the pin's merge base; it lands only when every one exits 0. They are repo commands, so land runs them only with `--allow-repo-commands`, never under `--dry-run`. `null` lands a stale base untested with a `STALE_BASE: warn` line. `docs_only_skip` lists `merged_checks` commands to skip for a docs-only pin ([pregate.md](pregate.md#docs-only)) and needs `min_gstack_version` at its own release (`LAND_DOCS_ONLY_SKIP_KEY_VERSION`), because older releases refuse it. `merge_commit_paths` (1 to 64 git glob pathspecs, no `..`) makes every land form keep a merge commit, with the plain subject and body, for a PR that changes a matching path, such as an eval results PR whose run records point to its own commits; with it, `merged_checks` may be left out, and it needs `min_gstack_version` at its own release (`LAND_MERGE_COMMIT_PATHS_KEY_VERSION`). Any other key under `land` is a warning, ignored. Read from the base revision only. Needs `min_gstack_version`. |
+| `land` | `{ merged_checks?, docs_only_skip?, merge_commit_paths?, merged_ci? }` or `null` | `null` | Under `merge: direct`, the shell commands (1 to 16, one line of at most 512 characters each, 15 minutes each) [`land --pin`](#land-direct) runs on the pin merged onto the base tip when the base moved past the pin's merge base; it lands only when every one exits 0. They are repo commands, so land runs them only with `--allow-repo-commands`, never under `--dry-run`. `null` lands a stale base untested with a `STALE_BASE: warn` line. `docs_only_skip` lists `merged_checks` commands to skip for a docs-only pin ([pregate.md](pregate.md#docs-only)) and needs `min_gstack_version` at its own release (`LAND_DOCS_ONLY_SKIP_KEY_VERSION`), because older releases refuse it. `merge_commit_paths` (1 to 64 git glob pathspecs, no `..`) makes every land form keep a merge commit, with the plain subject and body, for a PR that changes a matching path, such as an eval results PR whose run records point to its own commits; with it, `merged_checks` may be left out, and it needs `min_gstack_version` at its own release (`LAND_MERGE_COMMIT_PATHS_KEY_VERSION`). `merged_ci` (`{ workflow, profile }`) dispatches that workflow on the merged commit after any `merged_checks` pass and lands only when its run passes the named run profile of `.gstack/pregate.json` ([land --pin](#land-direct)); with it, `merged_checks` may be left out, and an older gstack ignores it with a warning. Any other key under `land` is a warning, ignored. Read from the base revision only. Needs `min_gstack_version`. |
| `docs_only` | `{ allow, deny?, tests? }` or `null` | `null` | Human-docs paths beyond `README.md`, `docs/**.md` and `changelog.d/*.md` for the [docs-only class](pregate.md#repo-docs-paths) (`{ "allow": ["wiki/board/**.md"] }`). `allow` (1 to 16) takes narrow Markdown globs: each ends in `.md`, starts with a literal directory or file name, and passes through no hidden, code, test or agent directory; `**`, `*`, `*.md` and patterns naming agent files are `POLICY_INVALID` with an example of a narrow one. `deny` (up to 64 globs) removes paths, built-in ones included. `tests` (up to 16 test files) are the repository's checks for those directories: the docs lane runs them, and a non-prose file that reads an allowed directory refuses the class unless it is tied to one; a listed test missing from the branch refuses it too. The built-in deny list always wins. Any other key under `docs_only` is a warning, and the classifier then ignores `allow`. Read from the base revision only; a pull request that edits this file is never docs-only. Needs `min_gstack_version`. |
| `release_gate` | `{ cadence_hours, gate_workflow, branch, stable_ref, check_name, on_red, bisect_spend_cap_usd }` or `null` | `null` | One full paid gate on main every `cadence_hours` (8 to 168) instead of the per-push main backstop, feeding the stable release; see [release_gate](#release-gate). Every field is required: `on_red` is `hold-release`, `bisect_spend_cap_usd` 0 to 500 (0 skips the bisect). `null` keeps the per-push backstop. Needs `min_gstack_version`. |
| `bookkeeping` | glob list | `[]` | <a id="bookkeeping"></a>Root-anchored globs of bookkeeping tables a verify or ratchet step rewrites (size baselines, serial lists, limits), each ending in `.tsv`, `.csv` or `.txt` and never under `.gstack/` or `.github/` (`["scripts/*-baseline.tsv"]`). A matching file changed at most 20 lines after review binds, first touched or not, takes finish's [one scoped reader](review-policy.md#bounded-post-review-edits) instead of Steps 5–11.5; the reader still reads every changed row. Read from the base revision only. Needs `min_gstack_version`. |
@@ -2965,14 +2965,15 @@ release-file rows):
| GitHub reports the PR `MERGEABLE` and `CLEAN` | [`QUEUE_LAND_NOT_CLEAN`](troubleshooting.md#queue-land-not-clean) |
| land takes the land lock (`land-pin:<pin>` journal, phase `merging`) and re-fetches `origin/main`; it takes over a lock an earlier `land --pin` run of the same PR left, and `--break-lock` breaks another lander's stale lock under the usual rules | `QUEUE_LAND_LOCKED`, `QUEUE_NOT_READY` |
| when the base moved past the pin's merge base and the base policy lists `land.merged_checks`: `--allow-repo-commands` was passed, the pin merges onto the tip without a conflict, and every command passes on that merged tree | [`REPO_COMMANDS_NOT_ALLOWED`](troubleshooting.md#repo-commands-not-allowed), [`QUEUE_LAND_NOT_CLEAN`](troubleshooting.md#queue-land-not-clean), [`QUEUE_LAND_MERGED_CHECKS`](troubleshooting.md#queue-land-merged-checks) |
+| when the base moved past the pin's merge base and the base policy sets `land.merged_ci`: the workflow's run on the merged commit is green, and `lib/run-evidence.ts` accepts it under the named run profile with the merged tree as its tested tree | [`QUEUE_LAND_MERGED_CHECKS`](troubleshooting.md#queue-land-merged-checks) (a red run), `QUEUE_NOT_READY` |
Release outputs (the agents digest) are checked by the Version Gate, which must
be green at the pin: it accepts an output only when it equals what the release
tool generates at the merge base's VERSION. A green PR merged onto newer
commits can still break main (#3886 pushed ship/DRIVER.md past its size cap
that way). So when the base moved, land builds the pin merged onto the tip of
-`origin/main` in a throwaway worktree (the checkout's `node_modules` linked
-in), runs each `land.merged_checks` command there in order, and prints
+`origin/main` in a fresh clone outside the checkout, with its own `.git` and a
+copy of the checkout's `node_modules`, runs each `land.merged_checks` command there in order, and prints
`MERGED_CHECKS: pass tree=<tree> base=<tip> pin=<pin> checks: …`. The
commands are repo commands: the merged tree's `package.json` decides what
`bun run` does, so the PR controls them. Land runs them only with
@@ -2992,12 +2993,35 @@ land's starting environment to a same-user process. A check that moves HEAD
off the merged commit fails. Land re-reads the base policy after the locked
fetch, so a `land.merged_checks` that main gained meanwhile applies. When the
merged tree's lockfile or `package.json` dependencies differ from the
-checkout's, the linked `node_modules` can't vouch for it: land refuses with
-`QUEUE_NOT_READY` before any check runs, and the lane merges main and re-ships. It doesn't sandbox
-the filesystem: a command can still write the checkout's `.git` (the worktree
-shares it) and the linked `node_modules`, and read anything the user can (other
-processes' environments, credential files), so pass the flag only for a base
-policy and PRs you trust to run. A list such
+checkout's, the copied `node_modules` can't vouch for it: land refuses with
+`QUEUE_NOT_READY` before any check runs, and the lane merges main and re-ships.
+What a check writes in the clone (its `.git`, hooks, config or `node_modules`)
+stays there, and land deletes the clone afterward. A check still runs as
+land's user, so it can write outside the clone by absolute path, to files
+land's later git and gh calls read with land's full environment. So before the
+checks land pins the absolute paths of `git` and `gh` (`lib/tool-path.ts`) and puts
+their directories first on its own `PATH`, so a `git` a check drops earlier on
+`PATH` never runs, and it records 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, plus the global and XDG files when absent),
+gh's `config.yml` and `hosts.yml`, the pinned `git` and `gh` files, and every hop of
+a symlink among them. When a check changed or added any of them, land
+restores nothing: it refuses with `QUEUE_LAND_MERGED_CHECKS` naming each path,
+makes no further git or gh call and leaves the land lock held. Inspect each
+named path and restore it from a trusted copy (delete a hook the checks
+added), then release the lock without running the checks with
+`gstack-ship-queue land --pr <n> --pin <sha>` (no `--allow-repo-commands`: it
+refuses with `REPO_COMMANDS_NOT_ALLOWED` and releases the lock). Land's own git
+calls in the clone run with the checks' environment, and no git call
+`gstack-ship-queue land` makes runs a hook or fsmonitor. That includes the managed
+pre-push guard: land pushes only the lock and notes it writes and, under
+`land.merged_ci`, the merged commit of commits that were already pushed, and a
+hook run after the checks is the opening this closes. It doesn't otherwise
+sandbox the filesystem: a command can still write the checkout's other files
+and read anything the user can (other processes' environments, credential
+files), so pass the flag only for a base policy and PRs you trust to
+run. A list such
as typecheck plus the size ratchets takes about two minutes, against a main
merge, a CI round and a new receipt per PR. gstack's own policy runs
typecheck, the generated-docs freshness check, and the size and budget guards
@@ -3008,7 +3032,25 @@ plus the core files of `test:quick` through the strict free runner on
doesn't run `test:quick` itself, because its browser tests find no Chromium
under the throwaway `HOME`. Without the key, land prints
`STALE_BASE: warn … no land.merged_checks configured` and merges the stale
-base untested, as it did before the key. Then land runs `gh pr merge
+base untested, as it did before the key.
+
+When the base policy sets `land.merged_ci` (`{ workflow, profile }`), land then runs CI
+on the same merged tree: it pushes the merged commit to the scratch branch
+`gstack-land/<n>`, dispatches the workflow there, waits up to 45 minutes, and
+prints `MERGED_CI: pass <workflow> run <url> on the merged tree <tree> (profile
+<profile>)` only when `lib/run-evidence.ts` accepts the run under that run profile
+of the base's `.gstack/pregate.json`, with the merged commit as its head and the
+merged tree as its tested tree. A red run refuses with
+`QUEUE_LAND_MERGED_CHECKS`; a run that can't be pushed, dispatched, finished in
+time or proved refuses with `QUEUE_NOT_READY`; the branch is deleted either way.
+The run is on CI runners, so it needs no `--allow-repo-commands`, and
+`--dry-run` dispatches nothing. gstack's own policy dispatches `free-tests.yml`
+under `ci-reuse/free-tests`, so the whole free suite has run on a stale-base tree
+before it lands (about 5 minutes); its `merged_checks` still run first and fail
+fast. A rerun after the merge checks the landed tree with `merged_checks` only,
+and main's own push run tests it in CI.
+
+Then land runs `gh pr merge
--squash --match-head-commit <pin>` (`--merge` under `history: merge-only`),
reads the merge commit, and checks that its tree is the pin merged onto the
merge commit's parent. The land lock keeps other gstack landers off main
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index b115dea9d..e93a72413 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -6434,13 +6434,24 @@ the lane fixes it at a new head (a flaky case gets its one rerun under rule
### `QUEUE_LAND_MERGED_CHECKS`
**Meaning.** `origin/main` moved since the pin's merge base, and a
-`land.merged_checks` command failed on the pin merged onto main's tip. The
-message names the command, its exit and its last output lines. Nothing was
-merged.
-
-**Fix.** The lane merges `origin/main` into the branch, fixes what the
-command names, pushes, waits for the required checks, runs /ship and `ready`
-at the new head, and sends a new READY.
+`land.merged_checks` command or the `land.merged_ci` run failed on the pin merged
+onto main's tip. The message names the command, its exit and its last output
+lines, or the CI run and its conclusion. Nothing was merged. When the message
+says the checks changed files land's later git and gh calls read (the
+checkout's git config, hooks, `commondir` or `gitdir` files, its `.git`, a config
+file git includes, the global git config, gh's config, or the pinned `git` or
+`gh`), land made no further git or gh call, pushed no lock release, and a
+`LOCK: warn` line says the land lock stays held.
+
+**Fix.** For changed files, hold: nothing goes back to the lane yet. Inspect
+each named path and restore it from a trusted copy (delete a hook the checks
+added) before any git command in that checkout, then release the lock without
+running the checks with `gstack-ship-queue land --pr <n> --pin <sha>` (no
+`--allow-repo-commands`), and find out why the PR's checks wrote there before it
+lands. For a failed command or a red CI run, read the output or the failed job;
+a flaky case gets one rerun of land, and a real failure goes back to the lane,
+which merges `origin/main` into the branch, fixes it, pushes, waits for the
+required checks, runs /ship and `ready` at the new head, and sends a new READY.
<a id="queue-land-not-clean"></a>
### `QUEUE_LAND_NOT_CLEAN`
diff --git a/lib/gh-poll.ts b/lib/gh-poll.ts
index 4d4c0f453..48f2430d9 100644
--- a/lib/gh-poll.ts
+++ b/lib/gh-poll.ts
@@ -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);
diff --git a/lib/land-merged-checks.ts b/lib/land-merged-checks.ts
index cf18e83e0..3b85c3871 100644
--- a/lib/land-merged-checks.ts
+++ b/lib/land-merged-checks.ts
@@ -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: '[email protected]', GIT_COMMITTER_NAME: 'gstack land', GIT_COMMITTER_EMAIL: '[email protected]' };
+ 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: '[email protected]', GIT_COMMITTER_NAME: 'gstack land', GIT_COMMITTER_EMAIL: '[email protected]' };
- 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 (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 (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 (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 });
}
}
diff --git a/lib/land-merged-ci.ts b/lib/land-merged-ci.ts
new file mode 100644
index 000000000..6dabf266b
--- /dev/null
+++ b/lib/land-merged-ci.ts
@@ -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}` } };
+}
diff --git a/lib/ship-queue-land-direct.ts b/lib/ship-queue-land-direct.ts
index 0a383832c..d881703f3 100644
--- a/lib/ship-queue-land-direct.ts
+++ b/lib/ship-queue-land-direct.ts
@@ -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`] };
}
diff --git a/lib/tool-path.ts b/lib/tool-path.ts
new file mode 100644
index 000000000..b74191ceb
--- /dev/null
+++ b/lib/tool-path.ts
@@ -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;
+}
diff --git a/test/land-merged-ci.test.ts b/test/land-merged-ci.test.ts
new file mode 100644
index 000000000..2695c5499
--- /dev/null
+++ b/test/land-merged-ci.test.ts
@@ -0,0 +1,114 @@
+/**
+ * land.merged_ci (lib/land-merged-ci.ts): the CI run land dispatches on the merged commit when the base moved. Fake
+ * dependencies stand in for git push, gh and lib/run-evidence.ts, so each verdict and the scratch branch's cleanup are
+ * checked without a network.
+ */
+import { describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { bunIsolationArgs } from '../lib/bun-isolation';
+import { runMergedCi, type CiDeps } from '../lib/land-merged-ci';
+import { landPolicyErrors } from '../lib/land-merged-checks';
+import type { ApiRun } from '../lib/run-evidence';
+
+const COMMIT = 'c'.repeat(40), TREE = 't'.repeat(40);
+const CI = { workflow: 'free-tests.yml', profile: 'ci-reuse/free-tests' };
+type Calls = string[];
+
+function fake(o: { runs?: ApiRun[][]; verify?: ReturnType<CiDeps['verify']>; push?: string; dispatch?: string } = {}): { deps: CiDeps; calls: Calls } {
+ const calls: Calls = [];
+ let clock = 0, polls = 0;
+ const runs = o.runs ?? [[{ id: 7, run_attempt: 1, status: 'completed', conclusion: 'success', event: 'workflow_dispatch', head_sha: COMMIT }]];
+ const deps: CiDeps = {
+ push: (c, b) => { calls.push(`push ${c.slice(0, 4)} ${b}`); return o.push ?? null; },
+ remove: b => { calls.push(`remove ${b}`); },
+ dispatch: (w, b) => { calls.push(`dispatch ${w} ${b}`); return o.dispatch ?? null; },
+ runsAt: () => runs[Math.min(polls++, runs.length - 1)] ?? [],
+ run: id => { const r = runs[Math.min(polls++, runs.length - 1)]?.[0]; return r ?? { id, run_attempt: 1, status: 'queued', conclusion: null, event: 'workflow_dispatch', head_sha: COMMIT }; },
+ verify: () => o.verify ?? { ok: true, head: COMMIT, tree: TREE },
+ sleep: ms => { clock += ms; },
+ now: () => clock,
+ url: id => `https://example.invalid/runs/${id}`,
+ };
+ return { deps, calls };
+}
+const run = (deps: CiDeps, timeoutMs?: number) => runMergedCi(deps, { pr: '42', commit: COMMIT, tree: TREE, ci: CI, timeoutMs });
+const queued: ApiRun = { id: 7, run_attempt: 1, status: 'in_progress', conclusion: null, event: 'workflow_dispatch', head_sha: COMMIT };
+
+describe('land.merged_ci', () => {
+ test('a green run that verifies the merged commit and tree passes; land pushes gstack-land/<pr>, dispatches there, waits, and deletes the branch', () => {
+ const { deps, calls } = fake({ runs: [[], [queued], [queued], [{ ...queued, status: 'completed', conclusion: 'success' }]] });
+ const r = run(deps);
+ expect(r).toEqual({ ok: true, line: 'MERGED_CI: pass free-tests.yml run https://example.invalid/runs/7 on the merged tree tttttttttttt (profile ci-reuse/free-tests)' });
+ expect(calls).toEqual(['push cccc gstack-land/42', 'dispatch free-tests.yml gstack-land/42', 'remove gstack-land/42']);
+ });
+
+ test('a red run refuses as red, naming its conclusion, and the branch is still deleted', () => {
+ const { deps, calls } = fake({ runs: [[{ ...queued, status: 'completed', conclusion: 'failure' }]] });
+ const r = run(deps);
+ expect(r).toMatchObject({ ok: false, red: true });
+ expect(r.ok ? '' : r.detail).toContain('concluded failure');
+ expect(calls.at(-1)).toBe('remove gstack-land/42');
+ });
+
+ test('a green run the run profile does not accept, or one that tested another commit, is no proof: refused, not red', () => {
+ const refused = run(fake({ verify: { ok: false, detail: 'job_missing: free-tests' } }).deps);
+ expect(refused).toMatchObject({ ok: false, red: false });
+ expect(refused.ok ? '' : refused.detail).toContain('does not prove the tree under ci-reuse/free-tests: job_missing: free-tests');
+ const other = run(fake({ verify: { ok: true, head: 'd'.repeat(40), tree: TREE } }).deps);
+ expect(other).toMatchObject({ ok: false, red: false });
+ expect(other.ok ? '' : other.detail).toContain('not the merged commit cccccccccccc');
+ });
+
+ test('no run by the timeout, a run still going at the timeout, a failed dispatch: refused, not red, and the branch is deleted; a failed push dispatches nothing', () => {
+ const none = fake({ runs: [[]] });
+ const r1 = run(none.deps, 60_000);
+ expect(r1).toMatchObject({ ok: false, red: false });
+ expect(r1.ok ? '' : r1.detail).toContain('no free-tests.yml run appeared on gstack-land/42');
+ expect(none.calls.at(-1)).toBe('remove gstack-land/42');
+ const slow = run(fake({ runs: [[queued]] }).deps, 60_000);
+ expect(slow.ok ? '' : slow.detail).toContain('is still in_progress after');
+ const sent = fake({ dispatch: 'HTTP 422' });
+ expect(run(sent.deps)).toMatchObject({ ok: false, red: false, detail: 'gh workflow run free-tests.yml --ref gstack-land/42 failed: HTTP 422' });
+ expect(sent.calls.at(-1)).toBe('remove gstack-land/42');
+ const pushed = fake({ push: 'rejected' });
+ expect(run(pushed.deps)).toMatchObject({ ok: false, red: false });
+ expect(pushed.calls).toEqual(['push cccc gstack-land/42']);
+ });
+
+ test('the policy key: { workflow, profile } only, a workflow file name and a run profile name; it may stand without merged_checks', () => {
+ expect(landPolicyErrors({ merged_ci: CI })).toEqual([]);
+ expect(landPolicyErrors({ merged_checks: ['true'], merged_ci: CI })).toEqual([]);
+ for (const bad of [{ workflow: '../x.yml', profile: 'p' }, { workflow: 'free-tests.yml' }, { ...CI, extra: 1 }, 'free-tests.yml', null]) expect(landPolicyErrors({ merged_ci: bad }).map(e => e.path)).toContain('land.merged_ci');
+ });
+
+ test('gstack\'s own base policy runs Free Tests on the merged tree under a run profile its pregate config declares', () => {
+ const root = path.join(import.meta.dir, '..');
+ const ci = JSON.parse(fs.readFileSync(path.join(root, '.gstack', 'ship-policy.json'), 'utf8')).land?.merged_ci;
+ expect(ci).toEqual(CI);
+ expect(JSON.parse(fs.readFileSync(path.join(root, '.gstack', 'pregate.json'), 'utf8')).run_profiles?.[ci.profile]?.workflow).toBe(ci.workflow);
+ });
+});
+
+describe('queue git hooks', () => {
+ test.skipIf(process.platform === 'win32')('a queue git call runs the checkout\'s hooks until land turns them off, so wave and train pushes keep the managed pre-push guard', () => {
+ const gate = JSON.stringify(path.join(import.meta.dir, '..', 'crew', 'lib', 'ship-queue-gate.ts'));
+ const script = `const fs = await import('node:fs'); const os = await import('node:os'); const path = await import('node:path');
+ const { git, queueHooksOff } = await import(${gate});
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'queue-hooks-'));
+ const marker = path.join(dir, 'ran');
+ const env = { ...process.env, GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@t', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@t' };
+ git(dir, ['init', '-q'], env);
+ fs.writeFileSync(path.join(dir, '.git', 'hooks', 'pre-commit'), '#!/bin/sh\\necho x >> "' + marker + '"\\n', { mode: 0o755 });
+ const runs = () => fs.existsSync(marker) ? fs.readFileSync(marker, 'utf8').split('\\n').filter(Boolean).length : 0;
+ const before = git(dir, ['commit', '-q', '--allow-empty', '-m', 'a'], env).ok && runs();
+ queueHooksOff();
+ const after = git(dir, ['commit', '-q', '--allow-empty', '-m', 'b'], env).ok && runs();
+ fs.rmSync(dir, { recursive: true, force: true });
+ console.log(JSON.stringify({ before, after }));`;
+ const r = spawnSync(process.execPath, [...bunIsolationArgs(), '-e', script], { encoding: 'utf8', timeout: 60_000 });
+ expect(r.stderr).toBe('');
+ expect(JSON.parse(r.stdout)).toEqual({ before: 1, after: 1 });
+ });
+});
diff --git a/test/ship-queue-land-direct.test.ts b/test/ship-queue-land-direct.test.ts
index 80c74a4d6..6674ae31d 100644
--- a/test/ship-queue-land-direct.test.ts
+++ b/test/ship-queue-land-direct.test.ts
@@ -130,6 +130,8 @@ function runMergedChecks(root: string, base: string, pin: string, checks: string
if (r.status !== 0) throw new Error(`runMergedChecks child exited ${r.status ?? r.signal}: ${r.stderr}`);
return JSON.parse(r.stdout) as MergedRun;
}
+/** A new base policy committed straight onto origin/main, for a policy whose commands name the fixture's own paths. */
+const writePolicy = (fx: Fx, policy: Record<string, unknown>) => moveMain(fx, '.gstack/ship-policy.json', JSON.stringify(policy, null, 2) + '\n');
/** Commit a file straight onto origin/main (another PR that landed first). */
function moveMain(fx: Fx, file: string, text: string): string {
const { repo } = fx;
@@ -340,6 +342,157 @@ describe('land --pin: direct merge at the PR\'s own green head', () => {
}
}, 90_000);
+ test('land.merged_checks that write .git hooks, .git config and node_modules in their own tree: the writes stay in the throwaway clone, no hook runs, and land merges', () => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-land-clone-'));
+ const marker = path.join(scratch, 'hook-ran');
+ const write = `d=$(git rev-parse --path-format=absolute --git-common-dir); printf '#!/bin/sh\\ntouch ${marker}\\n' > $d/hooks/pre-push; chmod +x $d/hooks/pre-push; git config --file $d/config gstack.probe changed; mkdir -p node_modules && echo poison > node_modules/poison`;
+ const fx = setup({ ...POLICY, land: { merged_checks: [write] }, min_gstack_version: LAND_KEY_VERSION });
+ try {
+ const pin = openPr(fx, '90');
+ moveMain(fx, 'other.txt', 'other\n');
+ const common = fx.repo.git('rev-parse', '--path-format=absolute', '--git-common-dir');
+ const config = fs.readFileSync(path.join(common, 'config'), 'utf8');
+ const ok = land(fx, '90', pin, ['--allow-repo-commands']);
+ expect(ok.err).toBe('');
+ expect(ok.status).toBe(EXIT.ok);
+ expect(fx.read().mergeArgs).toBeDefined();
+ expect(fs.existsSync(path.join(common, 'hooks', 'pre-push'))).toBe(false);
+ expect(fs.readFileSync(path.join(common, 'config'), 'utf8')).toBe(config);
+ expect(fs.existsSync(path.join(fx.repo.work, 'node_modules', 'poison'))).toBe(false);
+ expect(fs.existsSync(marker)).toBe(false);
+ } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
+ }, 90_000);
+
+ test('land.merged_checks that write the checkout\'s own git hooks or config by absolute path: land refuses with QUEUE_LAND_MERGED_CHECKS naming each path and a hold-and-inspect fix, runs no hook, pushes no lock release, and the unlock command releases the lock without running the checks', () => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-land-gitdir-'));
+ const marker = path.join(scratch, 'hook-ran');
+ const fx = setup({ ...POLICY, land: { merged_checks: ['true'] }, min_gstack_version: LAND_KEY_VERSION });
+ try {
+ const common = fx.repo.git('rev-parse', '--path-format=absolute', '--git-common-dir');
+ const write = `d=${common}; printf '#!/bin/sh\\ntouch ${marker}\\n' > $d/hooks/pre-push; chmod +x $d/hooks/pre-push; git config --file $d/config gstack.probe changed`;
+ writePolicy(fx, { ...POLICY, land: { merged_checks: [write] }, min_gstack_version: LAND_KEY_VERSION });
+ const pin = openPr(fx, '95');
+ moveMain(fx, 'other.txt', 'other\n');
+ const config = fs.readFileSync(path.join(common, 'config'), 'utf8');
+ const lock = () => JSON.parse(fx.repo.git('--git-dir', fx.repo.origin, 'show', 'refs/notes/gstack-land:lock.json'));
+ const r = land(fx, '95', pin, ['--allow-repo-commands']);
+ expect(r.status).not.toBe(EXIT.ok);
+ expect(r.err).toContain('(QUEUE_LAND_MERGED_CHECKS)');
+ expect(r.err).toContain('the checks changed .git/config, .git/hooks/pre-push, which land\'s later git and gh calls read');
+ expect(r.err).toContain('restore it from a trusted copy (delete a hook the checks added)');
+ expect(r.err).toContain('hold and inspect');
+ expect(r.err).not.toContain('git merge origin/main');
+ expect(r.out).toContain(`release the lock without running the checks: gstack-ship-queue land --pr 95 --pin ${pin} (without --allow-repo-commands)`);
+ expect(fx.read().mergeArgs).toBeUndefined();
+ expect(fs.existsSync(marker)).toBe(false);
+ expect(lock().released).not.toBe(true);
+ fs.rmSync(path.join(common, 'hooks', 'pre-push'));
+ fs.writeFileSync(path.join(common, 'config'), config);
+ const unlock = land(fx, '95', pin);
+ expect(unlock.err).toContain('(REPO_COMMANDS_NOT_ALLOWED)');
+ expect(fs.existsSync(path.join(common, 'hooks', 'pre-push'))).toBe(false);
+ expect(fx.read().mergeArgs).toBeUndefined();
+ expect(lock()).toMatchObject({ released: true });
+ } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
+ }, 90_000);
+
+ test('a hook a merged check writes under the checkout\'s core.hooksPath never runs in land\'s git calls, and land still merges', () => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-land-hookspath-'));
+ const marker = path.join(scratch, 'hook-ran');
+ const fx = setup({ ...POLICY, land: { merged_checks: ['true'] }, min_gstack_version: LAND_KEY_VERSION });
+ try {
+ const h = path.join(fx.repo.work, '.hooks');
+ writePolicy(fx, { ...POLICY, land: { merged_checks: [`mkdir -p ${h} && printf '#!/bin/sh\\ntouch ${marker}\\n' > ${h}/pre-push && chmod +x ${h}/pre-push`] }, min_gstack_version: LAND_KEY_VERSION });
+ fx.repo.git('config', 'core.hooksPath', '.hooks');
+ const pin = openPr(fx, '91');
+ moveMain(fx, 'other.txt', 'other\n');
+ const ok = land(fx, '91', pin, ['--allow-repo-commands']);
+ expect(ok.err).toBe('');
+ expect(ok.status).toBe(EXIT.ok);
+ expect(fs.existsSync(path.join(h, 'pre-push'))).toBe(true);
+ expect(fs.existsSync(marker)).toBe(false);
+ expect(fx.read().mergeArgs).toBeDefined();
+ } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
+ }, 90_000);
+
+ test('a merged check that points the checkout\'s .git/commondir at another directory: land refuses naming it and leaves the lock held', () => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-land-commondir-'));
+ const alt = path.join(scratch, 'alt');
+ const fx = setup({ ...POLICY, land: { merged_checks: ['true'] }, min_gstack_version: LAND_KEY_VERSION });
+ try {
+ const d = fx.repo.git('rev-parse', '--path-format=absolute', '--git-common-dir');
+ writePolicy(fx, { ...POLICY, land: { merged_checks: [`a=${alt}; mkdir -p $a && ln -s ${d}/objects ${d}/refs $a/ && cp ${d}/HEAD $a/ && printf '[core]\\n\\tsshCommand = false\\n' > $a/config && echo $a > ${d}/commondir`] }, min_gstack_version: LAND_KEY_VERSION });
+ const pin = openPr(fx, '92');
+ moveMain(fx, 'other.txt', 'other\n');
+ const r = land(fx, '92', pin, ['--allow-repo-commands']);
+ expect(r.status).not.toBe(EXIT.ok);
+ expect(r.err).toContain('(QUEUE_LAND_MERGED_CHECKS)');
+ expect(r.err).toContain('the checks changed .git/commondir, which');
+ expect(fx.read().mergeArgs).toBeUndefined();
+ expect(JSON.parse(fx.repo.git('--git-dir', fx.repo.origin, 'show', 'refs/notes/gstack-land:lock.json')).released).not.toBe(true);
+ } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
+ }, 90_000);
+
+ test('a merged check that repoints the middle link of a symlinked .git/config chain: land detects it and refuses naming the link', () => {
+ const fx = setup({ ...POLICY, land: { merged_checks: ['true'] }, min_gstack_version: LAND_KEY_VERSION });
+ const common = fx.repo.git('rev-parse', '--path-format=absolute', '--git-common-dir');
+ writePolicy(fx, { ...POLICY, land: { merged_checks: [`d=${common}; printf '[core]\\n\\tsshCommand = false\\n' > $d/alt && ln -sfn alt $d/config.mid`] }, min_gstack_version: LAND_KEY_VERSION });
+ const pin = openPr(fx, '94');
+ moveMain(fx, 'other.txt', 'other\n');
+ fs.renameSync(path.join(common, 'config'), path.join(common, 'config.real'));
+ fs.symlinkSync('config.real', path.join(common, 'config.mid'));
+ fs.symlinkSync('config.mid', path.join(common, 'config'));
+ const r = land(fx, '94', pin, ['--allow-repo-commands']);
+ expect(r.status).not.toBe(EXIT.ok);
+ expect(r.err).toContain('(QUEUE_LAND_MERGED_CHECKS)');
+ expect(r.err).toContain('the checks changed .git/config.mid, which');
+ expect(fx.read().mergeArgs).toBeUndefined();
+ }, 90_000);
+
+ test('GST-1766: a merged check that edits a config file the checkout includes, creates a global git config, or rewrites the gh land runs: land refuses naming that file and merges nothing', () => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-land-reads-'));
+ try {
+ const inc = path.join(scratch, 'inc.cfg');
+ fs.writeFileSync(inc, '[gstack]\n\tprobe = 1\n');
+ const cases: Array<[string, (fx: Fx) => string, (fx: Fx) => string]> = [
+ ['96', fx => { fx.repo.git('config', 'include.path', inc); return `printf '[core]\\n\\tsshCommand = false\\n' >> ${inc}`; }, () => inc],
+ ['97', fx => `printf '[credential]\\n\\thelper = !false\\n' >> ${fx.repo.env.GIT_CONFIG_GLOBAL}`, fx => fx.repo.env.GIT_CONFIG_GLOBAL],
+ ['98', fx => `echo '// changed' >> ${path.join(fx.repo.root, 'gh-shim', 'gh')}`, fx => path.join(fx.repo.root, 'gh-shim', 'gh')],
+ ];
+ for (const [pr, arm, named] of cases) {
+ const fx = setup({ ...POLICY, land: { merged_checks: ['true'] }, min_gstack_version: LAND_KEY_VERSION });
+ const write = arm(fx);
+ writePolicy(fx, { ...POLICY, land: { merged_checks: [write] }, min_gstack_version: LAND_KEY_VERSION });
+ const pin = openPr(fx, pr);
+ moveMain(fx, 'other.txt', 'other\n');
+ const r = land(fx, pr, pin, ['--allow-repo-commands']);
+ expect(r.status, pr).not.toBe(EXIT.ok);
+ expect(r.err, pr).toContain('(QUEUE_LAND_MERGED_CHECKS)');
+ expect(r.err, pr).toContain(`the checks changed ${named(fx)}, which land's later git and gh calls read`);
+ expect(fx.read().mergeArgs, pr).toBeUndefined();
+ }
+ } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
+ }, 120_000);
+
+ test('GST-1766: a git a merged check drops early on PATH never runs in land\'s later git or gh calls (land pinned git before the checks), and land merges', () => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-land-shim-'));
+ try {
+ const early = path.join(scratch, 'early'), marker = path.join(scratch, 'shim-ran'), shim = path.join(scratch, 'git-shim');
+ fs.mkdirSync(early);
+ fs.writeFileSync(shim, `#!/bin/sh\ntouch ${marker}\nexec ${Bun.which('git')} "$@"\n`, { mode: 0o755 });
+ const fx = setup({ ...POLICY, land: { merged_checks: [`cp ${shim} ${early}/git && chmod +x ${early}/git`] }, min_gstack_version: LAND_KEY_VERSION });
+ fx.env.PATH = `${early}:${fx.env.PATH}`;
+ const pin = openPr(fx, '99');
+ moveMain(fx, 'other.txt', 'other\n');
+ const ok = land(fx, '99', pin, ['--allow-repo-commands']);
+ expect(ok.err).toBe('');
+ expect(ok.status).toBe(EXIT.ok);
+ expect(fs.existsSync(path.join(early, 'git'))).toBe(true);
+ expect(fs.existsSync(marker)).toBe(false);
+ expect(fx.read().mergeArgs).toBeDefined();
+ } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
+ }, 90_000);
+
test('QUEUE_LAND_NOT_CLEAN: on a stale base the pin conflicts with main, so no merged check runs and nothing merges', () => {
const fx = setup(CHECKED);
const pin = openPr(fx, '83', { edit: w => fs.writeFileSync(path.join(w, 'other.txt'), 'pr\n') });