From e2e26b1839bfdc439a8f5e721b60688bd9fc64fb Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 23 Oct 2026 10:23:04 +0800 Subject: [PATCH 1/2] ci: rebalance core test matrix to /3 shards across all combos (#4351) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The suite grew ~399 -> ~860 files in three weeks while the core matrix shape stayed frozen at its ~650-file design point (#3295), so its heaviest legs became the per-PR wall-clock floor: the ubuntu-24 single-leg whole suite measured ~21 min and the windows 2-shard halves ~13-17 min (up to ~35 min tails on flake re-runs). All three core combos now shard /3. partitionAll stays total for any i/N, so the union of shards is still every file — zero coverage loss; the wall drops to the slowest shard (~7-12 min instead of 20-25). The win node-24 legs stay FULL-scope only. Check-run names are unchanged (explicit job name template), and all nine core leg names already sit in master's required-checks list. --- .github/workflows/ci.yml | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b903f9e0d5..7b7d223a4f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -58,13 +58,14 @@ concurrency: jobs: # Three-layer CI (#3295) plan: decide the matrix scope BEFORE paying for # legs. One cheap ubuntu job picks one of three scopes: - # core — every PR (push) and master push: 6 test legs (ubuntu 22 full 3-shard - # suite, ubuntu 24 single-leg whole suite, windows 22 2-shard) + 2 + # core — every PR (push) and master push: 9 test legs (all three combos at + # /3 shards: ubuntu 22, ubuntu 24, windows 22 — #4351 rebalance) + 2 # static legs (ubuntu 24, windows 22 — #3406 item 8: the windows # static leg keeps typecheck/build + the kernel/pi-subagents # suites covered on windows for EVERY PR, not only ci:full/nightly). - # The blocking layer; branch protection requires exactly - # these 6 test leg names. + # The blocking layer. master's required-checks list still carries + # the legacy 12 FULL-matrix leg names; core produces 9 of them (the + # win node-24 legs appear only in FULL scope), enforce_admins off. # full — `ci:full` label on a PR, a release PR (#3688: bot-authored # one-click fallback PRs, *_release-v* head branches, or a # "[PR] release…"/"release vN…" title — no label needed), @@ -110,13 +111,24 @@ jobs: FULL_INPUT: ${{ inputs.full }} run: | set -euo pipefail + # #4351: the suite grew ~399 -> ~860 files in three weeks while the + # core shape stayed frozen at its ~650-file design point (#3295), so + # its heaviest legs became the wall-clock floor: the ubuntu-24 + # single-leg whole suite measured ~21 min and the windows 2-shard + # halves ~13-17 min (up to ~35 min tails on flake re-runs). All three + # combos now shard /3: partitionAll stays total for any i/N, so + # union of shards == every file — zero coverage loss; wall drops to + # the slowest shard (~7-12 min). The win node-24 legs stay FULL-only. CORE_TEST='{"include":[ {"os":"ubuntu-latest","node-version":22,"shard":1,"shardTotal":3}, {"os":"ubuntu-latest","node-version":22,"shard":2,"shardTotal":3}, {"os":"ubuntu-latest","node-version":22,"shard":3,"shardTotal":3}, - {"os":"ubuntu-latest","node-version":24,"shard":1,"shardTotal":1}, - {"os":"windows-latest","node-version":22,"shard":1,"shardTotal":2}, - {"os":"windows-latest","node-version":22,"shard":2,"shardTotal":2}]}' + {"os":"ubuntu-latest","node-version":24,"shard":1,"shardTotal":3}, + {"os":"ubuntu-latest","node-version":24,"shard":2,"shardTotal":3}, + {"os":"ubuntu-latest","node-version":24,"shard":3,"shardTotal":3}, + {"os":"windows-latest","node-version":22,"shard":1,"shardTotal":3}, + {"os":"windows-latest","node-version":22,"shard":2,"shardTotal":3}, + {"os":"windows-latest","node-version":22,"shard":3,"shardTotal":3}]}' CORE_STATIC='{"include":[{"os":"ubuntu-latest","node-version":24},{"os":"windows-latest","node-version":22}]}' FULL_TEST='{"include":[ {"os":"ubuntu-latest","node-version":22,"shard":1,"shardTotal":3}, @@ -212,9 +224,10 @@ jobs: # across more legs: each runs a balanced slice (scripts/run-ci-tests.mjs partitions # deterministically + totally, so union of shards == allFiles, nothing skipped, # same tests/assertions/env, c=4 within each shard). Wall drops ~3x (~20 -> ~7min) - # with zero coverage loss. To go faster, add entries to the FULL_TEST include - # list in the plan job above (each entry carries its own shardTotal, so the - # legacy "bump the /3" coupling is gone — any denominator works). + # with zero coverage loss. To go faster, add entries to the include list of + # the scope you want faster in the plan job above (each entry carries its own + # shardTotal, so the legacy "bump the /3" coupling is gone — any denominator + # works; #4351 used exactly this knob on CORE_TEST). strategy: fail-fast: false matrix: ${{ fromJSON(needs.plan.outputs.testMatrix) }} From 1deb66ed05feaa52d1465993608cf01ee442d134 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Fri, 23 Oct 2026 13:15:04 +0800 Subject: [PATCH 2/2] ci: cache kernel+pi-subagents dist by content hash so legs stop rebuilding 6 minutes of artifacts every run (#4360) --- .github/workflows/ci.yml | 23 ++++ package.json | 2 +- scripts/ci-pretest-cache.d.mts | 22 ++++ scripts/ci-pretest-cache.mjs | 197 +++++++++++++++++++++++++++++++++ tests/ci-pretest-cache.test.ts | 174 +++++++++++++++++++++++++++++ 5 files changed, 417 insertions(+), 1 deletion(-) create mode 100644 scripts/ci-pretest-cache.d.mts create mode 100644 scripts/ci-pretest-cache.mjs create mode 100644 tests/ci-pretest-cache.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b7d223a4f..f9498ebe45 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -238,6 +238,29 @@ jobs: with: node-version: ${{ matrix.node-version }} cache: npm + # #4360 lever 1: pretest dist content-hash cache. kernel/ and + # pi-subagents/ dist are pure functions of (src tree, build config, + # manifests, lockfiles); the pretest hook (scripts/ci-pretest-cache.mjs) + # stamps each dist with a marker of that hash and skips the rebuild on + # a byte-exact match, saving the ~5-6.5 min Windows build per leg. + # Correctness never trusts the cache: marker mismatch => real rebuild, + # so a dirty/stale restore at worst wastes one build, never runs wrong + # artifacts. Per-OS keys (never share dists across platforms); no + # restore-keys — a near-miss restore is worthless because the marker + # check rejects it anyway. The post step saves automatically (on the + # exact primary key, job success only) AFTER the pretest build inside + # run-ci-tests.mjs below. The hashFiles patterns MUST stay in sync with + # the input tables in scripts/ci-pretest-cache.mjs. + - name: Restore kernel dist cache (#4360) + uses: actions/cache@v4 + with: + path: kernel/dist + key: pretest-dist-kernel-v1-${{ runner.os }}-${{ hashFiles('kernel/src/**', 'kernel/tsup.config.ts', 'kernel/tsconfig.json', 'kernel/package.json', 'kernel/package-lock.json', 'package-lock.json') }} + - name: Restore pi-subagents dist cache (#4360) + uses: actions/cache@v4 + with: + path: pi-subagents/dist + key: pretest-dist-pisub-v1-${{ runner.os }}-${{ hashFiles('pi-subagents/src/**', 'pi-subagents/tsup.config.ts', 'pi-subagents/tsconfig.json', 'pi-subagents/package.json', 'package-lock.json') }} - run: npm install --ignore-scripts --no-fund --no-audit # #2816: explicit file concurrency=4 for the whole suite. Baseline logs # show the old default (availableParallelism()-1) already ran several diff --git a/package.json b/package.json index 0293c41a3d..27472409fd 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ "check:unused-exports": "node scripts/check-unused-exports.mjs", "check:test-import-graph": "node scripts/check-test-import-graph.mjs", "check:dist-thin": "node scripts/check-dist-thin-install.mjs", - "pretest": "node scripts/test-suite-lock.mjs gate && npm --prefix kernel run build && npm --prefix pi-subagents run build", + "pretest": "node scripts/test-suite-lock.mjs gate && node scripts/ci-pretest-cache.mjs", "test": "node scripts/test-suite-lock.mjs run", "start": "node dist/index.js", "test:e2e": "node --import tsx --test tests/e2e/e2e-codex.test.ts", diff --git a/scripts/ci-pretest-cache.d.mts b/scripts/ci-pretest-cache.d.mts new file mode 100644 index 0000000000..83e96ded50 --- /dev/null +++ b/scripts/ci-pretest-cache.d.mts @@ -0,0 +1,22 @@ +interface PretestCacheComponent { + name: string; + dir: string; + inputs: string[]; +} + +interface PretestCacheResult { + name: string; + hit: boolean; + ms: number; +} + +export const MARKER_NAME: string; +export const COMPONENTS: PretestCacheComponent[]; +export function hashComponent(root: string, comp: PretestCacheComponent, platform?: string): string; +export function markerIsFresh(distDir: string, hash: string): boolean; +export function runPretestCache(opts?: { + root?: string; + components?: PretestCacheComponent[]; + log?: (line: string) => void; + build?: (comp: PretestCacheComponent, root: string) => void; +}): PretestCacheResult[]; diff --git a/scripts/ci-pretest-cache.mjs b/scripts/ci-pretest-cache.mjs new file mode 100644 index 0000000000..33b155d760 --- /dev/null +++ b/scripts/ci-pretest-cache.mjs @@ -0,0 +1,197 @@ +#!/usr/bin/env node +// #4360 lever 1: content-hash cache for the pretest dist builds. +// +// Every CI test leg used to fully rebuild kernel/ and pi-subagents/ dist +// (~5-6.5 min on Windows each leg) inside `npm run pretest` before a single +// test ran — yet those dists are a PURE FUNCTION of the source tree, the +// build config (tsup/tsc), the manifests that carry the build script chains +// (+ CURRENT_VERSION, inlined by pi-subagents' tsup), and the lockfiles that +// pin the toolchain (tsup/esbuild/typescript). This script makes that +// function explicit: after a REAL build it stamps each dist with a marker +// holding the sha256 of its inputs; on later runs the marker is verified +// BYTE-EXACTLY against the live source hash and the rebuild is skipped only +// on a match. +// +// Correctness rule (#4360): NEVER trust the cache. The marker is the only +// freshness oracle and it gates on the LIVE tree, not on what a cache +// restore happened to bring in — so a dirty or stale restore at worst wastes +// ONE rebuild (marker mismatch → real rebuild), it can never run wrong +// artifacts. Symmetrically, an absent marker (fresh checkout, dist wiped, +// build interrupted mid-way) is a MISS, never a guess. Exits non-zero only +// on a real failure: a build command that failed, or an input tree so broken +// the hash itself cannot be computed (which means the build would fail too). +// +// The workflow side (actions/cache keyed on hashFiles over the SAME inputs, +// per runner.os) only accelerates the MISS path across legs; the marker +// check stands on its own, so local `npm test` warm runs benefit too. +// +// Parity note: pretest previously ran `npm --prefix kernel run build && npm +// --prefix pi-subagents run build`; this script runs exactly those commands +// on a miss (same resolution, same clean semantics — kernel's build wipes +// dist, so the marker is written only after a fully successful build). + +import { createHash } from "node:crypto"; +import { execFileSync } from "node:child_process"; +import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const ROOT = join(fileURLToPath(new URL(".", import.meta.url)), ".."); + +/** Marker file written inside each dist; gitignored together with dist/. */ +export const MARKER_NAME = ".pretest-cache-marker"; + +/** Seed: bump when the hash recipe itself changes so old markers invalidate. */ +const HASH_SEED_PREFIX = "bili-pretest-cache-v1"; + +/** + * Shared inputs hashed relative to the repo root for BOTH components: the + * root lockfile pins the toolchain versions (tsup/esbuild/typescript) that + * the `file:` devDependencies resolve through, so a toolchain bump + * invalidates both caches even though no component source changed. + */ +const ROOT_INPUTS = ["package-lock.json"]; + +/** + * The two pretest components and the exact input set that determines their + * dist bytes. `inputs` are relative to the component dir; each entry is a + * file (hashed by content) or a directory (walked recursively, hashed by + * relative path + content). Keep this table in sync with the hashFiles() + * patterns in .github/workflows/ci.yml — the workflow README-comment there + * points back here. + */ +export const COMPONENTS = [ + { + name: "kernel", + dir: "kernel", + inputs: ["src", "tsup.config.ts", "tsconfig.json", "package.json", "package-lock.json"], + }, + { + name: "pi-subagents", + dir: "pi-subagents", + // package.json is a BUILD INPUT here, not just metadata: tsup.config.ts + // inlines CURRENT_VERSION from it into the bundle. + inputs: ["src", "tsup.config.ts", "tsconfig.json", "package.json"], + }, +]; + +/** Never hashed inside a walk — build outputs and deps are not inputs. */ +const SKIP_NAMES = new Set(["node_modules", "dist", "tmp", ".tmp", ".git"]); + +function hashFile(h, abs, rel) { + h.update(rel); + h.update("\0"); + h.update(readFileSync(abs)); + h.update("\0"); +} + +function hashDir(h, absDir, relDir) { + const entries = readdirSync(absDir, { withFileTypes: true }); + entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + for (const e of entries) { + if (SKIP_NAMES.has(e.name)) continue; + const rel = `${relDir}/${e.name}`; + if (e.isDirectory()) hashDir(h, join(absDir, e.name), rel); + else if (e.isFile()) hashFile(h, join(absDir, e.name), rel); + // symlinks/other node types are skipped — deterministic and inert + } +} + +/** + * The content hash for one component: sha256 over the platform plus every + * input's normalized relative path and bytes. Platform rides the hash + * because a cache restore crossing OSes (possible with a future key typo) + * must never satisfy the marker check — same never-trust rule as everything + * else here. Pure: no writes, no builds. + */ +export function hashComponent(root, comp, platform = process.platform) { + const h = createHash("sha256"); + h.update(`${HASH_SEED_PREFIX} platform=${platform}\0`); + const rels = [...ROOT_INPUTS, ...comp.inputs.map((i) => `${comp.dir}/${i}`)].sort(); + for (const rel of rels) { + const abs = join(root, rel); + if (!existsSync(abs)) { + throw new Error(`input "${rel}" not found under ${root} — cannot establish dist freshness`); + } + if (statSync(abs).isDirectory()) hashDir(h, abs, rel); + else hashFile(h, abs, rel); + } + return h.digest("hex"); +} + +/** Marker freshness: byte-exact hash comparison. Absent/corrupt marker = MISS. */ +export function markerIsFresh(distDir, hash) { + try { + return readFileSync(join(distDir, MARKER_NAME), "utf-8").trim() === hash; + } catch { + return false; + } +} + +/** + * The pretest loop. For each component: hash → fresh marker? HIT, skip : + * MISS → run the real build → stamp the marker. `build`/`log` are test seams + * (the CLI passes defaults); build failures propagate so the CLI exits 1 — + * non-zero exit means a REAL build failure, never a cache decision. + */ +export function runPretestCache(opts = {}) { + const root = opts.root ?? ROOT; + const components = opts.components ?? COMPONENTS; + const log = opts.log ?? ((line) => console.log(line)); + const build = opts.build ?? defaultBuild; + const results = []; + for (const comp of components) { + const hash = hashComponent(root, comp); + const distDir = join(root, comp.dir, "dist"); + if (markerIsFresh(distDir, hash)) { + log(`pretest-cache: HIT (${comp.name}) — dist fresh for hash ${hash.slice(0, 12)}`); + results.push({ name: comp.name, hit: true, ms: 0 }); + continue; + } + log(`pretest-cache: MISS (${comp.name}) → rebuilding`); + const t0 = Date.now(); + build(comp, root); + mkdirSync(distDir, { recursive: true }); + writeFileSync(join(distDir, MARKER_NAME), `${hash}\n`); + const ms = Date.now() - t0; + log(`pretest-cache: built (${comp.name}) in ${(ms / 1000).toFixed(1)}s — marker stamped (${hash.slice(0, 12)})`); + results.push({ name: comp.name, hit: false, ms }); + } + return results; +} + +function defaultBuild(comp, root) { + // Same invocation pretest used verbatim (`npm --prefix run build`). + // On Windows npm is a .cmd batch file CreateProcess cannot exec directly + // (EINVAL) — same shell:true dance as scripts/run-ci-tests.mjs; args are + // fixed literals, so there is no quoting surface. + const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm"; + execFileSync(npmCmd, ["--prefix", comp.dir, "run", "build"], { + cwd: root, + stdio: "inherit", + shell: process.platform === "win32", + }); +} + +function main() { + try { + runPretestCache(); + return 0; + } catch (e) { + console.error(`pretest-cache: FAILED — ${e?.message ?? e}`); + return 1; + } +} + +// Run only when invoked directly (not when imported by the regression test). +const INVOKED_DIRECTLY = (() => { + if (!process.argv[1]) return false; + try { + return resolve(process.argv[1]) === fileURLToPath(import.meta.url); + } catch { + return false; + } +})(); +if (INVOKED_DIRECTLY) { + process.exit(main()); +} diff --git a/tests/ci-pretest-cache.test.ts b/tests/ci-pretest-cache.test.ts new file mode 100644 index 0000000000..cb76d9d917 --- /dev/null +++ b/tests/ci-pretest-cache.test.ts @@ -0,0 +1,174 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import * as cache from "../scripts/ci-pretest-cache.mjs"; + +// #4360 lever 1: the pretest dist content-hash cache. kernel/ and +// pi-subagents/ dist are pure functions of (src tree, build config, +// manifests, lockfiles); scripts/ci-pretest-cache.mjs stamps each dist with +// a marker of that hash after a REAL build and skips the rebuild only on a +// byte-exact marker match. These tests pin the correctness contract from the +// issue: never trust the cache — absent/stale/tampered markers are MISSes +// (real rebuild), only a byte-exact match is a HIT, the two components +// invalidate independently, and build failures propagate (exit non-zero). + +function makeMiniRepo(): { root: string; write: (rel: string, v?: string) => void } { + const root = mkdtempSync(join(tmpdir(), "bili-pretest-cache-")); + const write = (rel: string, v = "x"): void => { + mkdirSync(join(root, rel, ".."), { recursive: true }); + writeFileSync(join(root, rel), v); + }; + // The exact input surface of cache.COMPONENTS, mirrored as a fake tree. + write("package-lock.json", "root-lock-v1"); + for (const [dir, extraLock] of [ + ["kernel", true], + ["pi-subagents", false], + ] as const) { + write(`${dir}/src/index.ts`, `export const v = "${dir}";\n`); + write(`${dir}/src/deep/util.ts`, `export const u = 1;\n`); + write(`${dir}/tsup.config.ts`, "export default {};\n"); + write(`${dir}/tsconfig.json`, "{}\n"); + write(`${dir}/package.json`, `{"name":"${dir}"}\n`); + if (extraLock) write(`${dir}/package-lock.json`, "component-lock-v1\n"); + } + return { root, write }; +} + +/** Fake build: records invocations and materializes the dist it "built". */ +function fakeBuild(seen: string[]) { + return (comp: { dir: string }, root: string): void => { + seen.push(comp.dir); + mkdirSync(join(root, comp.dir, "dist"), { recursive: true }); + writeFileSync(join(root, comp.dir, "dist/index.js"), "built-bytes"); + }; +} + +test("cold → warm → tamper lifecycle (the #4360 CI sequence)", () => { + const { root, write } = makeMiniRepo(); + const lines: string[] = []; + const log = (l: string): void => { + lines.push(l); + }; + + // COLD: no dist at all → both MISS, both really built, markers stamped. + const seen1: string[] = []; + const r1 = cache.runPretestCache({ root, build: fakeBuild(seen1), log }); + assert.deepEqual( + r1.map((r) => [r.name, r.hit]), + [ + ["kernel", false], + ["pi-subagents", false], + ], + ); + assert.deepEqual(seen1, ["kernel", "pi-subagents"]); + + // WARM: nothing changed → both HIT, zero builds. + const seen2: string[] = []; + const r2 = cache.runPretestCache({ root, build: fakeBuild(seen2), log }); + assert.deepEqual(r2.map((r) => r.hit), [true, true]); + assert.equal(seen2.length, 0); + + // TAMPER: one kernel source byte changes → ONLY kernel rebuilds; the + // untouched component stays a HIT (independent invalidation). + write("kernel/src/index.ts", "export const v = 'kernel-tampered';\n"); + const seen3: string[] = []; + const r3 = cache.runPretestCache({ root, build: fakeBuild(seen3), log }); + assert.deepEqual( + r3.map((r) => [r.name, r.hit]), + [ + ["kernel", false], + ["pi-subagents", true], + ], + ); + assert.deepEqual(seen3, ["kernel"]); + + // The exact log lines CI greps for (#4360). + assert.ok(lines.some((l) => l.startsWith("pretest-cache: HIT (kernel)"))); + assert.ok(lines.some((l) => l.startsWith("pretest-cache: MISS (kernel) → rebuilding"))); +}); + +test("marker must match byte-exactly — absent, stale, tampered, CRLF are decided by content", () => { + const { root } = makeMiniRepo(); + const kernel = cache.COMPONENTS[0]; + const hash = cache.hashComponent(root, kernel); + const dist = join(root, kernel.dir, "dist"); + + mkdirSync(dist, { recursive: true }); + // absent marker + assert.equal(cache.markerIsFresh(dist, hash), false); + // wrong hash (e.g. restored from a stale cache entry) + writeFileSync(join(dist, cache.MARKER_NAME), `${"0".repeat(64)}\n`); + assert.equal(cache.markerIsFresh(dist, hash), false); + // tampered: right hash plus trailing garbage + writeFileSync(join(dist, cache.MARKER_NAME), `${hash}-extra`); + assert.equal(cache.markerIsFresh(dist, hash), false); + // byte-exact match (the trailing newline the stamper writes) + writeFileSync(join(dist, cache.MARKER_NAME), `${hash}\n`); + assert.equal(cache.markerIsFresh(dist, hash), true); + // line-ending tolerance only: same hash, CRLF transport artifact + writeFileSync(join(dist, cache.MARKER_NAME), `${hash}\r\n`); + assert.equal(cache.markerIsFresh(dist, hash), true); +}); + +test("hash covers every input class: source, config, manifests, both lockfiles", () => { + const { root, write } = makeMiniRepo(); + const kernel = cache.COMPONENTS[0]; + const pisub = cache.COMPONENTS[1]; + const base = cache.hashComponent(root, kernel); + + for (const rel of [ + "kernel/src/deep/util.ts", // nested source + "kernel/tsup.config.ts", // build config + "kernel/tsconfig.json", + "kernel/package.json", // manifest (build script chain) + "kernel/package-lock.json", // component lockfile + "package-lock.json", // ROOT lockfile (toolchain pins) + ]) { + const orig = readFileSync(join(root, rel), "utf-8"); + write(rel, `${orig} #mut`); + assert.notEqual(cache.hashComponent(root, kernel), base, `${rel} must change the kernel hash`); + write(rel, orig); + } + + // NEW file in the tree also invalidates (not just edits). + write("kernel/src/new-file.ts", "export {};\n"); + assert.notEqual(cache.hashComponent(root, kernel), base); + + // A kernel change never moves the pi-subagents hash (independence). + const pisubBase = cache.hashComponent(root, pisub); + assert.equal(cache.hashComponent(root, pisub), pisubBase); +}); + +test("hash is deterministic and platform-seeded", () => { + const { root } = makeMiniRepo(); + const kernel = cache.COMPONENTS[0]; + assert.equal(cache.hashComponent(root, kernel), cache.hashComponent(root, kernel)); + assert.notEqual(cache.hashComponent(root, kernel, "linux"), cache.hashComponent(root, kernel, "win32")); +}); + +test("root-lockfile bump invalidates BOTH components (shared toolchain pins)", () => { + const { root, write } = makeMiniRepo(); + const before = cache.COMPONENTS.map((c) => cache.hashComponent(root, c)); + write("package-lock.json", "root-lock-v2"); + cache.COMPONENTS.forEach((c, i) => { + assert.notEqual(cache.hashComponent(root, c), before[i], `${c.name} must invalidate on toolchain bump`); + }); +}); + +test("a missing input is a hard error, never a silent HIT", () => { + const { root } = makeMiniRepo(); + const broken = { name: "kernel", dir: "kernel", inputs: ["src", "does-not-exist.ts"] }; + assert.throws(() => cache.hashComponent(root, broken), /does-not-exist\.ts/); +}); + +test("build failure propagates (CLI exit path) and stamps no marker", () => { + const { root } = makeMiniRepo(); + const boom = (): void => { + throw new Error("tsc exploded"); + }; + assert.throws(() => cache.runPretestCache({ root, build: boom }), /tsc exploded/); + // no marker for a failed component → next run is an honest MISS + assert.equal(cache.markerIsFresh(join(root, "kernel/dist"), "anything"), false); +});