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
Repos can prove copied open-source files match their upstream byte for byte (GST-3298) (#4646)
Garry Tan69ad1031a19c
diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.shindex 7ebbbcc21..0a6316f84 100644--- a/bin/gstack-doctor-components.sh+++ b/bin/gstack-doctor-components.sh@@ -373,6 +373,14 @@ gstack_result_anchor() {PREGATE_HEAD_POLICY_LOOSENS) printf '%s' 'pregate-head-policy-loosens' ;;REVIEW_DIFF_TOO_LARGE) printf '%s' 'review-diff-too-large' ;;REVIEW_EXCLUDE_KEEP_TOO_LARGE) printf '%s' 'review-exclude-keep-too-large' ;;+ VENDORED_MISMATCH) printf '%s' 'vendored-mismatch' ;;+ VENDORED_ABSENT_UPSTREAM) printf '%s' 'vendored-absent-upstream' ;;+ VENDORED_ABSENT_LOCAL) printf '%s' 'vendored-absent-local' ;;+ VENDORED_MODE) printf '%s' 'vendored-mode' ;;+ VENDORED_UNREACHABLE) printf '%s' 'vendored-unreachable' ;;+ VENDORED_NOT_ALLOWLISTED) printf '%s' 'vendored-not-allowlisted' ;;+ VENDORED_FETCH_FAILED) printf '%s' 'vendored-fetch-failed' ;;+ VENDORED_MANIFEST_INVALID) printf '%s' 'vendored-manifest-invalid' ;;REVIEW_DIFF_UNREADABLE) printf '%s' 'review-diff-unreadable' ;;REVIEW_PLAN_STOPPED) printf '%s' 'review-plan-stopped' ;;REVIEW_EXCLUDE_REFERENCE) printf '%s' 'review-exclude-reference' ;;diff --git a/bin/gstack-vendored-verify b/bin/gstack-vendored-verifynew file mode 100755index 000000000..6220f9403--- /dev/null+++ b/bin/gstack-vendored-verify@@ -0,0 +1,99 @@+#!/usr/bin/env -S bun --no-env-file --config=/dev/null+/**+ * gstack-vendored-verify — check that every file a vendored manifest pins is byte-for-byte its upstream's file at a+ * commit the upstream really holds (docs/vendored-code.md, GST-3298).+ *+ * gstack-vendored-verify --base <branch> [--all] [--offline] [--json]+ *+ * The allowlist and the manifest list come from the base branch's .gstack/ship-policy.json (review_vendored), never+ * from the head; the manifests themselves are read at HEAD. By default it checks the entries this branch changes+ * (files added, modified or deleted since the merge base, and entries whose pin the manifest diff changes); --all checks every+ * entry. --offline answers from the cache an earlier run filled, without the network. A repo makes it a required CI+ * check: exit 1 means a manifest says something that is not true. Logic: lib/review-vendored.ts.+ */+import { spawnSync } from '../lib/spawn-sync';+import { EXIT, exitTableHelp } from '../lib/headless-artifacts';+import { resultLine, type ResultCodeName } from '../lib/result-codes';+import { isUnavailable, policyUnavailableLine } from '../lib/ship-policy';+import { loadPolicyAt } from '../lib/ship-policy-at';+import { resolveStateRoot } from '../lib/state-root';+import { parseManifest, resolveVendored, vendoredCacheRoot, vendoredPolicy, type VendoredEntry, type VendoredVerdict } from '../lib/review-vendored';++const HELP = `gstack-vendored-verify — check vendored files against their upstream pins (docs/vendored-code.md)++ --base <branch> the base branch whose policy names the upstreams and manifests (required)+ --all check every manifest entry, not only the ones this branch changes+ --offline answer from the cache an earlier run filled; no network+ --json print one JSON object instead of lines++${exitTableHelp()}`;++const CODES: Record<Exclude<VendoredVerdict, 'verified'>, ResultCodeName> = {+ mismatched: 'VENDORED_MISMATCH', 'absent-upstream': 'VENDORED_ABSENT_UPSTREAM', 'absent-local': 'VENDORED_ABSENT_LOCAL', mode: 'VENDORED_MODE',+ unreachable: 'VENDORED_UNREACHABLE', 'not-allowlisted': 'VENDORED_NOT_ALLOWLISTED', 'fetch-failed': 'VENDORED_FETCH_FAILED',+};+const CTX = 'gstack-vendored-verify';+const argv = process.argv.slice(2);+if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP); process.exit(EXIT.ok); }+const known = new Set(['--base', '--all', '--offline', '--json']);+const baseAt = argv.indexOf('--base');+const base = baseAt >= 0 ? argv[baseAt + 1] : undefined;+const stray = argv.filter((a, i) => !known.has(a) && i !== baseAt + 1);+if (!base || base.startsWith('-') || stray.length) { process.stderr.write(`${CTX}: ${stray.length ? `unknown argument ${stray[0]}` : '--base <branch> is required'}\n${HELP}`); process.exit(EXIT.usage); }+const json = argv.includes('--json');++function git(args: string[]): string | null {+ const r = spawnSync('git', args, { encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });+ return r.status === 0 ? r.stdout : null;+}+const root = git(['rev-parse', '--show-toplevel'])?.trim();+const ref = base.startsWith('origin/') ? base : `origin/${base}`;+const baseSha = root ? (git(['rev-parse', '--verify', '-q', `${ref}^{commit}`]) ?? git(['rev-parse', '--verify', '-q', `${base}^{commit}`]))?.trim() : undefined;+const head = root ? git(['rev-parse', '--verify', 'HEAD^{commit}'])?.trim() : undefined;+const mergeBase = baseSha && head ? git(['merge-base', baseSha, head])?.trim() : undefined;+if (!root || !baseSha || !head || !mergeBase) { process.stderr.write(`${CTX}: could not resolve ${!root ? 'the repository' : !baseSha ? ref : !head ? 'HEAD' : 'the merge base'}; fix: git fetch origin ${base.replace(/^origin\//, '')}, then rerun\n`); process.exit(EXIT.refused); }++const load = loadPolicyAt(root, baseSha, ref);+if (isUnavailable(load)) { process.stderr.write(policyUnavailableLine(CTX, load.base, load.detail) + '\n'); process.exit(EXIT.refused); }+if (load.errors.length) { for (const e of load.errors) process.stderr.write(`${CTX}: the base policy does not validate (${e.path}: ${e.message}); fix: gstack-ship-policy validate --policy-from base --base ${base} (${e.code})\n`); process.exit(EXIT.refused); }+const policy = vendoredPolicy(load.policy);+if (!policy) { process.stdout.write(json ? JSON.stringify({ state: 'none' }) + '\n' : `VENDORED_VERIFY: none (the base policy ${ref}@${baseSha.slice(0, 12)} declares no review_vendored)\n`); process.exit(EXIT.ok); }++const problems: string[] = [];+const entries: VendoredEntry[] = [];+const before = new Map<string, string>();+for (const m of policy.manifests) {+ const text = git(['show', `${head}:${m}`]);+ if (text === null) { problems.push(`${m} is not in HEAD`); continue; }+ const parsed = parseManifest(text, m);+ problems.push(...parsed.errors);+ entries.push(...parsed.entries);+ const old = git(['show', `${mergeBase}:${m}`]);+ if (old !== null) for (const e of parseManifest(old, m).entries) before.set(e.path, `${e.upstream}@${e.commit}:${e.upstream_path}`);+}+const seen = new Map<string, number>();+entries.forEach(e => seen.set(e.path.toLowerCase(), (seen.get(e.path.toLowerCase()) ?? 0) + 1));+for (const [p, n] of seen) if (n > 1) problems.push(`${p} is pinned by more than one manifest`);++let selected = entries;+if (!argv.includes('--all')) {+ const diff = git(['diff', '--name-only', '-z', '--no-renames', '--diff-filter=ADMT', mergeBase, head]);+ if (diff === null) { process.stderr.write(`${CTX}: git could not list the files this branch changes; fix: rerun once, then check the checkout (git status)\n`); process.exit(EXIT.refused); }+ const changed = new Set(diff.split('\0').filter(Boolean));+ selected = entries.filter(e => changed.has(e.path) || before.get(e.path) !== `${e.upstream}@${e.commit}:${e.upstream_path}`);+}+const res = problems.length ? null : resolveVendored({ root, rev: head, policy, entries: selected, fetch: !argv.includes('--offline'), cacheRoot: vendoredCacheRoot(resolveStateRoot()) });+if (!problems.length && !res) { process.stderr.write(`${CTX}: git could not list HEAD's files; fix: rerun once, then check the checkout (git status)\n`); process.exit(EXIT.refused); }+const failed = res?.entries.filter(e => e.verdict !== 'verified') ?? [];+const summary = { scope: argv.includes('--all') ? 'all' : 'changed', manifests: policy.manifests.length, entries: entries.length, checked: res?.entries.length ?? 0, verified: (res?.entries.length ?? 0) - failed.length, failed: failed.length, pins: res?.pins.length ?? 0, digest: res?.digest ?? null };+if (json) {+ process.stdout.write(JSON.stringify({ state: problems.length || failed.length ? 'failed' : 'verified', ...summary, manifest_errors: problems, pin_results: res?.pins ?? [], failures: failed }) + '\n');+} else {+ for (const p of problems) process.stdout.write(resultLine(CTX, 'VENDORED_MANIFEST_INVALID', p) + '\n');+ for (const p of res?.pins ?? []) process.stdout.write(`VENDORED_PIN: ${p.upstream}@${p.commit.slice(0, 12)} reachable_from=${p.reachable_from ?? 'none'} files=${p.files} verified=${p.verified}\n`);+ for (const f of failed.slice(0, 50)) process.stdout.write(resultLine(CTX, CODES[f.verdict as Exclude<VendoredVerdict, 'verified'>], `${f.path} <- ${f.upstream}@${f.commit.slice(0, 12)}:${f.upstream_path}${f.detail ? `; ${f.detail}` : ''}`) + '\n');+ if (failed.length > 50) process.stdout.write(`VENDORED_VERIFY_FAILED: +${failed.length - 50} more (--json lists every one)\n`);+ process.stdout.write(problems.length ? `VENDORED_VERIFY: failed manifests=${policy.manifests.length} manifest_errors=${problems.length}\n`+ : `VENDORED_VERIFY: checked=${summary.checked} verified=${summary.verified} failed=${summary.failed} pins=${summary.pins} manifests=${summary.manifests} scope=${summary.scope} digest=${summary.digest}\n`);+}+process.exit(problems.length || failed.length ? EXIT.fail : EXIT.ok);diff --git a/changelog.d/vendored-files-verified-against-upstream-pins.md b/changelog.d/vendored-files-verified-against-upstream-pins.mdnew file mode 100644index 000000000..5e9ac621a--- /dev/null+++ b/changelog.d/vendored-files-verified-against-upstream-pins.md@@ -0,0 +1 @@+Repos that copy open-source files unchanged can now prove it. List the upstream repositories in `review_vendored` on the base branch and pin each copied file in a manifest, and `gstack-vendored-verify` checks that every file is byte-for-byte that upstream's file at a commit on its default branch, a tag or a branch the base names. Run it as a required CI check. A file that doesn't match, can't be fetched, or comes from an unlisted repository, a fork or a merge-queue branch fails with a reason and a fix (docs/vendored-code.md).diff --git a/docs/ship-policy.md b/docs/ship-policy.mdindex c7c7b2cfe..a1eae5e9b 100644--- a/docs/ship-policy.md+++ b/docs/ship-policy.md@@ -77,6 +77,7 @@ branch that changes the policy.| `review_content_patterns` | git glob pathspecs | `[]` | Files that `review_exclude_paths` also matches and that count as content whatever their extension (`.patch` files, `MANIFEST.sha256`, extension-less licence texts), so the exclusion leaves them out. Source code, agent prose, config and the other keep rules still keep a matched file in review. Explicit policy only; a pattern here with no `review_exclude_paths` pattern over the same files excludes nothing. Read from the base only. See [review_content_patterns](#review-content-patterns). Needs `min_gstack_version`. || `review` | `{ panel?, reader_model?, platform?, risk_paths? }` | `{ all, lane, off, [] }` | Who does `/ship`'s review, read from the base only; see [Who reads](review-policy.md#who-reads-r65-the-base-policys-review-key). `panel`: `all` (today's panel on every class) \| `risk` \| `off` (the opt-in one-reader shapes); `reader_model`: `lane`, `cross-family` or a model id; `platform`: `off` \| `on` (a docs or tests diff with no numeric, results or prereg claims whose PR carries capy-ai[bot]'s review at the exact head skips the readers); `risk_paths`: globs of code paths that count as risk class `policy`. Introduced at 1.94.30.0; needs `min_gstack_version` when set to a non-default value. || `readers` | `{ forbid_fetch?, forbid_paths?, brief_note? }` | `{ [], [], null }` | What `/ship`'s readers may not reach beyond the fetch rule every brief carries; see [readers](#readers). Read from the base; the head may add `forbid_fetch` entries, never remove one. Needs `min_gstack_version`. |+| `review_vendored` | `{ upstreams, manifests }` or `null` | `null` | The repositories this repo copies unchanged files from (https URLs, or `{ url, branches }`) and the manifests that pin each copied file to a path at a commit. `gstack-vendored-verify` checks every pinned file is byte-for-byte that upstream file at a commit on the upstream's default branch or a tag; see [vendored-code.md](vendored-code.md). Read from the base only. Needs `min_gstack_version`. || `min_gstack_version` | version or `null` | `null` | The oldest gstack that may read the file; see the compatibility rule above. || `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`. |diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex c954368f3..4c243a9ab 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -4621,6 +4621,90 @@ file name no root has, a sha a shallow clone lacks) printsevidence lives in another checkout, run `check` with `--root <dir>` for it(repeatable; the default is the git top level of the working directory).+## Vendored upstream files (gstack-vendored-verify)++<a id="vendored-mismatch"></a>+### `VENDORED_MISMATCH`++**Meaning.** A file the manifest pins is not the upstream's file at the pinned+commit: its git blob id (git's hash of the exact bytes) differs. The line names+the local path, the upstream, the commit and the upstream path. The file is not+treated as vendored.++**Fix.** Rebuild the file from the pinned commit. If the change is deliberate,+remove the file from the manifest so it is reviewed as the repo's own code.++<a id="vendored-absent-upstream"></a>+### `VENDORED_ABSENT_UPSTREAM`++**Meaning.** The upstream path an entry names does not exist at the pinned+commit. A manifest maps files by prefix, so a file cannot be renamed on the way+in: `vendor/lib/tests/conftest.py` only matches an upstream `tests/conftest.py`.++**Fix.** Correct the entry's `upstream_prefix`, file path or commit.++<a id="vendored-absent-local"></a>+### `VENDORED_ABSENT_LOCAL`++**Meaning.** The manifest lists a file that is not in the commit being checked.++**Fix.** Add the file, or remove the entry. The repo's build writes both, so+rebuild them together.++<a id="vendored-mode"></a>+### `VENDORED_MODE`++**Meaning.** The file is an executable, a symlink or a submodule, here or+upstream. Only plain files (mode `100644` on both sides) count as vendored.++**Fix.** Clear the executable bit when the upstream file is a plain file, or+remove the entry so the file is reviewed.++<a id="vendored-unreachable"></a>+### `VENDORED_UNREACHABLE`++**Meaning.** The pinned commit is not on the upstream's default branch, a tag,+or a branch the base policy names for that upstream. GitHub serves a fork's+commits and pull request heads through the original repository's URL, so a+commit that merely exists there proves nothing. Merge-queue branches and+force-pushed commits fail the same way.++**Fix.** Pin a commit on the default branch or a release tag. When the upstream+ships from another branch, add it to that upstream's `branches` in+`review_vendored` on the base branch, as its own PR.++<a id="vendored-not-allowlisted"></a>+### `VENDORED_NOT_ALLOWLISTED`++**Meaning.** The manifest pins files to an upstream the base branch's+`review_vendored.upstreams` does not list. The list is read from the base+only, so a branch cannot trust a new upstream for itself.++**Fix.** Add the upstream's URL on the base branch as its own PR, then bring the+base into the branch and rerun.++<a id="vendored-fetch-failed"></a>+### `VENDORED_FETCH_FAILED`++**Meaning.** The upstream could not be fetched anonymously over https: it was+deleted, renamed, made private, redirected, or the network failed or timed out+(`GSTACK_VENDORED_FETCH_TIMEOUT_MS`, default 180,000). `--offline` reports it+for a pin no earlier run cached. Its files stay in review.++**Fix.** Rerun once; a fetch has no side effects. If it fails again, check the+URL opens without signing in and does not redirect, and update+`review_vendored.upstreams` on the base if the repository moved.++<a id="vendored-manifest-invalid"></a>+### `VENDORED_MANIFEST_INVALID`++**Meaning.** A manifest the base policy lists is missing at the commit being+checked, or breaks the `gstack-vendored/v1` format; the line names the field.+Nothing is checked until it is fixed.++**Fix.** Fix the field ([the manifest](vendored-code.md#the-manifest)), usually+by rerunning the build that writes it.+## Pre-gate: generated-file registry, gstack-pregate, issue linksBoth tools read their pin file (`.gstack/generated.json`, `.gstack/pregate.json`)diff --git a/docs/vendored-code.md b/docs/vendored-code.mdnew file mode 100644index 000000000..0053786b5--- /dev/null+++ b/docs/vendored-code.md@@ -0,0 +1,154 @@+# Vendored upstream code++Some repos copy open-source files in on purpose, unchanged: an eval that runs a+project's own tests, a fixture built from a real library. Those files are+someone else's code, and reading ten megabytes of them in review checks very+little. What matters is whether they really are that project's files, at the+commit you say, from the project you think.++`review_vendored` lets a repo make that claim in a form gstack can check, and+`gstack-vendored-verify` checks it.++## What a check proves++A file passes when all of these hold:++1. Its upstream repository is listed in `review_vendored.upstreams` in the+ **base branch's** `.gstack/ship-policy.json`. A branch cannot add an+ upstream for itself; that takes its own PR on the base.+2. The pinned commit is on the upstream's default branch, one of its tags, or a+ branch the base policy names for that upstream. A commit that only a fork, a+ pull request (`refs/pull/*`) or a merge-queue branch holds fails, even+ though GitHub serves those through the original repository's URL. A branch+ glob never admits a merge-queue branch (`gh-readonly-queue/*`), not even+ `*`, and a named branch the upstream doesn't have is skipped instead of+ failing the other pins.+3. The file's git blob id and the upstream file's blob id are equal, and both+ are plain files (mode `100644`). A blob id is git's hash of the exact bytes,+ so equal ids mean byte-identical files.+4. The file keeps its path relative to the upstream root (a prefix map), so a+ file cannot be renamed on the way in, for example into a `conftest.py` that+ pytest runs automatically.++It does **not** prove that the upstream code is safe, that the pinned commit is+the right version, that the code is safe to run where you run it, or anything+about licences. Keep each upstream's licence notice in the repo. Review moves to+the pin: which repository, which commit, which files, and where they land.++| Attack or mistake | Result |+|---|---|+| Pin to an attacker's repository or a fork | `VENDORED_NOT_ALLOWLISTED` |+| Fork commit fetched through the original URL, a pull request head, a merge-queue branch | `VENDORED_UNREACHABLE` |+| Upstream force-pushed so the commit left every branch and tag | `VENDORED_UNREACHABLE` |+| Upstream deleted, renamed (redirects are not followed), made private; network down | `VENDORED_FETCH_FAILED` |+| A local edit to a vendored file | `VENDORED_MISMATCH` |+| A file renamed under its prefix | `VENDORED_ABSENT_UPSTREAM` |+| An executable or symlink | `VENDORED_MODE` |++Every failure fails closed: the file is simply not vendored.++## Set it up++1. On the base branch, declare the upstreams and the manifest:++ ```json+ {+ "review_vendored": {+ "upstreams": [+ "https://github.com/pallets/click",+ { "url": "https://github.com/example/lib", "branches": ["release/*"] }+ ],+ "manifests": ["tasks/VENDORED.json"]+ },+ "min_gstack_version": "<the release that introduced review_vendored>"+ }+ ```++ `gstack-ship-policy validate --policy-from base --base main` checks it.++2. Have your build write the manifest beside the files it copies (below).++3. Run `gstack-vendored-verify --base main` locally and add it to CI as a+ required check.++## The manifest++`gstack-vendored/v1` JSON, one pin per upstream commit and local folder:++```json+{+ "schema": "gstack-vendored/v1",+ "pins": [+ {+ "upstream": "https://github.com/pallets/click",+ "commit": "04ef3a6f473deb2499721a8d11f92a7d2c0912f2",+ "local_prefix": "tasks/rf-01/verifier/protected/",+ "upstream_prefix": "",+ "files": ["tests/test_basic.py", "tests/conftest.py"]+ }+ ]+}+```++- `commit` is the full 40-character id.+- `local_prefix` is a folder ending in `/`; `upstream_prefix` is `""` or a+ folder ending in `/`. Each file lands at `local_prefix + file` and comes from+ `upstream_prefix + file`.+- Paths are repo-relative, with no `..`, `.` or empty segment, no backslash,+ and no two entries that differ only in letter case.+- A file listed here and edited locally fails the check. Remove it from the+ manifest to have it reviewed as your own code instead.++## The command++```+gstack-vendored-verify --base <branch> [--all] [--offline] [--json]+```++By default it checks the entries a branch changes: files added, modified or+deleted since the merge base, and entries whose pin the manifest diff changes. `--all`+checks every entry. Output is one `VENDORED_PIN:` line per pin (with the branch+or tag that holds it), one line per failure with its reason code and fix, and a+summary:++```+VENDORED_PIN: https://github.com/Textualize/rich@12eeb42c96a7 reachable_from=heads/main files=71 verified=71+VENDORED_VERIFY: checked=1056 verified=1054 failed=2 pins=71 manifests=1 scope=all digest=<sha256>+```++Exit 0 means every checked entry verified (or the base declares no+`review_vendored`), 1 means a manifest claims something untrue, 2 is a usage+error and 3 means the base branch, its policy or the checkout could not be read+(or the base policy does not validate).++Fetches go straight to each upstream over https, anonymously: no credential+helper, extra header or URL rewrite from your git configuration, no prompt, no+redirect, and a timeout (`GSTACK_VENDORED_FETCH_TIMEOUT_MS`, default 180,000).+That way a check that passes on your machine passes in CI. Each upstream's+commit history (no file contents) and each pin's file listing are cached under+the gstack state root, so a rerun is quick and `--offline` answers from the+cache without the network. On harness-evals#504 (1,056 files from 11 Python+projects, 71 pinned commits), a cold run took 19 seconds and a 15 MB cache.++## In CI++```yaml+- name: Vendored files match their upstream pins+ env:+ GSTACK_TAG: v1.103.0.0 # any release at or above your policy's min_gstack_version+ run: |+ git fetch --no-tags origin main+ git clone --depth 1 --branch "$GSTACK_TAG" https://github.com/garrytan/gstack.git "$RUNNER_TEMP/gstack"+ bun --no-env-file --config=/dev/null "$RUNNER_TEMP/gstack/bin/gstack-vendored-verify" --base main+```++The check+runs from the head's workflow file, so it is a backstop for honest mistakes; a+workflow edit is itself reviewed like any other `.github/` change.++## What comes next++Today the check proves the claim. A later release lets `/ship`'s review skip+verified files under a `review_exclude_paths` pattern while still showing+reviewers the manifest, every pin and the lines in those files that skip or+silence tests.diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.tsindex caaaa6461..7306a72ee 100644--- a/lib/result-codes-release.ts+++ b/lib/result-codes-release.ts@@ -606,6 +606,46 @@ export const RELEASE_RESULT_CODES = {summary: 'a review_exclude_paths pattern keeps so many matched files in review that the command readers run to read them would pass 24,000 argument bytes, so gstack-review-plan stopped instead of silently dropping the pattern; the line names the pattern, the kept count, the reasons they are kept and the bytes',fix: 'when the kept files are published data (reason code on .patch, MANIFEST.sha256 or extension-less files), land a review_content_patterns entry over them beside the pattern on the base as its own PR, then bring the base into the branch and rerun once; otherwise narrow the pattern or split the PR',},+ VENDORED_MISMATCH: {+ anchor: 'vendored-mismatch',+ summary: 'a file a vendored manifest pins is not byte-for-byte the upstream file at the pinned commit (its git blob id differs), so it is not treated as vendored and stays in review',+ fix: 'restore the upstream bytes (rebuild it from the pinned commit), or remove the entry from the manifest so the edited file is reviewed as the repo\'s own code',+ },+ VENDORED_ABSENT_UPSTREAM: {+ anchor: 'vendored-absent-upstream',+ summary: 'the upstream path a vendored manifest entry names does not exist at the pinned commit',+ fix: 'correct the entry\'s upstream_prefix, file path or commit in the manifest so it names a file that exists upstream at that commit',+ },+ VENDORED_ABSENT_LOCAL: {+ anchor: 'vendored-absent-local',+ summary: 'a vendored manifest lists a file that is not in the commit being checked',+ fix: 'add the file, or remove its entry from the manifest (the repo\'s build writes both, so rebuild them together)',+ },+ VENDORED_MODE: {+ anchor: 'vendored-mode',+ summary: 'a vendored file is an executable, a symlink or a submodule, here or upstream; only plain files (mode 100644 on both sides) count as vendored',+ fix: 'clear the executable bit if the upstream file is a plain file, or remove the entry so the file is reviewed',+ },+ VENDORED_UNREACHABLE: {+ anchor: 'vendored-unreachable',+ summary: 'the pinned commit is not reachable from the upstream\'s default branch, its tags or a branch the base policy names for it (a fork\'s commit, a pull request head, a merge-queue branch or a force-pushed commit), so its files stay in review',+ fix: 'pin a commit on the upstream\'s default branch or a release tag; if the upstream ships from another branch, add it to that upstream\'s branches in review_vendored on the base branch as its own PR',+ },+ VENDORED_NOT_ALLOWLISTED: {+ anchor: 'vendored-not-allowlisted',+ summary: 'a vendored manifest pins files to an upstream that the base branch\'s review_vendored.upstreams does not list; a branch cannot trust a new upstream for itself',+ fix: 'add the upstream URL to review_vendored.upstreams on the base branch as its own PR, then bring the base into the branch and rerun',+ },+ VENDORED_FETCH_FAILED: {+ anchor: 'vendored-fetch-failed',+ summary: 'the upstream could not be fetched anonymously over https (deleted, renamed, private, redirected, or the network failed or timed out), so its files could not be checked and stay in review',+ fix: 'rerun once (a fetch has no side effects); if it fails again, check the URL opens without signing in and does not redirect, and update review_vendored.upstreams on the base if the repository moved',+ },+ VENDORED_MANIFEST_INVALID: {+ anchor: 'vendored-manifest-invalid',+ summary: 'a manifest the base policy lists is missing at the commit being checked or does not follow gstack-vendored/v1 (the line names the field), so none of its files count as vendored',+ fix: 'fix the field the line names (docs/vendored-code.md#the-manifest), usually by rerunning the repo\'s build that writes the manifest',+ },REVIEW_DIFF_UNREADABLE: {anchor: 'review-diff-unreadable',summary: 'git could not read a reviewer\'s diff (reason=timeout after timeout_ms, or reason=git-exit with git\'s exit code), so /ship stopped; the full stderr, with remote URLs redacted, is in the log= file',diff --git a/lib/review-vendored.ts b/lib/review-vendored.tsnew file mode 100644index 000000000..d6f0fd44c--- /dev/null+++ b/lib/review-vendored.ts@@ -0,0 +1,291 @@+/**+ * review-vendored — the review_vendored key of .gstack/ship-policy.json and the check that a vendored file is+ * byte-for-byte an allowlisted upstream's file at a pinned commit (docs/vendored-code.md, GST-3298).+ *+ * The base branch's policy names the upstream repositories a repo trusts and the manifests that pin files to them. A+ * manifest (gstack-vendored/v1, written by the repo's own build) maps each local path, by prefix, to a path at one+ * commit of one upstream. A file is verified only when: its upstream is on the base allowlist; the commit is reachable+ * from that upstream's default branch, one of its tags, or a branch matching a glob the base names for it (never+ * refs/pull/* or another repository in its fork network); and the blob at the upstream path has the same git blob id+ * and mode (100644 on both sides) as the head's file. A blob id is git's hash of the exact bytes, so equal ids mean+ * equal bytes. Anything else is a verdict with a reason code, and a caller treats it as not vendored.+ *+ * Fetches go straight to the upstream over https with no ambient git configuration (no credential helper, extra+ * header or URL rewrite), no prompt, no redirect and a timeout, so a check that passes on one machine passes in CI.+ * Each upstream has two bare caches under the state root: refs.git (commit history only, for reachability) and+ * trees.git (each pin's trees at depth 1, no file contents). Verdicts are cached per pin, so resolveVendored with+ * fetch: false answers offline from what a fetching run recorded.+ */+import { spawnSync } from './spawn-sync';+import { createHash } from 'node:crypto';+import * as fs from 'node:fs';+import * as path from 'node:path';++export const MANIFEST_SCHEMA = 'gstack-vendored/v1';+export interface VendoredUpstream { url: string; branches: string[] }+/** The key as a policy file writes it. */+export interface VendoredPolicyRaw { upstreams: Array<string | { url: string; branches?: string[] }>; manifests: string[] }+export interface VendoredPolicy { upstreams: VendoredUpstream[]; manifests: string[] }+export interface VendoredPin { upstream: string; commit: string; local_prefix: string; upstream_prefix: string; files: string[] }+export interface VendoredEntry { path: string; upstream: string; commit: string; upstream_path: string }+export type VendoredVerdict = 'verified' | 'mismatched' | 'absent-upstream' | 'absent-local' | 'mode' | 'unreachable' | 'not-allowlisted' | 'fetch-failed';+export interface EntryResult extends VendoredEntry { verdict: VendoredVerdict; detail?: string }+export interface PinResult { upstream: string; commit: string; reachable_from: string | null; files: number; verified: number }++/** What \`gstack-ship-policy init --explain\` prints for the key. */+export const VENDORED_EXPLANATION = '{ upstreams, manifests } or null (default), read from the base branch only: upstreams lists the https URLs of the repositories a repo vendors unchanged files from (a string, or { url, branches } to also accept commits on branches matching those globs); manifests lists the repo paths of gstack-vendored/v1 manifests that pin each vendored file to an upstream path at a commit. gstack-vendored-verify checks every pinned file is byte-for-byte that upstream file at a commit reachable from the upstream\'s default branch or a tag; a head cannot add an upstream or a manifest (docs/vendored-code.md).';++const UPSTREAM = /^https:\/\/[a-z0-9]([a-z0-9.-]{0,252}[a-z0-9])?(:[0-9]{1,5})?(\/[A-Za-z0-9_.-]{1,100}){2,4}$/;+const BRANCH_GLOB = /^(?!refs\/)(?!pull\/)(?!gh-readonly-queue\/)[A-Za-z0-9._\/-]*\*?[A-Za-z0-9._\/-]*$/;+type PolicyError = { code: 'POLICY_INVALID'; path: string; message: string };++/** The key normalized: every upstream as { url, branches }; null when the policy does not declare it. */+export function vendoredPolicy(p: { review_vendored?: unknown } | null | undefined): VendoredPolicy | null {+ const v = p?.review_vendored as { upstreams?: Array<string | { url: string; branches?: string[] }>; manifests?: string[] } | null | undefined;+ if (!v) return null;+ return { upstreams: (v.upstreams ?? []).map(u => (typeof u === 'string' ? { url: u, branches: [] } : { url: u.url, branches: u.branches ?? [] })), manifests: [...(v.manifests ?? [])] };+}++/** \`review_vendored\`: each field's error at its path (\`contained\` is lib/ship-policy.ts's containedRelative). */+export function vendoredErrors(value: unknown, out: PolicyError[] | any[], contained: (p: string) => string | null): void {+ if (value === null) return;+ const err = (p: string, message: string) => out.push({ code: 'POLICY_INVALID', path: p, message });+ if (!value || typeof value !== 'object' || Array.isArray(value)) { err('review_vendored', 'must be { upstreams, manifests } or null'); return; }+ const v = value as Record<string, unknown>;+ for (const k of Object.keys(v)) if (k !== 'upstreams' && k !== 'manifests') err(`review_vendored.${k}`, 'unknown key');+ if (!Array.isArray(v.upstreams) || !v.upstreams.length || v.upstreams.length > 64) err('review_vendored.upstreams', 'must be an array of 1 to 64 upstreams');+ else v.upstreams.forEach((u, i) => {+ const at = `review_vendored.upstreams[${i}]`;+ const o = typeof u === 'string' ? { url: u } : u && typeof u === 'object' && !Array.isArray(u) ? (u as Record<string, unknown>) : null;+ if (!o) { err(at, 'must be an https URL or { url, branches? }'); return; }+ for (const k of Object.keys(o)) if (k !== 'url' && k !== 'branches') err(`${at}.${k}`, 'unknown key');+ if (typeof o.url !== 'string' || !UPSTREAM.test(o.url) || /\.\.|\/\.$|\.git\//.test(o.url)) err(at, `${JSON.stringify(o.url)} must be an https URL of a repository (https://github.com/owner/repo), with no credentials, query or fragment`);+ if ('branches' in o && (!Array.isArray(o.branches) || o.branches.length > 16 || o.branches.some(b => typeof b !== 'string' || !b || b.length > 100 || !BRANCH_GLOB.test(b)))) {+ err(`${at}.branches`, 'must be at most 16 branch names or globs with one *, never under refs/, pull/ or gh-readonly-queue/');+ }+ });+ if (Array.isArray(v.upstreams)) {+ const urls = v.upstreams.map(u => (typeof u === 'string' ? u : (u as { url?: unknown })?.url));+ urls.forEach((u, i) => { if (urls.indexOf(u) !== i) err(`review_vendored.upstreams[${i}]`, 'is listed twice'); });+ }+ if (!Array.isArray(v.manifests) || !v.manifests.length || v.manifests.length > 16) err('review_vendored.manifests', 'must be an array of 1 to 16 manifest paths');+ else v.manifests.forEach((m, i) => {+ const why = typeof m !== 'string' ? 'must be a string' : contained(m) ?? (pathProblem(m) ?? (/[*?[\]]/.test(m) ? 'must be a path, not a glob' : null));+ if (why) err(`review_vendored.manifests[${i}]`, `${JSON.stringify(m)} ${why}`);+ });+}++/** Why a repo-relative path is refused, or null: no empty, . or .. segment, leading /, backslash or control character. */+export function pathProblem(p: string): string | null {+ if (!p) return 'is empty';+ if (p.startsWith('/')) return 'must be relative';+ if (/[\\\x00-\x1f\x7f]/.test(p)) return 'contains a backslash or control character';+ if (p.split('/').some(s => s === '' || s === '.' || s === '..')) return 'has an empty, . or .. segment';+ return null;+}++/** A manifest's pins and every problem with it; entries are the pins flattened to one row per file. */+export function parseManifest(text: string, where: string): { pins: VendoredPin[]; entries: VendoredEntry[]; errors: string[] } {+ const errors: string[] = [];+ let raw: unknown;+ try { raw = JSON.parse(text); } catch (e) { return { pins: [], entries: [], errors: [`${where}: not JSON (${(e as Error).message})`] }; }+ const m = raw as { schema?: unknown; pins?: unknown };+ if (!m || typeof m !== 'object' || m.schema !== MANIFEST_SCHEMA) errors.push(`${where}: schema must be "${MANIFEST_SCHEMA}"`);+ if (!Array.isArray(m?.pins) || !m.pins.length) return { pins: [], entries: [], errors: [...errors, `${where}: pins must be a non-empty array`] };+ const pins: VendoredPin[] = [];+ const entries: VendoredEntry[] = [];+ const seen = new Map<string, string>();+ m.pins.forEach((p: any, i: number) => {+ const at = `${where}: pins[${i}]`;+ const bad = (s: string) => errors.push(`${at}${s}`);+ if (!p || typeof p !== 'object') { bad(' must be an object'); return; }+ for (const k of Object.keys(p)) if (!['upstream', 'commit', 'local_prefix', 'upstream_prefix', 'files'].includes(k)) bad(`.${k}: unknown key`);+ if (typeof p.upstream !== 'string' || !UPSTREAM.test(p.upstream)) bad('.upstream must be an https repository URL');+ if (typeof p.commit !== 'string' || !/^[0-9a-f]{40}$/.test(p.commit)) bad('.commit must be a full 40-character lowercase commit id');+ for (const k of ['local_prefix', 'upstream_prefix'] as const) {+ const v = p[k];+ if (typeof v !== 'string' || (v !== '' && (!v.endsWith('/') || pathProblem(v.slice(0, -1)))) || (k === 'local_prefix' && v === '')) bad(`.${k} must be ${k === 'local_prefix' ? 'a' : '"" or a'} repo-relative directory ending in /`);+ }+ if (!Array.isArray(p.files) || !p.files.length) { bad('.files must be a non-empty array'); return; }+ const ok = errors.length;+ p.files.forEach((f: unknown, j: number) => { const why = typeof f !== 'string' ? 'must be a string' : pathProblem(f); if (why) bad(`.files[${j}] ${JSON.stringify(f)} ${why}`); });+ if (errors.length !== ok || typeof p.local_prefix !== 'string' || typeof p.upstream_prefix !== 'string') return;+ pins.push({ upstream: p.upstream, commit: p.commit, local_prefix: p.local_prefix, upstream_prefix: p.upstream_prefix, files: [...p.files] });+ for (const f of p.files as string[]) {+ const local = p.local_prefix + f;+ const folded = local.toLowerCase();+ if (seen.has(folded)) { bad(`: ${local} collides with ${seen.get(folded)} (listed twice, or the same path in another letter case)`); continue; }+ seen.set(folded, local);+ entries.push({ path: local, upstream: p.upstream, commit: p.commit, upstream_path: p.upstream_prefix + f });+ }+ });+ return { pins, entries, errors };+}++/** The fetch environment: no global or system git config, no prompt, nothing that lets ambient credentials or rewrites in. */+function gitEnv(cache: string): NodeJS.ProcessEnv {+ const empty = path.join(cache, 'empty.gitconfig');+ if (!fs.existsSync(empty)) fs.writeFileSync(empty, '');+ const keep = Object.fromEntries(['SYSTEMROOT', 'SystemRoot', 'TEMP', 'TMP', 'TMPDIR'].flatMap(k => (process.env[k] ? [[k, process.env[k]!]] : [])));+ return { ...keep, PATH: process.env.PATH ?? '', HOME: cache, GIT_CONFIG_GLOBAL: empty, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', GCM_INTERACTIVE: 'never', LANG: 'C', LC_ALL: 'C' };+}++const TEST_ROOT = 'GSTACK_VENDORED_FETCH_ROOT';+/** Where a fetch goes: the upstream itself, or (tests only) the same host/path under GSTACK_VENDORED_FETCH_ROOT. */+export function fetchUrl(url: string, env: NodeJS.ProcessEnv = process.env): string {+ const root = env[TEST_ROOT];+ return root ? `${root.replace(/\/+$/, '')}/${url.replace(/^https:\/\//, '')}` : url;+}++function remoteFlags(env: NodeJS.ProcessEnv): string[] {+ const test = !!env[TEST_ROOT];+ return ['-c', 'credential.helper=', '-c', 'http.extraHeader=', '-c', 'http.followRedirects=false', '-c', 'protocol.allow=never', '-c', 'protocol.https.allow=always',+ ...(test ? ['-c', 'protocol.file.allow=always', '-c', 'protocol.http.allow=always'] : []), '-c', 'http.lowSpeedLimit=1000', '-c', 'http.lowSpeedTime=30'];+}++const timeoutMs = (env: NodeJS.ProcessEnv) => { const n = Number(env.GSTACK_VENDORED_FETCH_TIMEOUT_MS); return Number.isFinite(n) && n > 0 ? n : 180_000; };++function git(cwd: string, args: string[], env: NodeJS.ProcessEnv, timeout = 60_000): { ok: boolean; out: string; err: string } {+ const r = spawnSync('git', args, { cwd, env, encoding: 'utf8', timeout, maxBuffer: 256 * 1024 * 1024 });+ return { ok: r.status === 0, out: r.stdout ?? '', err: `${r.stderr ?? ''}${r.error ? ` ${r.error.message}` : ''}`.trim() };+}++/** One lock file per upstream cache; a lock older than ten minutes belonged to a dead process. */+function withLock<T>(dir: string, fn: () => T): T {+ const lock = path.join(dir, 'lock');+ for (let i = 0; ; i++) {+ try { fs.writeFileSync(lock, String(process.pid), { flag: 'wx' }); break; } catch {+ try { if (Date.now() - fs.statSync(lock).mtimeMs > 600_000) { fs.rmSync(lock, { force: true }); continue; } } catch { continue; }+ if (i > 600) throw new Error(`vendored cache ${dir} stayed locked`);+ Bun.sleepSync(100);+ }+ }+ try { return fn(); } finally { fs.rmSync(lock, { force: true }); }+}++interface PinCache { reachable_from: string | null; default_branch?: string; checked_at: number; tree: Record<string, [string, string] | null>; error?: string }++/** Whether a cached ref the commit sits on is one the current policy trusts: a tag, the default branch, or a branch the base names, never a merge-queue branch. */+function trustedHolder(ref: string, def: string | undefined, up: VendoredUpstream): boolean {+ if (ref.startsWith('tags/')) return true;+ if (!ref.startsWith('heads/')) return false;+ const branch = ref.slice('heads/'.length);+ if (branch.startsWith('gh-readonly-queue/')) return false;+ return branch === def || up.branches.some(g => new RegExp(`^${g.split('*').map(s => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`).test(branch));+}+const key = (url: string) => createHash('sha256').update(url).digest('hex').slice(0, 24);+const pinFile = (dir: string, commit: string) => path.join(dir, 'pins', `${commit}.json`);+function readPin(dir: string, commit: string): PinCache | null { try { return JSON.parse(fs.readFileSync(pinFile(dir, commit), 'utf8')) as PinCache; } catch { return null; } }+function writePin(dir: string, commit: string, p: PinCache): void {+ fs.mkdirSync(path.join(dir, 'pins'), { recursive: true });+ const f = pinFile(dir, commit);+ fs.writeFileSync(`${f}.tmp`, JSON.stringify(p));+ fs.renameSync(`${f}.tmp`, f);+}++/**+ * Fetch one upstream's reachability refs and each pin's trees into its cache and record, per pin, the ref that holds+ * the commit and the mode and blob id of every upstream path asked for. A failed fetch is recorded as the pin's error.+ */+function fetchUpstream(cacheRoot: string, up: VendoredUpstream, pins: Map<string, Set<string>>, env: NodeJS.ProcessEnv): void {+ const dir = path.join(cacheRoot, key(up.url));+ fs.mkdirSync(dir, { recursive: true });+ withLock(dir, () => {+ const genv = gitEnv(dir);+ const flags = remoteFlags(env);+ const url = fetchUrl(up.url, env);+ const t = timeoutMs(env);+ for (const repo of ['refs.git', 'trees.git']) if (!fs.existsSync(path.join(dir, repo, 'HEAD'))) git(dir, ['init', '--quiet', '--bare', repo], genv);+ const refs = path.join(dir, 'refs.git');+ const trees = path.join(dir, 'trees.git');+ const fail = (error: string) => { for (const c of pins.keys()) writePin(dir, c, { reachable_from: null, checked_at: Date.now(), tree: {}, error }); };+ const head = git(refs, [...flags, 'ls-remote', '--symref', url, 'HEAD', 'refs/heads/*'], genv, t);+ const def = /^ref: refs\/heads\/(\S+)\tHEAD$/m.exec(head.out)?.[1];+ if (!head.ok || !def) { fail(`could not read the default branch (${head.err.split('\n').pop() || 'no HEAD'})`); return; }+ const heads = new Set(head.out.split('\n').map(l => l.split('\t')[1]).filter(Boolean));+ const named = up.branches.filter(b => b.includes('*') || heads.has(`refs/heads/${b}`));+ const specs = [`+refs/heads/${def}:refs/vendored/heads/${def}`, '+refs/tags/*:refs/vendored/tags/*', ...named.map(b => `+refs/heads/${b}:refs/vendored/heads/${b}`)];+ const f = git(refs, [...flags, 'fetch', '--quiet', '--no-tags', '--prune', '--filter=tree:0', url, ...specs], genv, t);+ if (!f.ok) { fail(`could not fetch its branches and tags (${f.err.split('\n').pop()})`); return; }+ for (const [commit, paths] of pins) {+ const has = git(refs, ['cat-file', '-e', `${commit}^{commit}`], genv).ok;+ const holders = has ? git(refs, ['for-each-ref', '--format=%(refname)', '--contains', commit, 'refs/vendored/'], genv).out.split('\n').map(r => r.trim().replace(/^refs\/vendored\//, '')) : [];+ const reachable_from = holders.find(r => r && trustedHolder(r, def, up)) ?? null;+ if (!reachable_from) { writePin(dir, commit, { reachable_from: null, default_branch: def, checked_at: Date.now(), tree: {} }); continue; }+ const tf = git(trees, [...flags, 'fetch', '--quiet', '--no-tags', '--depth=1', '--filter=blob:none', url, commit], genv, t);+ if (!tf.ok) { writePin(dir, commit, { reachable_from, default_branch: def, checked_at: Date.now(), tree: {}, error: `could not fetch the commit's trees (${tf.err.split('\n').pop()})` }); continue; }+ const ls = git(trees, ['ls-tree', '-r', '-z', '--full-tree', commit], genv);+ if (!ls.ok) { writePin(dir, commit, { reachable_from, default_branch: def, checked_at: Date.now(), tree: {}, error: 'could not list the commit\'s tree' }); continue; }+ const all = new Map<string, [string, string]>();+ for (const rec of ls.out.split('\0')) { const m = /^(\d{6}) (?:blob|commit) ([0-9a-f]{40,64})\t([\s\S]+)$/.exec(rec); if (m) all.set(m[3]!, [m[1]!, m[2]!]); }+ const prev = readPin(dir, commit);+ const tree: Record<string, [string, string] | null> = { ...(prev?.reachable_from ? prev.tree : {}) };+ for (const p of paths) tree[p] = all.get(p) ?? null;+ writePin(dir, commit, { reachable_from, default_branch: def, checked_at: Date.now(), tree });+ }+ });+}++/** The head's mode and blob id for each path (git ls-tree under each pin's prefix); missing paths are absent. */+function headBlobs(root: string, rev: string, entries: readonly VendoredEntry[]): Map<string, [string, string]> | null {+ const out = new Map<string, [string, string]>();+ const prefixes = [...new Set(entries.map(e => e.path.slice(0, e.path.lastIndexOf('/') + 1)))].sort();+ const roots = prefixes.filter((p, i) => !prefixes.slice(0, i).some(q => p.startsWith(q)));+ for (let i = 0; i < roots.length; i += 200) {+ const r = spawnSync('git', ['ls-tree', '-r', '-z', '--full-tree', rev, '--', ...roots.slice(i, i + 200).map(p => `:(top,literal)${p || '.'}`)], { cwd: root, encoding: 'utf8', timeout: 120_000, maxBuffer: 256 * 1024 * 1024 });+ if (r.status !== 0) return null;+ for (const rec of (r.stdout ?? '').split('\0')) { const m = /^(\d{6}) (\w+) ([0-9a-f]{40,64})\t([\s\S]+)$/.exec(rec); if (m) out.set(m[4]!, [m[1]!, m[3]!]); }+ }+ return out;+}++export interface ResolveInput {+ root: string; rev: string; policy: VendoredPolicy; entries: readonly VendoredEntry[];+ /** Fetch upstreams and refresh the cache (gstack-vendored-verify); false answers from the cache alone. */+ fetch: boolean; cacheRoot: string; env?: NodeJS.ProcessEnv;+}++/** One verdict per entry, one summary per pin, and a digest over both; null when git could not read the head. */+export function resolveVendored(i: ResolveInput): { entries: EntryResult[]; pins: PinResult[]; digest: string } | null {+ const env = i.env ?? process.env;+ const allowed = new Map(i.policy.upstreams.map(u => [u.url, u]));+ const byUpstream = new Map<string, Map<string, Set<string>>>();+ for (const e of i.entries) {+ if (!allowed.has(e.upstream)) continue;+ const pins = byUpstream.get(e.upstream) ?? new Map<string, Set<string>>();+ pins.set(e.commit, (pins.get(e.commit) ?? new Set()).add(e.upstream_path));+ byUpstream.set(e.upstream, pins);+ }+ if (i.fetch) for (const [url, pins] of byUpstream) fetchUpstream(i.cacheRoot, allowed.get(url)!, pins, env);+ const head = headBlobs(i.root, i.rev, i.entries);+ if (!head) return null;+ const results: EntryResult[] = i.entries.map(e => {+ const local = head.get(e.path);+ if (!allowed.has(e.upstream)) return { ...e, verdict: 'not-allowlisted' };+ if (!local) return { ...e, verdict: 'absent-local' };+ const pin = readPin(path.join(i.cacheRoot, key(e.upstream)), e.commit);+ if (!pin || !(e.upstream_path in pin.tree) && !pin.error && pin.reachable_from) return { ...e, verdict: 'fetch-failed', detail: 'not in the cache; run gstack-vendored-verify' };+ if (pin.error) return { ...e, verdict: 'fetch-failed', detail: pin.error };+ if (!pin.reachable_from) return { ...e, verdict: 'unreachable' };+ if (!trustedHolder(pin.reachable_from, pin.default_branch, allowed.get(e.upstream)!)) return { ...e, verdict: 'unreachable', detail: `the cached ref ${pin.reachable_from} is not a tag, the default branch or a branch the base names` };+ const up = pin.tree[e.upstream_path];+ if (!up) return { ...e, verdict: 'absent-upstream' };+ if (local[0] !== '100644' || up[0] !== '100644') return { ...e, verdict: 'mode', detail: `head ${local[0]}, upstream ${up[0]}` };+ return local[1] === up[1] ? { ...e, verdict: 'verified' } : { ...e, verdict: 'mismatched', detail: `head blob ${local[1].slice(0, 12)}, upstream blob ${up[1].slice(0, 12)}` };+ });+ const pinRows = new Map<string, PinResult>();+ for (const r of results) {+ const k = `${r.upstream}@${r.commit}`;+ const row = pinRows.get(k) ?? { upstream: r.upstream, commit: r.commit, reachable_from: allowed.has(r.upstream) ? readPin(path.join(i.cacheRoot, key(r.upstream)), r.commit)?.reachable_from ?? null : null, files: 0, verified: 0 };+ row.files++;+ if (r.verdict === 'verified') row.verified++;+ pinRows.set(k, row);+ }+ const pins = [...pinRows.values()].sort((a, b) => (a.upstream + a.commit < b.upstream + b.commit ? -1 : 1));+ const sorted = [...results].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+ const digest = createHash('sha256').update(JSON.stringify({ policy: i.policy, entries: sorted.map(r => [r.path, r.upstream, r.commit, r.upstream_path, r.verdict]) })).digest('hex');+ return { entries: sorted, pins, digest };+}++/** The cache directory under a state root. */+export const vendoredCacheRoot = (stateRoot: string) => path.join(stateRoot, 'vendored-cache');diff --git a/lib/ship-policy-keys.ts b/lib/ship-policy-keys.tsindex b431d0356..e0657af88 100644--- a/lib/ship-policy-keys.ts+++ b/lib/ship-policy-keys.ts@@ -58,6 +58,7 @@ export const LAND_DOCS_ONLY_SKIP_KEY_VERSION = '1.99.0.0';export const HISTORY_NO_REWRITE_KEY_VERSION = '1.100.0.0';export const LAND_MERGE_COMMIT_PATHS_KEY_VERSION = '1.100.0.0';export const REVIEW_CONTENT_KEY_VERSION = '1.102.0.0';+export const REVIEW_VENDORED_KEY_VERSION = '1.102.3.0';export const POLICY_KEY_INTRODUCED: Record<PolicyKey, string> = {bump: '1.91.73.0', queue_mode: '1.91.73.0', release_tool: '1.91.73.0', release_outputs: '1.91.73.0', stamp_paths: '1.91.73.0',changelog: '1.91.73.0', mirror: '1.91.73.0', history: '1.91.73.0', preregistration_shas: '1.91.73.0', stamp_sensitive_gates: '1.91.73.0',@@ -68,5 +69,5 @@ export const POLICY_KEY_INTRODUCED: Record<PolicyKey, string> = {base_red: BASE_RED_KEY_VERSION, review_exclude_paths: REVIEW_EXCLUDE_KEY_VERSION, review_content_patterns: REVIEW_CONTENT_KEY_VERSION, review: REVIEW_POLICY_KEY_VERSION, release_gate: RELEASE_GATE_KEY_VERSION,stamp_placeholders: STAMP_PLACEHOLDERS_KEY_VERSION, merge: MERGE_KEY_VERSION, land: LAND_KEY_VERSION, readers: READERS_KEY_VERSION,bookkeeping: BOOKKEEPING_KEY_VERSION, mechanical_retake: MECHANICAL_RETAKE_KEY_VERSION, test_code: TEST_CODE_KEY_VERSION, ci_record_timeout_s: CI_RECORD_TIMEOUT_KEY_VERSION,- plan_record: PLAN_RECORD_KEY_VERSION, docs_only: DOCS_ONLY_KEY_VERSION,+ plan_record: PLAN_RECORD_KEY_VERSION, docs_only: DOCS_ONLY_KEY_VERSION, review_vendored: REVIEW_VENDORED_KEY_VERSION,};diff --git a/lib/ship-policy.ts b/lib/ship-policy.tsindex bafd4bf08..e838323e1 100644--- a/lib/ship-policy.ts+++ b/lib/ship-policy.ts@@ -21,7 +21,7 @@ import { LAND_EXPLANATION, LAND_KEYS, landPolicyErrors, type LandPolicy } from 'import { DOCS_ONLY_KEYS, docsOnlyPolicyErrors, unknownKeyWarnings, type DocsOnlyPolicy, type PolicyWarning } from './ship-policy-docs-only';import { RESULT_CODES, type ResultCodeName } from './result-codes';import { reviewErrors, type ReviewPolicy } from './ship-policy-review';-import { READERS_EXPLANATION, readersErrors, type ReadersPolicy } from './ship-policy-readers';+import { READERS_EXPLANATION, readersErrors, type ReadersPolicy } from './ship-policy-readers'; import { VENDORED_EXPLANATION, vendoredErrors, type VendoredPolicyRaw } from './review-vendored';import { cmpVersion, parseVersion } from './version-source';import { POLICY_COMPAT_FLOOR, BUMP_NEVER_KEY_VERSION, TRAIN_GATES_KEY_VERSION, POLICY_KEY_INTRODUCED, LAND_DOCS_ONLY_SKIP_KEY_VERSION, HISTORY_NO_REWRITE_KEY_VERSION, LAND_MERGE_COMMIT_PATHS_KEY_VERSION } from './ship-policy-keys';import { placeholderErrors, templateErrors } from './ship-policy-stamps';@@ -70,6 +70,7 @@ export interface ShipPolicy {review_content_patterns: string[];/** How much review /ship runs (docs/review-policy.md#review-depth): the panel fallback, the risk reader's model, platform review and extra risk paths; read from the base only. */ review: ReviewPolicy;/** What /ship's readers may not fetch or open beyond the default fetch rule, and the one-line note every brief carries; the base governs, the head may only add (docs/ship-policy.md#readers). */ readers: ReadersPolicy;+ /** The upstreams a repo vendors unchanged files from and the manifests that pin them; read from the base only (docs/vendored-code.md). */ review_vendored: VendoredPolicyRaw | null;/** Consumed by the plan reviews (D1). */pr_count: { default_pr_count: number; split_requires_owner: boolean };/** Maintainer logins for contributor-PR mode (E3); empty means "use push permission". */@@ -198,7 +199,7 @@ export const DEFAULT_POLICY: ShipPolicy = {train: null,docs: null,base_red: null, merge: 'train', land: null, bookkeeping: [], mechanical_retake: [], test_code: [],- release_gate: null, readers: { forbid_fetch: [], forbid_paths: [], brief_note: null }, ci_record_timeout_s: 600,+ release_gate: null, readers: { forbid_fetch: [], forbid_paths: [], brief_note: null }, review_vendored: null, ci_record_timeout_s: 600,plan_record: 'off', docs_only: null,};@@ -222,7 +223,7 @@ export const POLICY_EXPLANATIONS: Record<PolicyKey, string> = {review_exclude_paths: 'Git glob pathspecs, root-anchored and case-sensitive (`receipts/**`, `**/*.jsonl`; at most 64, 256 characters each, no leading `:` or `!`): /ship\'s reviewers leave out the data, docs, binary and .log files they match. Read from the base branch only, so a branch cannot exclude its own files. Code, gate paths, agent prose, config, executables, .gstack/ and .github/ files, gate-tagged or secret-bearing files and files a kept code or test file names by full path stay reviewed (docs/ship-policy.md#review-exclude-paths).',review_content_patterns: 'Git glob pathspecs in the same dialect as review_exclude_paths (`results/*/raw/**`): a file both keys match is content, so the exclusion leaves it out whatever its extension (.patch files, MANIFEST.sha256, extension-less licence texts). Explicit policy only: nothing is inferred, and a pattern here with no review_exclude_paths pattern over the same files excludes nothing. Read from the base branch only. Gate paths, agent prose, config, source files (.ts, .py, .sh and the like), executables, links, native binaries, .gstack/ and .github/ files, gate-tagged or secret-bearing files and files a kept code or test file names by full path stay reviewed (docs/ship-policy.md#review-content-patterns).',review: '{ panel?, reader_model?, platform?, risk_paths? }, read from the base branch only. panel: all (default: today\'s panel and loop everywhere) | risk (opt-in: today\'s panel at full depth on risk class, one reader on the rest) | off (one merged reader on risk class too); risk and off run one fix round. Their one-reader shape has not passed a no-loss replay yet (GSTA-258 C: FIX-METHOD). reader_model: the model of the one reader a lean depth runs, `lane` (default: the lane\'s own model, the native adversarial reader), `cross-family` or a model id. platform: off (default) | on: a docs or tests diff with no numeric, results or prereg claims whose PR carries the platform review (capy-ai[bot]) at the exact head skips /ship\'s readers (review_depth platform); never runtime code. risk_paths: globs of code paths that are risk class on top of R51\'s; data, docs and binary files under them stay out (docs/review-policy.md#review-depth).',- readers: READERS_EXPLANATION,+ readers: READERS_EXPLANATION, review_vendored: VENDORED_EXPLANATION,pr_count: '{ default_pr_count, split_requires_owner }: the PR-count row in plan reviews.',maintainers: 'GitHub logins treated as maintainers by /review contributor mode; empty uses repository push permission.',stamp_files: 'The repo’s stamp rule: globs of the only files that may differ by a stamp (version file, manifests, plugin trees, the PR’s own since: rows). Empty keeps gstack’s per-file rules; set, it applies before every rule.',@@ -481,6 +482,7 @@ export function validatePolicy(raw: unknown, opts: { gstackVersion?: string } =if ('review_content_patterns' in obj) excludeErrors('review_content_patterns', obj.review_content_patterns, errors);if ('review' in obj) reviewErrors(obj.review, errors, (k, v) => listErrors(k, v, errors, globError));if ('readers' in obj) readersErrors(obj.readers, errors, containedRelative);+ if ('review_vendored' in obj) vendoredErrors(obj.review_vendored, errors, containedRelative);if ('release_tool' in obj && obj.release_tool !== null) {const t = obj.release_tool;if (typeof t !== 'string' || !t.trim()) errors.push({ code: 'POLICY_INVALID', path: 'release_tool', message: 'must be a non-empty string or null' });diff --git a/test/egress-receipt-wiring.test.ts b/test/egress-receipt-wiring.test.tsindex adb32b989..10bc11e7a 100644--- a/test/egress-receipt-wiring.test.ts+++ b/test/egress-receipt-wiring.test.ts@@ -162,6 +162,8 @@ const SCANNER_EXEMPT: Record<string, string> = {'git fetch appears only in the revision row\'s fix string (the command the user runs to move the checkout)','bin/gstack-next-version':'fetches the user\'s own repo\'s base branch for version-claim freshness — a user-repo dev-workflow op, not gstack-state egress',+ 'bin/gstack-vendored-verify':+ 'git fetch appears only in the fix string of the base-resolution error; the CLI\'s own upstream fetches live in lib/review-vendored.ts (anonymous download of allowlisted public upstreams by commit, no gstack or user state sent)','bin/gstack-version-bump':'git fetch appears only in an error-message string','bin/gstack-worktree-audit':diff --git a/test/review-vendored.test.ts b/test/review-vendored.test.tsnew file mode 100644index 000000000..c100ca49e--- /dev/null+++ b/test/review-vendored.test.ts@@ -0,0 +1,284 @@+/**+ * review_vendored and gstack-vendored-verify (GST-3298, docs/vendored-code.md): a vendored file counts only when it is+ * byte-for-byte an allowlisted upstream's file at a commit that upstream's default branch, tags or named branches hold.+ * Upstreams are local bare repositories reached through GSTACK_VENDORED_FETCH_ROOT; every consumer repo's global git+ * config rewrites that root to a missing directory, so a fetch that read ambient git configuration would fail.+ */+import { afterEach, describe, expect, setDefaultTimeout, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import { bunIsolationArgs } from '../lib/bun-isolation';+import { REVIEW_VENDORED_KEY_VERSION, finish } from '../lib/ship-policy';+import { parseManifest, pathProblem, vendoredErrors } from '../lib/review-vendored';+import { cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture';++setDefaultTimeout(60_000);+const repos: FixtureRepo[] = [];+const dirs: string[] = [];+afterEach(() => { while (repos.length) cleanup(repos.pop()!); while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); });++const UP = 'https://example.test/up/lib';+const A = 'def test_a():\n assert 1 + 1 == 2\n';+const B1 = 'def test_b():\n assert "x".upper() == "X"\n';+const B2 = B1 + '\ndef test_c():\n assert [] == []\n';+const ENV = { GIT_AUTHOR_DATE: '2026-01-01T00:00:00Z', GIT_COMMITTER_DATE: '2026-01-01T00:00:00Z' };++function run(cwd: string, args: string[], env: Record<string, string>): string {+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000, env: { ...process.env, ...env, ...ENV } });+ if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);+ return r.stdout.trim();+}++/** An upstream at <fetchRoot>/example.test/up/lib: c1 (tag v1), c2 on main, and commits held only by a pull ref, a merge-queue branch and release/2. */+function upstream(fetchRoot: string, env: Record<string, string>) {+ const bare = path.join(fetchRoot, 'example.test', 'up', 'lib');+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-vendored-up-'));+ dirs.push(work);+ fs.mkdirSync(bare, { recursive: true });+ run(bare, ['init', '-q', '--bare', '-b', 'main'], env);+ run(work, ['init', '-q', '-b', 'main'], env);+ const put = (rel: string, text: string) => { fs.mkdirSync(path.dirname(path.join(work, rel)), { recursive: true }); fs.writeFileSync(path.join(work, rel), text); };+ const snap = (msg: string) => { run(work, ['add', '-A'], env); run(work, ['commit', '-q', '-m', msg], env); return run(work, ['rev-parse', 'HEAD'], env); };+ put('tests/a.py', A); put('tests/b.py', B1); put('README.md', 'lib\n');+ const c1 = snap('c1');+ run(work, ['tag', 'v1'], env);+ put('tests/b.py', B2);+ const c2 = snap('c2');+ const side = (name: string) => { run(work, ['checkout', '-q', '-b', name, c1], env); put('tests/a.py', A + '# ' + name + '\n'); const c = snap(name); run(work, ['checkout', '-q', 'main'], env); return c; };+ const pull = side('pr'); const queue = side('queue'); const release = side('rel');+ run(work, ['push', '-q', bare, 'main', 'v1', `${pull}:refs/pull/1/head`, `${queue}:refs/heads/gh-readonly-queue/main/pr-1`, `${release}:refs/heads/release/2`], env);+ return { bare, work, c1, c2, pull, queue, release };+}++interface Pin { upstream?: string; commit: string; local_prefix?: string; upstream_prefix?: string; files: string[] }+const manifest = (pins: Pin[]) => JSON.stringify({ schema: 'gstack-vendored/v1', pins: pins.map(p => ({ upstream: UP, local_prefix: 'vendor/lib/', upstream_prefix: '', ...p })) }, null, 1) + '\n';+const policy = (upstreams: unknown[] = [UP]) => JSON.stringify({ review_vendored: { upstreams, manifests: ['vendor/MANIFEST.json'] }, min_gstack_version: REVIEW_VENDORED_KEY_VERSION }) + '\n';++/** A consumer repo whose base declares review_vendored; the branch adds vendor/lib/tests/*.py and the manifest. */+function consumer(opts: { policy?: string; files?: Record<string, string | null>; pins?: Pin[] } = {}) {+ const repo = makeFixtureRepo({ prefix: 'gstack-vendored-', baseFiles: { '.gstack/ship-policy.json': opts.policy ?? policy() } });+ repos.push(repo);+ const fetchRoot = path.join(repo.root, 'upstreams');+ const up = upstream(fetchRoot, repo.env);+ const upEnv = { ...repo.env, GIT_CONFIG_GLOBAL: path.join(repo.root, 'upstream.gitconfig') };+ fs.copyFileSync(repo.env.GIT_CONFIG_GLOBAL, upEnv.GIT_CONFIG_GLOBAL);+ fs.appendFileSync(repo.env.GIT_CONFIG_GLOBAL, `[url "/nonexistent/"]\n\tinsteadOf = "${fetchRoot.replace(/\\/g, '\\\\')}/"\n`);+ repo.git('checkout', '-q', '-b', 'feat');+ commit(repo, { 'vendor/lib/tests/a.py': A, 'vendor/lib/tests/b.py': B1, 'vendor/MANIFEST.json': manifest(opts.pins ?? [{ commit: up.c1, files: ['tests/a.py', 'tests/b.py'] }]), ...(opts.files ?? {}) }, 'vendor lib');+ const verify = (args: string[] = ['--base', 'main'], env: Record<string, string> = {}) => runBin(repo, 'gstack-vendored-verify', args, { GSTACK_VENDORED_FETCH_ROOT: fetchRoot, ...env });+ return { repo, up, upEnv, fetchRoot, verify };+}+const outOf = (r: { out: string; err: string }) => `${r.out}${r.err}`;++describe('manifest and policy shapes', () => {+ test('path problems refuse .., absolute, backslash and empty segments', () => {+ for (const p of ['../x', 'a/../b', '/abs', 'a\\b', 'a//b', './a', '']) expect(pathProblem(p)).not.toBeNull();+ expect(pathProblem('tests/test_x.py')).toBeNull();+ });+ test('a manifest refuses short commits, prefixes without a slash, case collisions and duplicates', () => {+ const c = 'a'.repeat(40);+ const bad = parseManifest(JSON.stringify({ schema: 'gstack-vendored/v1', pins: [+ { upstream: UP, commit: 'abc123', local_prefix: 'v/', upstream_prefix: '', files: ['x.py'] },+ { upstream: UP, commit: c, local_prefix: 'v', upstream_prefix: '', files: ['x.py'] },+ { upstream: UP, commit: c, local_prefix: 'w/', upstream_prefix: '', files: ['A.py', 'a.py', '../b.py'] },+ ] }), 'm.json');+ expect(bad.errors.join('\n')).toMatch(/40-character/);+ expect(bad.errors.join('\n')).toMatch(/local_prefix/);+ expect(bad.errors.join('\n')).toMatch(/\.\. segment/);+ const dup = parseManifest(JSON.stringify({ schema: 'gstack-vendored/v1', pins: [{ upstream: UP, commit: c, local_prefix: 'w/', upstream_prefix: 'src/', files: ['A.py', 'a.py'] }] }), 'm.json');+ expect(dup.errors.join('\n')).toMatch(/collides/);+ const ok = parseManifest(JSON.stringify({ schema: 'gstack-vendored/v1', pins: [{ upstream: UP, commit: c, local_prefix: 'w/', upstream_prefix: 'src/', files: ['a.py'] }] }), 'm.json');+ expect(ok.errors).toEqual([]);+ expect(ok.entries).toEqual([{ path: 'w/a.py', upstream: UP, commit: c, upstream_path: 'src/a.py' }]);+ });+ test('the policy key validates through the ship policy and refuses pull and merge-queue branch globs', () => {+ const errs = (v: unknown) => { const out: Array<{ path: string; message: string }> = []; vendoredErrors(v, out, () => null); return out.map(e => `${e.path}: ${e.message}`).join('\n'); };+ expect(errs({ upstreams: [UP], manifests: ['vendor/MANIFEST.json'] })).toBe('');+ expect(errs({ upstreams: [{ url: UP, branches: ['release/*'] }], manifests: ['m.json'] })).toBe('');+ for (const b of ['pull/*', 'gh-readonly-queue/*', 'refs/heads/x']) expect(errs({ upstreams: [{ url: UP, branches: [b] }], manifests: ['m.json'] })).toMatch(/branches/);+ expect(errs({ upstreams: ['http://example.test/up/lib'], manifests: ['m.json'] })).toMatch(/https URL/);+ expect(errs({ upstreams: [['https://user', '[email protected]/up/lib'].join(':')], manifests: ['m.json'] })).toMatch(/https URL/);+ expect(errs({ upstreams: [UP], manifests: ['vendor/*.json'] })).toMatch(/not a glob/);+ const loaded = finish(JSON.stringify({ review_vendored: { upstreams: [UP], manifests: ['m.json'] } }), { kind: 'head', label: 'x', ref: 'x', sha: 'x' } as never) as { errors: Array<{ path: string; message: string }> };+ expect(loaded.errors.map(e => e.message).join('\n')).toContain(REVIEW_VENDORED_KEY_VERSION);+ });+});++describe('gstack-vendored-verify', () => {+ test('files byte-identical to a tagged upstream commit verify, through no ambient git configuration', () => {+ const { verify } = consumer();+ const r = verify();+ expect(outOf(r)).toMatch(/VENDORED_PIN: https:\/\/example\.test\/up\/lib@[0-9a-f]{12} reachable_from=(heads\/main|tags\/v1) files=2 verified=2/);+ expect(outOf(r)).toMatch(/VENDORED_VERIFY: checked=2 verified=2 failed=0 pins=1 manifests=1 scope=changed digest=[0-9a-f]{64}/);+ expect(r.status).toBe(0);+ });+ test('one changed byte fails as a mismatch with its fix', () => {+ const { verify } = consumer({ files: { 'vendor/lib/tests/b.py': B1.replace('X', 'Y') } });+ const r = verify();+ expect(outOf(r)).toMatch(/vendor\/lib\/tests\/b\.py <- .*tests\/b\.py.*fix: restore the upstream bytes.*\(VENDORED_MISMATCH\)/);+ expect(r.status).toBe(1);+ });+ test('commits only a pull ref or a merge-queue branch hold are unreachable; a base-named branch glob admits release/2', () => {+ for (const which of ['pull', 'queue'] as const) {+ const c = consumer();+ const pin = which === 'pull' ? c.up.pull : c.up.queue;+ commit(c.repo, { 'vendor/lib/tests/a.py': A + '# ' + (which === 'pull' ? 'pr' : 'queue') + '\n', 'vendor/MANIFEST.json': manifest([{ commit: pin, files: ['tests/a.py'] }]) }, 'pin');+ const r = c.verify();+ expect(outOf(r)).toContain('(VENDORED_UNREACHABLE)');+ expect(r.status).toBe(1);+ }+ const plain = consumer();+ commit(plain.repo, { 'vendor/lib/tests/a.py': A + '# rel\n', 'vendor/MANIFEST.json': manifest([{ commit: plain.up.release, files: ['tests/a.py'] }]) }, 'pin');+ expect(outOf(plain.verify())).toContain('(VENDORED_UNREACHABLE)');+ const named = consumer({ policy: policy([{ url: UP, branches: ['release/*'] }]) });+ commit(named.repo, { 'vendor/lib/tests/a.py': A + '# rel\n', 'vendor/MANIFEST.json': manifest([{ commit: named.up.release, files: ['tests/a.py'] }]) }, 'pin');+ const r = named.verify();+ expect(outOf(r)).toContain('reachable_from=heads/release/2');+ expect(r.status).toBe(0);+ });+ test('a branch glob the base drops stops admitting its commits on a warm cache, online and offline', () => {+ const c = consumer({ policy: policy([{ url: UP, branches: ['release/*'] }]) });+ commit(c.repo, { 'vendor/lib/tests/a.py': A + '# rel\n', 'vendor/MANIFEST.json': manifest([{ commit: c.up.release, files: ['tests/a.py'] }]) }, 'pin');+ expect(c.verify().status).toBe(0);+ c.repo.git('checkout', '-q', 'main');+ commit(c.repo, { '.gstack/ship-policy.json': policy() }, 'narrow');+ c.repo.git('push', '-q', 'origin', 'main');+ c.repo.git('checkout', '-q', 'feat');+ for (const args of [['--base', 'main', '--all', '--offline'], ['--base', 'main', '--all']]) {+ const r = c.verify(args);+ expect(outOf(r)).toContain('(VENDORED_UNREACHABLE)');+ expect(r.status).toBe(1);+ }+ });+ test('deleting a vendored file the base already holds fails the default scope', () => {+ const c = consumer();+ c.repo.git('checkout', '-q', 'main');+ c.repo.git('merge', '-q', '--ff-only', 'feat');+ c.repo.git('push', '-q', 'origin', 'main');+ c.repo.git('checkout', '-q', 'feat');+ c.repo.git('rm', '-q', 'vendor/lib/tests/a.py');+ c.repo.git('commit', '-q', '-m', 'rm');+ const r = c.verify();+ expect(outOf(r)).toContain('(VENDORED_ABSENT_LOCAL)');+ expect(r.status).toBe(1);+ });+ test('a force-pushed pin and a deleted upstream fail closed', () => {+ const c = consumer();+ commit(c.repo, { 'vendor/lib/tests/b.py': B2, 'vendor/MANIFEST.json': manifest([{ commit: c.up.c2, files: ['tests/a.py', 'tests/b.py'] }]) }, 'repin');+ expect(c.verify().status).toBe(0);+ run(c.up.work, ['push', '-q', '--force', c.up.bare, `${c.up.c1}:refs/heads/main`], c.upEnv);+ const gone = c.verify();+ expect(outOf(gone)).toContain('(VENDORED_UNREACHABLE)');+ fs.rmSync(c.up.bare, { recursive: true, force: true });+ const deleted = c.verify();+ expect(outOf(deleted)).toContain('(VENDORED_FETCH_FAILED)');+ expect(deleted.status).toBe(1);+ });+ test('an upstream the base does not list fails, and a head cannot add one for itself', () => {+ const other = 'https://example.test/up/other';+ const c = consumer();+ commit(c.repo, { 'vendor/MANIFEST.json': manifest([{ upstream: other, commit: c.up.c1, files: ['tests/a.py', 'tests/b.py'] }]), '.gstack/ship-policy.json': policy([UP, other]) }, 'trust other');+ const r = c.verify();+ expect(outOf(r)).toContain('(VENDORED_NOT_ALLOWLISTED)');+ expect(r.status).toBe(1);+ });+ test('executables, symlinks and a file renamed under its prefix are not vendored', () => {+ const c = consumer();+ c.repo.git('update-index', '--chmod=+x', 'vendor/lib/tests/a.py');+ c.repo.git('commit', '-q', '-m', 'exec');+ expect(outOf(c.verify())).toContain('(VENDORED_MODE)');+ const d = consumer();+ commit(d.repo, { 'vendor/lib/tests/conftest.py': A, 'vendor/MANIFEST.json': manifest([{ commit: d.up.c1, files: ['tests/a.py', 'tests/b.py', 'tests/conftest.py'] }]) }, 'rename');+ expect(outOf(d.verify())).toContain('(VENDORED_ABSENT_UPSTREAM)');+ });+ test('an invalid or missing manifest fails without checking anything', () => {+ const c = consumer();+ commit(c.repo, { 'vendor/MANIFEST.json': manifest([{ commit: c.up.c1, files: ['../escape.py'] }]) }, 'bad');+ const r = c.verify();+ expect(outOf(r)).toContain('(VENDORED_MANIFEST_INVALID)');+ expect(r.status).toBe(1);+ commit(c.repo, { 'vendor/MANIFEST.json': null }, 'gone');+ expect(outOf(c.verify())).toMatch(/vendor\/MANIFEST\.json is not in HEAD.*\(VENDORED_MANIFEST_INVALID\)/);+ });+ test('the default scope checks only what the branch changes; --all checks every entry; --offline reuses the cache', () => {+ const c = consumer();+ expect(c.verify().status).toBe(0);+ c.repo.git('push', '-q', 'origin', 'feat:main');+ c.repo.git('fetch', '-q', 'origin');+ commit(c.repo, { 'vendor/lib/tests/b.py': B1 + '# local\n' }, 'edit b');+ const changed = c.verify();+ expect(outOf(changed)).toMatch(/checked=1 verified=0 failed=1/);+ const all = c.verify(['--base', 'main', '--all']);+ expect(outOf(all)).toMatch(/checked=2 verified=1 failed=1 .* scope=all/);+ const offline = c.verify(['--base', 'main', '--all', '--offline']);+ expect(outOf(offline).match(/digest=([0-9a-f]{64})/)?.[1]).toBe(outOf(all).match(/digest=([0-9a-f]{64})/)?.[1]);+ const cold = c.verify(['--base', 'main', '--all', '--offline'], { GSTACK_STATE_ROOT: path.join(c.repo.root, 'cold'), GSTACK_HOME: path.join(c.repo.root, 'cold'), GSTACK_STATE_DIR: path.join(c.repo.root, 'cold') });+ expect(outOf(cold)).toContain('(VENDORED_FETCH_FAILED)');+ });+ test('a base with no review_vendored prints none and exits 0', () => {+ const repo = makeFixtureRepo({ prefix: 'gstack-vendored-none-' });+ repos.push(repo);+ const r = runBin(repo, 'gstack-vendored-verify', ['--base', 'main']);+ expect(outOf(r)).toContain('VENDORED_VERIFY: none');+ expect(r.status).toBe(0);+ });+});++describe.skipIf(process.platform === 'win32')('gstack-vendored-verify against a misbehaving server', () => {+ function server(mode: '401' | 'hang') {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-vendored-srv-'));+ dirs.push(dir);+ const script = path.join(dir, 'srv.ts');+ fs.writeFileSync(script, mode === '401'+ ? "const s = Bun.serve({ port: 0, fetch: () => new Response('no', { status: 401, headers: { 'WWW-Authenticate': 'Basic realm=x' } }) }); console.log(s.port);\n"+ : "const s = Bun.serve({ port: 0, idleTimeout: 0, fetch: () => new Promise<Response>(() => {}) }); console.log(s.port);\n");+ const proc = Bun.spawn(['bun', ...bunIsolationArgs(), script], { stdout: 'pipe', stderr: 'ignore' });+ return { proc, port: async () => Number((await new Response(proc.stdout).text().catch(() => '')).trim() || 0) };+ }+ for (const mode of ['401', 'hang'] as const) {+ test(`a ${mode} remote fails as fetch-failed without prompting or hanging`, async () => {+ const { proc } = server(mode);+ const reader = proc.stdout.getReader();+ const { value } = await reader.read();+ const port = Number(new TextDecoder().decode(value).trim());+ try {+ const c = consumer();+ const started = Date.now();+ const r = c.verify(['--base', 'main'], { GSTACK_VENDORED_FETCH_ROOT: `http://127.0.0.1:${port}`, GSTACK_VENDORED_FETCH_TIMEOUT_MS: '3000' });+ expect(outOf(r)).toContain('(VENDORED_FETCH_FAILED)');+ expect(r.status).toBe(1);+ expect(Date.now() - started).toBeLessThan(25_000);+ } finally { proc.kill(); }+ }, 60_000);+ }+});++describe('branch globs, missing branches, gitlinks and --json', () => {+ test('a * glob still refuses a commit only a merge-queue branch holds, and a named branch the upstream lacks fails nothing else', () => {+ const star = consumer({ policy: policy([{ url: UP, branches: ['*'] }]) });+ commit(star.repo, { 'vendor/lib/tests/a.py': A + '# queue\n', 'vendor/MANIFEST.json': manifest([{ commit: star.up.queue, files: ['tests/a.py'] }]) }, 'pin');+ const r = star.verify();+ expect(outOf(r)).toContain('(VENDORED_UNREACHABLE)');+ expect(r.status).toBe(1);+ const missing = consumer({ policy: policy([{ url: UP, branches: ['release/2', 'gone'] }]) });+ commit(missing.repo, { 'vendor/lib/tests/a.py': A + '# rel\n', 'vendor/MANIFEST.json': manifest([{ commit: missing.up.release, files: ['tests/a.py'] }]) }, 'pin');+ const m = missing.verify();+ expect(outOf(m)).toContain('reachable_from=heads/release/2');+ expect(m.status).toBe(0);+ });+ test('an upstream gitlink is VENDORED_MODE, and --json keeps the pin count beside the pin rows', () => {+ const c = consumer();+ run(c.up.work, ['update-index', '--add', '--cacheinfo', `160000,${c.up.c1},tests/sub`], c.upEnv);+ run(c.up.work, ['commit', '-q', '-m', 'gitlink'], c.upEnv);+ const g = run(c.up.work, ['rev-parse', 'HEAD'], c.upEnv);+ run(c.up.work, ['push', '-q', c.up.bare, 'main'], c.upEnv);+ commit(c.repo, { 'vendor/lib/tests/sub': A, 'vendor/MANIFEST.json': manifest([{ commit: g, files: ['tests/sub'] }]) }, 'gitlink');+ expect(outOf(c.verify())).toContain('(VENDORED_MODE)');+ const j = c.verify(['--base', 'main', '--json']);+ const out = JSON.parse(j.out) as { pins: number; pin_results: unknown[] };+ expect(out.pins).toBe(1);+ expect(out.pin_results).toHaveLength(1);+ });+});