import { spawnSync } from "node:child_process"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { publishBuildPeaks, publishDiskReading } from "./helpers/disk-reading"; /** * `scripts/ui-tests-stub.sh` runs apps/cotton's CottonUITests from a package * outside the tree, because `swift test` in apps/cotton cannot build under the * FFI stub. Held here, with no Swift build: * - the package it writes names the three products the tests need, depends * on a private copy of apps/cotton by path, and copies its tools version * and platforms from apps/cotton/Package.swift rather than hard-coding them; * - the tests are re-synced every run, so a deleted test file is gone; * - a run hands its arguments to `swift test` under the build lock, exits * with its status, and `--summary` names the counts and failing tests; * - a run tells the tests which checkout they were copied from, so the ones * that read the tree read that one. * * The fake checkout carries a no-op `scripts/ffi-stub.sh`; `swift` is a * stand-in on PATH; the build lock lives in the sandbox. */ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); const SCRIPT = join(ROOT, "scripts", "ui-tests-stub.sh"); const FAKE_SWIFT = `#!/bin/bash echo "swift $*" >> "$FAKE_SWIFT_CALLS" echo "lock held by $TINMEN_BUILD_LOCK_LABEL" >> "$FAKE_SWIFT_CALLS" echo "repo root $COTTON_UI_TESTS_REPO_ROOT" >> "$FAKE_SWIFT_CALLS" echo "Test Case '-[Check.AlphaTests testOne]' passed (0.001 seconds)." echo "Test Case '-[Check.AlphaTests testTwo]' failed (0.002 seconds)." echo "Test Case '-[Check.BetaTests testThree]' failed (0.002 seconds)." echo "Executed 2 tests, with 1 failure (0 unexpected) in 0.003 (0.003) seconds" echo "Executed 5 tests, with 2 failures (0 unexpected) in 0.010 (0.010) seconds" exit 1 `; let sandbox: string; let checkout: string; let pkg: string; function write(path: string, body: string): void { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, body); } function run(args: string[], extraEnv: Record = {}) { // A scratch HOME with a fresh device reading: on a Mac the stub's build // admits through the device policy, which reads it there — never the person's HOME. const home = join(sandbox, "home"); publishDiskReading(home); // A byte of RAM per build: admission must not turn on the machine's free RAM. publishBuildPeaks(home); const env: NodeJS.ProcessEnv = { ...process.env, HOME: home, PATH: `${join(sandbox, "bin")}:${process.env.PATH}`, FAKE_SWIFT_CALLS: join(sandbox, "swift-calls"), BUILD_LOCK_DIR: join(sandbox, "build.lock"), BUILD_LOCK_LOG: join(sandbox, "build-lock.log"), BUILD_LOCK_CLASS: "local", BUILD_LOCK_LOCAL_NICE: "0", // The lock wraps a command in the Mac's cargo lock when the tree's cargo // config names the shared target, so a cargo job running here held these // tests for its whole length; a target of the sandbox's own takes no such lock. CARGO_TARGET_DIR: join(sandbox, "cargo-target"), // The command as an unsandboxed shell runs it: inside a lane the build // policy adds --disable-sandbox (mac_disk_policy.lane_args), its own guard's case. COTTON_LANE_SANDBOXED: "", ...extraEnv, }; delete env.TINMEN_BUILD_LOCK_HELD; const r = spawnSync("bash", [SCRIPT, ...args], { encoding: "utf8", env }); return { status: r.status, stdout: r.stdout, stderr: r.stderr }; } beforeEach(() => { sandbox = mkdtempSync(join(tmpdir(), "ui-tests-stub-")); checkout = join(sandbox, "checkout"); pkg = join(sandbox, "pkg"); write( join(checkout, "apps/cotton/Package.swift"), "// swift-tools-version: 9.9\nimport PackageDescription\nlet package = Package(\n name: \"Cotton\",\n platforms: [.iOS(.v99), .macOS(.v98)],\n)\n", ); write(join(checkout, "apps/cotton/Tests/CottonUITests/AlphaTests.swift"), "// alpha\n"); write(join(checkout, "apps/loom/Package.swift"), "// loom\n"); write(join(checkout, "apps/cotton/Tests/CottonUITests/Faces/BetaTests.swift"), "// beta\n"); write(join(checkout, "scripts/ffi-stub.sh"), "#!/bin/bash\nexit 0\n"); // The stub regenerates the catalogue storage from Rust before copying the package (d1cd4a09f); the fixture checkout carries the generator the real one has. write(join(checkout, "scripts/gen-swift-definition-types.py"), ""); write(join(sandbox, "bin/swift"), FAKE_SWIFT); chmodSync(join(sandbox, "bin/swift"), 0o755); }); afterEach(() => { rmSync(sandbox, { recursive: true, force: true }); }); describe("ui-tests-stub.sh — the package outside the tree", () => { // RULE: UI stub tests use their own stub even when a phone cut left a real phone-only framework; the cut's retained framework bytes are never overwritten or removed. it("builds its own stub beside a retained phone-only framework", () => { const phoneRoot = join(checkout, "apps/cotton/.ffi/CottonFFI.xcframework"); const phone = `AvailableLibraries LibraryIdentifierios-arm64 SupportedPlatformios HeadersPathHeaders `; write(join(phoneRoot, "Info.plist"), phone); write(join(phoneRoot, "ios-arm64/libcotton_ffi.a"), "retained phone cut"); write(join(checkout, "scripts/ffi-stub.sh"), readFileSync(join(ROOT, "scripts/ffi-stub.sh"), "utf8")); write(join(sandbox, "bin/swift"), String.raw`#!/bin/bash set -euo pipefail dep=$(sed -n 's/.*\.package(path: "\([^"]*\)").*/\1/p' Package.swift) plist="$dep/.ffi/CottonFFI.xcframework/Info.plist" grep -q 'macos' "$plist" grep -q CottonFFIStub "$plist" ! grep -q HeadersPath "$plist" echo 'stub build ok' `); const r = run(["--checkout", checkout, "--dir", pkg]); expect(r.status, r.stderr + r.stdout).toBe(0); expect(r.stdout).toContain("stub build ok"); expect(readFileSync(join(phoneRoot, "Info.plist"), "utf8")).toBe(phone); expect(readFileSync(join(phoneRoot, "ios-arm64/libcotton_ffi.a"), "utf8")).toBe("retained phone cut"); }); // RULE: The private stub package stays outside the checkout; overlapping rsync source/destination can recursively copy or delete the cut being preserved. it("refuses a private package inside the checkout", () => { const r = run(["--checkout", checkout, "--dir", join(checkout, "scratch"), "--prepare-only"]); expect(r.status).toBe(2); expect(r.stderr).toContain("outside the checkout"); }); // RULE: UI stub tests depend on a private copy of the checkout package and preserve its products, tools version and platforms, so a retained real framework cannot affect the stub build. it("writes a package over the two products, with the checkout's tools version and platforms", () => { const r = run(["--checkout", checkout, "--dir", pkg, "--prepare-only"]); expect(r.status, r.stderr).toBe(0); const manifest = readFileSync(join(pkg, "Package.swift"), "utf8"); expect(manifest.split("\n")[0]).toBe("// swift-tools-version: 9.9"); expect(manifest).toContain("platforms: [.iOS(.v99), .macOS(.v98)],"); expect(manifest).toContain(`.package(path: "${realpathSync(join(pkg, "apps/cotton"))}")`); expect(manifest).toContain('.product(name: "CottonUI", package: "cotton")'); expect(manifest).toContain('path: "Tests/Check"'); expect(readFileSync(join(pkg, "Tests/Check/AlphaTests.swift"), "utf8")).toBe("// alpha\n"); expect(existsSync(join(pkg, "Tests/Check/Faces/BetaTests.swift"))).toBe(true); expect(existsSync(join(sandbox, "swift-calls")), "--prepare-only builds nothing").toBe(false); }); // RULE: The private copy carries Loom (apps/loom) beside apps/cotton, so the app package's `../loom` path dependency resolves there exactly as in the checkout, without Loom's build products. it("copies Loom beside the app package", () => { write(join(checkout, "apps/loom/.build/huge.bin"), "derived"); expect(run(["--checkout", checkout, "--dir", pkg, "--prepare-only"]).status).toBe(0); expect(readFileSync(join(pkg, "apps/loom/Package.swift"), "utf8")).toBe("// loom\n"); expect(existsSync(join(pkg, "apps/loom/.build"))).toBe(false); }); // RULE: The private package never copies the app's derived data (apps/cotton/build, where `xcodebuild -derivedDataPath build` writes): a copy of it filled one Mac's disk to its floor on 15 Oct 2026. A source folder named build deeper in the tree is still copied. it("leaves the app's derived data behind", () => { write(join(checkout, "apps/cotton/build/Build/Products/huge.bin"), "derived"); write(join(checkout, "apps/cotton/Sources/Kit/build/Kept.swift"), "// kept\n"); expect(run(["--checkout", checkout, "--dir", pkg, "--prepare-only"]).status).toBe(0); expect(existsSync(join(pkg, "apps/cotton/build"))).toBe(false); expect(existsSync(join(pkg, "apps/cotton/Sources/Kit/build/Kept.swift"))).toBe(true); }); // RULE: scripts/ui-tests-stub.sh re-syncs the tests on every run, so a test file deleted from the checkout is gone from the package and an edited one is the one that runs. it("drops a deleted test file and picks up an edited one on the next run", () => { expect(run(["--checkout", checkout, "--dir", pkg, "--prepare-only"]).status).toBe(0); rmSync(join(checkout, "apps/cotton/Tests/CottonUITests/Faces/BetaTests.swift")); write(join(checkout, "apps/cotton/Tests/CottonUITests/AlphaTests.swift"), "// alpha, edited\n"); expect(run(["--checkout", checkout, "--dir", pkg, "--prepare-only"]).status).toBe(0); expect(existsSync(join(pkg, "Tests/Check/Faces/BetaTests.swift"))).toBe(false); expect(readFileSync(join(pkg, "Tests/Check/AlphaTests.swift"), "utf8")).toBe("// alpha, edited\n"); expect(existsSync(join(pkg, "apps/cotton/Tests/CottonUITests/Faces/BetaTests.swift"))).toBe(false); expect(readFileSync(join(pkg, "apps/cotton/Tests/CottonUITests/AlphaTests.swift"), "utf8")).toBe("// alpha, edited\n"); }); // RULE: scripts/ui-tests-stub.sh runs swift test under the machine-wide build lock with the caller's arguments, exits with its status, and --summary names the counts and every failing test. it("runs swift test under the build lock, passes the arguments, keeps the status and summarises", () => { const r = run(["--checkout", checkout, "--dir", pkg, "--summary", "--", "--filter", "Alpha"]); expect(r.status).toBe(1); const calls = readFileSync(join(sandbox, "swift-calls"), "utf8"); expect(calls).toContain("swift test --filter Alpha"); expect(calls).toContain("lock held by ui-tests-stub"); expect(r.stdout).toContain("ui-tests-stub: 5 run, 2 failed"); expect(r.stdout).toContain("ui-tests-stub: FAILED Check.AlphaTests testTwo"); expect(r.stdout).toContain("ui-tests-stub: FAILED Check.BetaTests testThree"); expect(r.stdout).not.toContain("FAILED Check.AlphaTests testOne"); }); // RULE: scripts/ui-tests-stub.sh tells the tests which checkout they were copied from (COTTON_UI_TESTS_REPO_ROOT), so a test that reads the repository reads the tree the script was called for and never a path walked up from the copy. it("names the checkout the tests were copied from to the run", () => { run(["--checkout", checkout, "--dir", pkg]); expect(readFileSync(join(sandbox, "swift-calls"), "utf8")).toContain(`repo root ${checkout}\n`); }); // RULE: A changed private stub path or plist drops cached build plans and products, including real-core headers; resolved dependencies stay so isolation does not require another network fetch. it("drops the cached plan and products when the private stub changed, and only then", () => { const ffi = join(pkg, "apps/cotton/.ffi/CottonFFI.xcframework/Info.plist"); const plan = [ join(pkg, ".build/manifest.pif"), join(pkg, ".build/out/Intermediates.noindex/XCBuildData/plan"), join(pkg, ".build/out/Products/Debug/include/CottonFFI/module.modulemap"), ]; const kept = join(pkg, ".build/workspace-state.json"); const seed = () => { for (const file of [...plan, kept]) write(file, "cached\n"); }; write(ffi, "stub\n"); seed(); run(["--checkout", checkout, "--dir", pkg]); for (const file of plan) expect(existsSync(file), `first sight of an archive: ${file}`).toBe(false); expect(existsSync(kept)).toBe(true); seed(); run(["--checkout", checkout, "--dir", pkg]); for (const file of plan) expect(existsSync(file), `the same archive: ${file}`).toBe(true); // An old run stored only the plist digest and used the checkout directly. write(join(pkg, ".ffi-plist"), readFileSync(join(pkg, ".ffi-plist"), "utf8").split(":").at(-1)!); run(["--checkout", checkout, "--dir", pkg]); for (const file of plan) expect(existsSync(file), `transition to a private path: ${file}`).toBe(false); expect(existsSync(kept)).toBe(true); seed(); write(ffi, "new stub shape\n"); run(["--checkout", checkout, "--dir", pkg]); for (const file of plan) expect(existsSync(file), `a changed archive: ${file}`).toBe(false); expect(existsSync(kept)).toBe(true); }); it("--summary says nothing ran when swift printed no count, never 0 failed", () => { write(join(sandbox, "bin/swift"), '#!/bin/bash\necho "error: build failed"\nexit 1\n'); const r = run(["--checkout", checkout, "--dir", pkg, "--summary"]); expect(r.status).toBe(1); expect(r.stdout).toContain("ui-tests-stub: NO TESTS RAN"); expect(r.stdout).not.toContain("0 failed"); }); it("--list asks swift for the list", () => { run(["--checkout", checkout, "--dir", pkg, "--list"]); expect(readFileSync(join(sandbox, "swift-calls"), "utf8")).toContain("swift test list\n"); }); it("reads this repository's real manifest and copies every CottonUITests file", () => { const r = run(["--dir", pkg, "--prepare-only"]); expect(r.status, r.stderr).toBe(0); const real = readFileSync(join(ROOT, "apps/cotton/Package.swift"), "utf8"); const manifest = readFileSync(join(pkg, "Package.swift"), "utf8"); expect(manifest.split("\n")[0]).toBe(real.split("\n")[0]); const platforms = real.match(/^\s*(platforms: \[[^\]]*\])/m)?.[1]; expect(platforms).toBeTruthy(); expect(manifest).toContain(platforms as string); const count = (dir: string): number => readdirSync(dir, { recursive: true, withFileTypes: true }).filter((e) => e.isFile()).length; expect(count(join(pkg, "Tests/Check"))).toBe(count(join(ROOT, "apps/cotton/Tests/CottonUITests"))); }, 300_000); // It copies every CottonUITests file: past 60 s on a loaded runner (verify-main 16167). }); // RULE: Fresh CI checkout paths share a locked job package even after failure, so every push cannot leave another multi-GB Swift build. it("reuses the CI job package across fresh checkouts and failed builds", () => { const env = { GITHUB_WORKSPACE: checkout, GITHUB_JOB: "decoder", TMPDIR: sandbox }; expect(run(["--checkout", checkout], env).status).toBe(1); const shared = join(sandbox, "cotton-ui-tests-stub/ci-decoder"); write(join(shared, ".build/sentinel"), "incremental cache"); const next = join(sandbox, "next-checkout"); write(join(next, "apps/cotton/Package.swift"), readFileSync(join(checkout, "apps/cotton/Package.swift"), "utf8")); write(join(next, "apps/cotton/Tests/CottonUITests/Next.swift"), "// next"); write(join(next, "apps/loom/Package.swift"), "// loom\n"); write(join(next, "scripts/ffi-stub.sh"), "#!/bin/bash\nexit 0\n"); write(join(next, "scripts/gen-swift-definition-types.py"), ""); expect(run(["--checkout", next], { ...env, GITHUB_WORKSPACE: next }).status).toBe(1); expect(readFileSync(join(shared, ".build/sentinel"), "utf8")).toBe("incremental cache"); expect(readdirSync(join(sandbox, "cotton-ui-tests-stub")).filter(n => !n.endsWith(".lock"))).toEqual(["ci-decoder"]); }); // RULE: A dependency checkout the temp sweep emptied is resolved again, never built from; whole checkouts keep their resolved state. it("resolves the dependencies again when a checkout has lost its manifest", () => { const state = join(pkg, ".build/workspace-state.json"); const whole = join(pkg, ".build/checkouts/Whole/Package.swift"); const seed = (): void => { write(state, "{}"); write(whole, "// whole"); write(join(pkg, ".build/repositories/Whole-1/HEAD"), "ref"); }; seed(); run(["--checkout", checkout, "--dir", pkg]); expect(existsSync(state), "whole checkouts keep their state").toBe(true); expect(existsSync(whole)).toBe(true); write(join(pkg, ".build/checkouts/Hollow/.git/HEAD"), "ref"); const r = run(["--checkout", checkout, "--dir", pkg]); expect(r.stderr).toContain("has no manifest"); for (const gone of [state, whole, join(pkg, ".build/repositories")]) expect(existsSync(gone), gone).toBe(false); }); // RULE: The legacy sweep adopts only older generated packages with no open files, never active packages, unrecognized folders or symlink targets. it("sweeps an idle legacy stub and preserves active and unowned folders", () => { const root = join(sandbox, "cotton-ui-tests-stub"); for (const name of ["111111111111", "222222222222", "333333333333"]) { write(join(root, name, "Package.swift"), name === "333333333333" ? "unowned" : '// Written by scripts/ui-tests-stub.sh\nname: "CottonUITestsStub"'); utimesSync(join(root, name, "Package.swift"), 1, 1); utimesSync(join(root, name), 1, 1); } symlinkSync(checkout, join(root, "444444444444")); write(join(sandbox, "bin/lsof"), '#!/bin/bash\ncase "$*" in *222222222222*) echo 123; exit 0;; *) exit 1;; esac\n'); chmodSync(join(sandbox, "bin/lsof"), 0o755); expect(run(["--checkout", checkout, "--prepare-only"], { GITHUB_WORKSPACE: checkout, GITHUB_JOB: "decoder", TMPDIR: sandbox }).status).toBe(0); expect(existsSync(join(root, "111111111111"))).toBe(false); expect(existsSync(join(root, "222222222222"))).toBe(true); expect(existsSync(join(root, "333333333333"))).toBe(true); expect(existsSync(join(checkout, "apps/cotton/Package.swift"))).toBe(true); });