diff --git a/.agents/skills/release/SKILL.md b/.agents/skills/release/SKILL.md index e41bceafaf..013c6eb884 100644 --- a/.agents/skills/release/SKILL.md +++ b/.agents/skills/release/SKILL.md @@ -199,9 +199,13 @@ from a direct `bun run test experiments/…`, about 34 native/paid-harness failures with "Installed dependency inode has external hardlinks")? Bun's default install hard-links `node_modules` to its global cache, and the offline harnesses refuse runtime bytes they do not own. Reinstall the same lock as -copies and rerun: `rm -rf node_modules && bun install --frozen-lockfile ---backend=copyfile`. The lock is unchanged, so this does not invalidate -anything; do not skip or edit the tests. +copies using [dependency diagnostic preparation](../../../docs/process/diagnostic-installs.md): +preserve evidence, move aside only the owned checkout's `node_modules`, then run +`sh scripts/prepare-diagnostic-install.sh`. A fresh private cache avoids modified +shared-cache bytes; copyfile alone does not verify provenance. Keep the lock and +qualification pins unchanged, rebuild, and rerun. Retain the old failed receipt; +a changed installation requires fresh proof, even with an unchanged lock. Do not +skip or edit the tests. **An offline experiment app refuses with `Hosted workers require managed Btrfs storage`?** Measurement harnesses are outside the normal product tests and diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 34a5563afc..ca628ae45f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -80,6 +80,9 @@ coordination, not protection against arbitrary filesystem edits. Direct Vitest diagnostics do not acquire whole-command ownership. Editorial captures retain their existing separate capture guard. Use the coordinated entry points or separate worktrees when overlapping those runs. +Before instrumenting installed dependencies, follow +[dependency diagnostic preparation](docs/process/diagnostic-installs.md): +worktrees alone do not isolate Bun cache hardlinks. The frozen native diagram control also requires the independently qualified installation bytes and modes. An `installation-mismatch` with matching frozen @@ -91,22 +94,20 @@ owned checkout through a fresh private cache and independent file copies, **under umask `022`**. The installation identity includes file modes, and the installer's umask narrows them. The qualified install was made under `022`, so an install under any other umask, such as `0077`, never matches, even though its -package, file and byte counts are identical. Run the recovery in a subshell so +package, file and byte counts are identical. The preparation script sets its own umask so your own umask is unchanged: ```sh -( - umask 022 - native_fixture_cache=$(mktemp -d) - bun install --force --frozen-lockfile --backend=copyfile --cache-dir "$native_fixture_cache" -) +# Preserve evidence and move aside this owned checkout's node_modules first. +sh scripts/prepare-diagnostic-install.sh bun run test ./tests/native-diagram-inputs.test.ts ``` Retain the failed and restored installation identities. Verify any suspected package edits against the lockfile's archive integrity; never normalize unknown bytes or modes to force qualification. Leave shared caches and other checkouts -alone. This recovery does not prevent future diagnostic cache edits (#1980). +alone. Use the same preparation before future dependency instrumentation; retain the +original failure evidence as described in the diagnostic guide. The Linux backend nonpersistence tests require `bubblewrap` and permitted user namespaces. They launch the installed Claude and pi adapters with a loopback diff --git a/docs/README.md b/docs/README.md index c928446f50..54aec6778c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -68,6 +68,7 @@ the published template rather than a source checkout. | --- | --- | | [process/github.md](process/github.md) | Where work lives: the label taxonomy, what a milestone commits to, the project board's fields, the issue lifecycle, and what an agent does before writing code. | | [process/testing.md](process/testing.md) | Testing and proof: the offline test harness, tests that cannot fail, failing-first receipts, required PR proof and the GitHub Actions CI policy. | +| [process/diagnostic-installs.md](process/diagnostic-installs.md) | Isolated dependency instrumentation, fresh-cache recovery and the limits of package-byte evidence. | | [process/test-authoring.md](process/test-authoring.md) | Writing tests: which kind of test proves which claim, how to structure one, and what keeps it deterministic and cheap. The rules the test-health audit checks against. | | [process/feature-captures.md](process/feature-captures.md) | Editorial screenshot and demo recipes, source/readiness rules and public asset provenance. | | [decisions/README.md](decisions/README.md) | Why things are the way they are — the alternatives rejected and the measurements that decided them. Read the record for whatever you are about to change. | diff --git a/docs/process/diagnostic-installs.md b/docs/process/diagnostic-installs.md new file mode 100644 index 0000000000..af12fbe708 --- /dev/null +++ b/docs/process/diagnostic-installs.md @@ -0,0 +1,65 @@ +# Preparing dependency diagnostics + +Before editing anything under `node_modules`, use an exclusively owned checkout +with no build, test or editor process using its dependencies. A separate git +worktree alone does not isolate dependency inodes: Bun's default hardlink +backend can link installations to the same cache file. A diagnostic write then +changes the cache and other installations. + +From that checkout, preserve failed receipts, installed-byte hashes and inode +identities before moving its `node_modules` aside to an owned evidence directory +outside the checkout. Do not move another worker's dependencies. Then run: + +```sh +sh scripts/prepare-diagnostic-install.sh +``` + +The command refuses an existing `node_modules`, sets umask `022` in its own +process, creates an empty private cache, and installs the unchanged lock with +`--force --frozen-lockfile --backend=copyfile`. Both `BUN_INSTALL_CACHE_DIR` and +`--cache-dir` select that cache: an inherited environment setting can otherwise +override the flag. It removes only its own temporary cache on success or failure. +An interrupted/failed install may leave partial `node_modules`; preserve its +failure, move aside that owned partial installation and prepare again. Do not +run diagnostics against a failed install. + +Preparation is allowed to fetch packages; subsequent tests still run through +the repository's offline entry points. Never add `--no-verify`. A fresh cache +avoids reusing modified cached bytes, and Bun verifies downloaded registry +archives against lockfile integrity. This does not authenticate local/path/git +dependencies or a custom registry without trusted integrity metadata. Check a +suspected registry package's archive against its locked integrity, then compare +the extracted files with installed bytes. An unchanged lockfile or a single-link +copy alone proves neither provenance nor pristine package bytes. + +Keep the original and recovered observations separate. Do not change package +versions, locks, assertions, qualification pins or file modes to force a pass. +Rebuild as required and rerun the original focused check through its offline +wrapper. For the frozen native diagram fixture, retain the failed/restored +installation identities and run `bun run test ./tests/native-diagram-inputs.test.ts`. +Once evidence is retained and no process uses it, remove only the owned old +installation. Never delete or repair shared caches while others may use them. +Repeat preparation before a new independent diagnostic; an installation you +have instrumented is no longer pristine. + +## Evidence and its limits + +[#1980](https://github.com/schlessera/brain-kit/issues/1980) preserves the +observed Vitest 4.1.11 comparison: the instrumented chunk and shared-cache chunk +had identical device/inode identity and 63 links. The modified chunk's SHA-256 +was `6b1a505f3953877013957189d5714f77298c40392f19145ab001b6f9dbb76f0c`; +the registry/private-install chunk's was +`a236001d048380e2c67d05423fc9ea3f26b07ee019ba8d6e622082f29d49102e`. +The npm archive's declared SHA-512 integrity was independently verified. The +403-byte difference was `REPRO1973` session tracing. Later owned-install +recoveries reproduced the clean qualified installation without changing pins. +These observations establish cache modification and recovery, not its original +author, a product defect, or retrospective cleanliness/failure causation for +historical runs whose installed bytes were not captured. + +`tests/diagnostic-install.test.ts` runs a bounded actual Bun install fixture in +a network namespace with only a loopback registry. It demonstrates unsafe +cross-hardlink writes, wrong-byte single-link copies, independent preparation +from a deliberately modified source cache, unchanged package/lock inputs, +archive rejection, refusal to overwrite evidence and owned cache cleanup. +Its fictional package does not requalify historical Vitest or browser runs. diff --git a/scripts/native-diagram-inputs.ts b/scripts/native-diagram-inputs.ts index 981ee67a7b..5001b073f4 100644 --- a/scripts/native-diagram-inputs.ts +++ b/scripts/native-diagram-inputs.ts @@ -21,7 +21,7 @@ const qualified:Omit={source:"e8502b6ffb3c575f2 // The installation identity includes file modes, which the installer's umask // narrows: the qualified install was made under umask 022, and any other umask // (such as 0077) can never match. Recovery replaces only this owned install. -const installationRecovery="Reinstall this owned checkout under umask 022 from a fresh private cache: umask 022 && bun install --force --frozen-lockfile --backend=copyfile --cache-dir \"$(mktemp -d)\". The installation identity includes file modes, so an install under any other umask (such as 0077) never matches. See CONTRIBUTING.md; never refresh qualification pins."; +const installationRecovery="Preserve evidence and move aside this owned checkout's node_modules, then run sh scripts/prepare-diagnostic-install.sh. It sets umask 022 and installs the unchanged lock through a fresh private cache and copyfile. The installation identity includes file modes, so an install under any other umask (such as 0077) never matches. See CONTRIBUTING.md; never refresh qualification pins."; const caller="packages/ui-kit/vitest.config.ts",owner="packages/ui-react/tests/browser/diagram-export-command.ts"; const sourcePins:Record={ "packages/ui-kit/vitest.config.ts": "e724696a55955e9f32d396b2031214600086533c3f9b8baabcc1c6bb7311f1db", diff --git a/scripts/prepare-diagnostic-install.sh b/scripts/prepare-diagnostic-install.sh new file mode 100644 index 0000000000..6cc86ce0e8 --- /dev/null +++ b/scripts/prepare-diagnostic-install.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Run from an exclusively owned checkout, before editing installed dependencies. +set -eu +if [ -e node_modules ] || [ -L node_modules ]; then + echo 'Diagnostic install refused: preserve evidence and move aside the owned node_modules first; see CONTRIBUTING.md.' >&2 + exit 1 +fi +umask 022 +diagnostic_cache=$(mktemp -d) +trap 'rm -rf "$diagnostic_cache"' EXIT +trap 'exit 130' INT +trap 'exit 143' TERM +BUN_INSTALL_CACHE_DIR="$diagnostic_cache" bun install --force --frozen-lockfile --backend=copyfile --cache-dir "$diagnostic_cache" diff --git a/scripts/test-experiments.ts b/scripts/test-experiments.ts index e4189fd857..6183efff05 100644 --- a/scripts/test-experiments.ts +++ b/scripts/test-experiments.ts @@ -209,7 +209,7 @@ export function danglingBins(root: string): string[] { } /** The reinstall that gives the harnesses runtime bytes they own. */ -export const COPY_INSTALL = "rm -rf node_modules && bun install --frozen-lockfile --backend=copyfile"; +export const COPY_INSTALL = "sh scripts/prepare-diagnostic-install.sh"; /** * The first installed file that shares its inode with something outside @@ -267,7 +267,7 @@ async function main(): Promise { const linked = externallyHardlinked(root); if (linked) { console.error(`Experiment tier refused: node_modules is hard-linked to Bun's cache (${linked}), which the ` + - `offline harnesses reject. Reinstall the same lock as copies: ${COPY_INSTALL}`); + `offline harnesses reject. Preserve evidence and move aside the owned node_modules, then prepare the same lock: ${COPY_INSTALL}`); return 1; } const namespace = Bun.spawnSync(["bwrap", "--unshare-net", "--ro-bind", "/", "/", "--proc", "/proc", "--dev", "/dev", "/usr/bin/true"]); diff --git a/tests/diagnostic-install.test.ts b/tests/diagnostic-install.test.ts new file mode 100644 index 0000000000..a33b0fb2d4 --- /dev/null +++ b/tests/diagnostic-install.test.ts @@ -0,0 +1,15 @@ +import { expect, test } from "bun:test"; +import { readlinkSync } from "node:fs"; +import { join } from "node:path"; + +test("diagnostic installs avoid modified cache bytes and isolate diagnostic edits", async () => { + // The installer is native code, outside the JS network preload. Give the + // entire local registry/install fixture a real network namespace instead. + const child = Bun.spawn(["bwrap", "--unshare-net", "--bind", "/", "/", "--proc", "/proc", "--dev", "/dev", + process.execPath, join(import.meta.dir, "fixtures/diagnostic-install-probe.ts")], { + env: { ...process.env, DIAGNOSTIC_PARENT_NET: readlinkSync("/proc/self/ns/net") }, stdout: "pipe", stderr: "pipe", + }); + const [out, err, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + expect(exit, out + err).toBe(0); + expect(out).toContain("diagnostic isolation and provenance passed"); +}); diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index 2fad53a575..620daa0acf 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -109,7 +109,7 @@ describe("experiment tier discovery", () => { writeFileSync(join(dir, "cache.js"), ""); linkSync(join(dir, "cache.js"), join(dir, "node_modules/a/cached.js")); expect(externallyHardlinked(dir)).toBe("node_modules/a/cached.js"); - expect(COPY_INSTALL).toBe("rm -rf node_modules && bun install --frozen-lockfile --backend=copyfile"); + expect(COPY_INSTALL).toBe("sh scripts/prepare-diagnostic-install.sh"); } finally { rmSync(dir, { recursive: true, force: true }); } }); diff --git a/tests/fixtures/diagnostic-install-probe.ts b/tests/fixtures/diagnostic-install-probe.ts new file mode 100644 index 0000000000..0ab1bd9bce --- /dev/null +++ b/tests/fixtures/diagnostic-install-probe.ts @@ -0,0 +1,113 @@ +import assert from "node:assert/strict"; +import { readlinkSync } from "node:fs"; +import { networkInterfaces } from "node:os"; +import { createHash } from "node:crypto"; +import { cpSync, existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const script = join(import.meta.dir, "../../scripts/prepare-diagnostic-install.sh"); +const clean = 'export const voyage = "Ithaca";\n'; +const changed = 'export const voyage = "Sirens";\n'; + +// Real Bun installs, one local archive, no external registry or provider access. +assert.notEqual(readlinkSync("/proc/self/ns/net"), process.env.DIAGNOSTIC_PARENT_NET); +assert.deepEqual(Object.keys(networkInterfaces()), ["lo"]); +{ + const root = mkdtempSync(join(tmpdir(), "diagnostic-install-")); + let server: ReturnType | undefined; + try { + mkdirSync(join(root, "package")); + writeFileSync(join(root, "package/package.json"), JSON.stringify({ name: "odyssey-diagnostic", version: "1.0.0", main: "index.js" })); + writeFileSync(join(root, "package/index.js"), clean); + const tar = Bun.spawnSync(["tar", "-czf", join(root, "package.tgz"), "package"], { cwd: root }); + assert.equal(tar.exitCode, 0); + const archive = readFileSync(join(root, "package.tgz")); + writeFileSync(join(root, "package/index.js"), changed); + const alteredTar = Bun.spawnSync(["tar", "-czf", join(root, "altered.tgz"), "package"], { cwd: root }); + assert.equal(alteredTar.exitCode, 0); + const alteredArchive = readFileSync(join(root, "altered.tgz")); + const integrity = `sha512-${createHash("sha512").update(archive).digest("base64")}`; + let downloads = 0; + let corrupt = false; + server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch(request) { + if (new URL(request.url).pathname.endsWith(".tgz")) { + downloads++; + return new Response(corrupt ? alteredArchive : archive); + } + return Response.json({ name: "odyssey-diagnostic", "dist-tags": { latest: "1.0.0" }, versions: { + "1.0.0": { name: "odyssey-diagnostic", version: "1.0.0", dist: { + tarball: `${new URL(request.url).origin}/odyssey-diagnostic-1.0.0.tgz`, integrity, + } }, + } }); + } }); + const cache = join(root, "shared-cache"); + const scratch = join(root, "private-caches"); + mkdirSync(scratch); + const env = { ...process.env, BUN_INSTALL_CACHE_DIR: cache, TMPDIR: scratch }; + async function run(cwd: string, argv: string[]) { + const child = Bun.spawn(argv, { cwd, env, stdout: "pipe", stderr: "pipe" }); + const [out, err, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + assert.deepEqual({ exit, error: exit ? out + err : "" }, { exit: 0, error: "" }); + } + const seed = join(root, "seed"); + mkdirSync(seed); + writeFileSync(join(seed, "package.json"), JSON.stringify({ name: "odyssey-fixture", dependencies: { "odyssey-diagnostic": "1.0.0" } })); + writeFileSync(join(seed, ".npmrc"), `registry=http://127.0.0.1:${server.port}\n`); + await run(seed, [process.execPath, "install", "--backend=hardlink", "--cache-dir", cache]); + const installed = (dir: string) => join(dir, "node_modules/odyssey-diagnostic/index.js"); + const shared = [...new Bun.Glob("**/index.js").scanSync({ cwd: cache, absolute: true })][0]!; + assert.equal(statSync(shared).ino, statSync(installed(seed)).ino); + // Unsafe control: a diagnostic write changes the shared cache and a peer. + const peer = join(root, "unsafe-peer.js"); + linkSync(shared, peer); + writeFileSync(installed(seed), changed); + assert.equal(readFileSync(shared, "utf8"), changed); + assert.equal(readFileSync(peer, "utf8"), changed); + const copied = join(root, "copied.js"); + cpSync(shared, copied); + assert.equal(statSync(copied).nlink, 1); + assert.notEqual(readFileSync(copied, "utf8"), clean); + + const lock = readFileSync(join(seed, "bun.lock")); + const manifest = readFileSync(join(seed, "package.json")); + const prepared: string[] = []; + for (const name of ["first", "second"]) { + const dir = join(root, name); + mkdirSync(dir); + for (const file of ["package.json", "bun.lock", ".npmrc"]) cpSync(join(seed, file), join(dir, file)); + const beforeDownloads = downloads; + await run(dir, ["sh", script]); + assert.ok(downloads > beforeDownloads); + assert.equal(readFileSync(installed(dir), "utf8"), clean); + assert.equal(statSync(installed(dir)).nlink, 1); + assert.deepEqual(readFileSync(join(dir, "bun.lock")), lock); + assert.deepEqual(readFileSync(join(dir, "package.json")), manifest); + prepared.push(dir); + } + writeFileSync(installed(prepared[0]!), changed); + assert.equal(readFileSync(installed(prepared[1]!), "utf8"), clean); + assert.equal(readFileSync(shared, "utf8"), changed); + // Refuse in-place replacement: retain the diagnostic bytes for inspection. + const refused = Bun.spawn(["sh", script], { cwd: prepared[0], env, stdout: "pipe", stderr: "pipe" }); + const [refusedOut, refusedErr, refusedExit] = await Promise.all([new Response(refused.stdout).text(), new Response(refused.stderr).text(), refused.exited]); + assert.equal(refusedExit, 1, refusedOut + refusedErr); + assert.ok(refusedErr.includes("move aside the owned node_modules first")); + assert.equal(readFileSync(installed(prepared[0]!), "utf8"), changed); + assert.equal(existsSync(cache), true); + corrupt = true; + const rejected = join(root, "bad-archive"); + mkdirSync(rejected); + for (const file of ["package.json", "bun.lock", ".npmrc"]) cpSync(join(seed, file), join(rejected, file)); + const bad = Bun.spawn(["sh", script], { cwd: rejected, env, stdout: "pipe", stderr: "pipe" }); + const [badOut, badErr, badExit] = await Promise.all([new Response(bad.stdout).text(), new Response(bad.stderr).text(), bad.exited]); + assert.notEqual(badExit, 0); + assert.match(badOut + badErr, /integrity/i); + assert.deepEqual(readFileSync(join(rejected, "bun.lock")), lock); + assert.deepEqual(readdirSync(scratch), []); + } finally { + server?.stop(true); + rmSync(root, { recursive: true, force: true }); + } +} +console.log("diagnostic isolation and provenance passed"); diff --git a/tests/native-diagram-inputs.test.ts b/tests/native-diagram-inputs.test.ts index ad3c2e30c2..e16bae7e31 100644 --- a/tests/native-diagram-inputs.test.ts +++ b/tests/native-diagram-inputs.test.ts @@ -101,7 +101,7 @@ test("an install under umask 0077 is refused with the umask 022 recovery, and th const refused=restrictive.diagnostic();assert(refused,"RESTRICTIVE_UMASK_REFUSAL_MUST_REPORT_DIAGNOSTIC"); expect(refused.status).toBe("installation-mismatch");expect(refused.actual?.source).toBe(qualifiedSource); expect(refused.recovery,"INSTALLATION_REFUSAL_NAMES_THE_REQUIRED_UMASK").toContain("umask 022"); - expect(refused.recovery,"INSTALLATION_REFUSAL_NAMES_THE_INSTALL_COMMAND").toContain("bun install --force --frozen-lockfile --backend=copyfile --cache-dir"); + expect(refused.recovery,"INSTALLATION_REFUSAL_NAMES_THE_INSTALL_COMMAND").toContain("sh scripts/prepare-diagnostic-install.sh"); expect(JSON.stringify(refused)).not.toContain(restrictive.root); reference.bind();const expected=reference.diagnostic();assert(expected?.actual?.installation,"REFERENCE_INSTALL_MUST_REPORT_IDENTITY"); // Same packages, files and bytes: only the modes differ.