import { spawnSync } from "node:child_process";
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, relative } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
/**
* `scripts/dev-household.sh` runs the DEVELOPMENT household. The owner's
* household is frozen (DEV MODE, 2026-10-03), and the one thing this script
* must never do is seed, serve or — via `reset` — `rm -rf` the app's own data
* folder. So its first act is a refusal: `COTTON_DEV_DIR` resolved through
* symlinks and `..` must not be the real data folder, the old Application
* Support folder, anything under either or anything above either.
*
* Every case runs against a FAKE `$HOME` holding a fake `CottonDB`, with a
* stub `cotton-headless` that records being called — the real household is
* never the target of a test, and a refusal that failed would show up as the
* stub's mark or a changed file, not as damage.
*/
const SCRIPT = join(__dirname, "..", "dev-household.sh");
let scratch: string;
let home: string;
let stub: string;
let called: string;
let launchctl: string;
let launchctlCalled: string;
function tree(root: string): string[] {
if (!existsSync(root)) return [];
const out: string[] = [];
const walk = (dir: string) => {
for (const name of readdirSync(dir)) {
const path = join(dir, name);
out.push(relative(root, path));
// A symlink is listed, never followed: the link to the fake CottonDB is walked once, as itself.
if (lstatSync(path).isDirectory()) walk(path);
}
};
walk(root);
return out.sort();
}
function run(args: string[], env: Record) {
return spawnSync("bash", [SCRIPT, ...args], {
encoding: "utf8",
env: {
PATH: process.env.PATH ?? "/usr/bin:/bin",
HOME: home,
COTTON_HEADLESS: stub,
// Never the real dev server's port, never Tailscale.
COTTON_DEV_PORT: "19790",
COTTON_TAILSCALE: join(scratch, "no-tailscale"),
// Never the real launchd: a stub records what it was asked, and the plist lands in scratch.
COTTON_LAUNCHCTL: launchctl,
COTTON_DEV_LAUNCH_AGENTS: join(scratch, "LaunchAgents"),
...env,
},
});
}
beforeEach(() => {
scratch = mkdtempSync(join(tmpdir(), "dev-household-"));
home = join(scratch, "home");
mkdirSync(join(home, "CottonDB", "files"), { recursive: true });
writeFileSync(join(home, "CottonDB", "registry.db"), "the owner's household");
mkdirSync(join(home, "Library", "Application Support", "CottonDB"), { recursive: true });
called = join(scratch, "stub-called");
stub = join(scratch, "bin", "cotton-headless");
mkdirSync(join(scratch, "bin"));
writeFileSync(stub, `#!/usr/bin/env bash\nprintf '%s\\n' "$*" >>"${called}"\necho '{"rows":0}'\n`);
chmodSync(stub, 0o755);
launchctlCalled = join(scratch, "launchctl-called");
launchctl = join(scratch, "bin", "launchctl");
writeFileSync(launchctl, `#!/usr/bin/env bash\nprintf '%s\\n' "$*" >>"${launchctlCalled}"\n`);
chmodSync(launchctl, 0o755);
});
afterEach(() => {
rmSync(scratch, { recursive: true, force: true });
});
describe("dev-household.sh --name: a second household beside the first", () => {
// RULE: The second development household's --dir is judged like COTTON_DEV_DIR — the app's own data folder is refused before anything runs.
it("dev_household_member_option_refuses_the_real_folder", () => {
for (const dir of [join(home, "CottonDB"), join(home, "Library", "Application Support", "CottonDB"), home]) {
for (const subcommand of ["seed", "reset", "up", "status", "down"]) {
const before = tree(scratch);
const result = run(["--name", "member", "--port", "19791", "--dir", dir, subcommand], {});
expect(result.status, result.stderr).toBe(2);
expect(result.stderr.trim().split("\n")).toHaveLength(1);
expect(result.stderr).toContain("app's own data folder");
expect(result.stdout).toBe("");
expect(existsSync(called), "the stub cotton-headless ran").toBe(false);
expect(tree(scratch)).toEqual(before);
}
}
});
it("seeds its own folder on its own port, small, under its own name — and leaves the first household's folder alone", () => {
const result = run(["--name", "member", "seed"], { COTTON_DEV_PORT: "" });
expect(result.status, result.stderr).toBe(0);
const asked = readFileSync(called, "utf8");
expect(asked).toContain(`seed --data-dir ${join(home, "CottonDevMember")} --size small --seed 2 --name `);
expect(asked.trim().endsWith("-member")).toBe(true);
expect(readFileSync(join(home, "CottonDevMember", "env"), "utf8")).toContain("PORT=9791\n");
expect(existsSync(join(home, "CottonDevHousehold"))).toBe(false);
});
it("refuses a name that is not a short lowercase word, and the login agent and follow build for a named household", () => {
const bad = run(["--name", "../CottonDB", "status"], {});
expect(bad.status).toBe(1);
expect(bad.stderr).toContain("--name is a short lowercase word");
for (const subcommand of ["install", "uninstall", "follow"]) {
const result = run(["--name", "member", subcommand], {});
expect(result.status, result.stderr).toBe(1);
expect(result.stderr).toContain("is run by hand");
}
expect(existsSync(called)).toBe(false);
expect(existsSync(launchctlCalled)).toBe(false);
});
});
describe("dev-household.sh refuses the app's own data folder", () => {
const refused: Array<[string, () => string]> = [
["the real data folder", () => join(home, "CottonDB")],
["a symlink to the real data folder", () => {
const link = join(scratch, "elsewhere", "CottonDev");
mkdirSync(join(scratch, "elsewhere"));
symlinkSync(join(home, "CottonDB"), link);
return link;
}],
["a folder under the real data folder, which does not exist", () => join(home, "CottonDB", "sub")],
["$HOME/CottonDev/../CottonDB, through a folder that does not exist", () => `${home}/CottonDev/../CottonDB`],
["the old Application Support folder", () => join(home, "Library", "Application Support", "CottonDB")],
["$HOME itself, which holds it — a reset would wipe it", () => home],
["$HOME/cottondb, the same folder on a case-insensitive disk", () => join(home, "cottondb")],
];
for (const [label, dir] of refused) {
for (const subcommand of ["seed", "reset", "status", "down", "install", "uninstall"]) {
it(`${subcommand} with ${label}: exit 2, one sentence, nothing touched`, () => {
const devDir = dir();
const before = tree(scratch);
const result = run([subcommand], { COTTON_DEV_DIR: devDir });
expect(result.status, result.stderr).toBe(2);
expect(result.stderr.trim().split("\n")).toHaveLength(1);
expect(result.stderr).toContain("app's own data folder");
expect(result.stdout).toBe("");
expect(existsSync(called), "the stub cotton-headless ran").toBe(false);
expect(tree(scratch)).toEqual(before);
expect(readFileSync(join(home, "CottonDB", "registry.db"), "utf8")).toBe("the owner's household");
});
}
}
});
describe("dev-household.sh with a folder of its own", () => {
it("is not refused: with no cotton-headless built it exits 3, saying how to build one", () => {
const devDir = join(scratch, "CottonDev");
const result = run(["seed"], { COTTON_DEV_DIR: devDir, COTTON_HEADLESS: join(scratch, "not-built") });
expect(result.status, result.stderr).toBe(3);
expect(result.stderr).not.toContain("app's own data folder");
expect(result.stderr).toContain("cargo build --release --manifest-path crates/Cargo.toml -p cotton-ffi --bin cotton-headless");
expect(result.stderr).not.toContain("with-build-lock");
expect(existsSync(devDir)).toBe(false);
});
it("finds the binary under the checkout's cargo target directory and prefers release over debug", () => {
// COTTON_HEADLESS empty → the script looks itself; CARGO_TARGET_DIR stands in for the
// target-dir the worktree's .cargo/config.toml names. The release build takes the large
// seed in a minute where debug takes ten, so it wins when both exist.
const target = join(scratch, "target");
for (const profile of ["debug", "release"]) {
mkdirSync(join(target, profile), { recursive: true });
const bin = join(target, profile, "cotton-headless");
writeFileSync(bin, `#!/usr/bin/env bash\nprintf '%s\\n' "${profile} $*" >>"${called}"\necho '{"rows":0}'\n`);
chmodSync(bin, 0o755);
}
const devDir = join(scratch, "CottonDev");
const result = run(["seed", "--size", "small"], { COTTON_DEV_DIR: devDir, COTTON_HEADLESS: "", CARGO_TARGET_DIR: target });
expect(result.status, result.stderr).toBe(0);
const lines = readFileSync(called, "utf8").trim().split("\n");
// TWO DATABASES: the seed, then the second database beside it, from the
// same binary.
expect(lines).toHaveLength(2);
expect(lines[0]).toMatch(/^release seed /);
expect(lines[1]).toMatch(/^release add-database --data-dir .* --database Allotment --size small --seed 2 --name \S+-dev$/);
});
it("install writes a LaunchAgent that runs `up` at login with the binary pinned, and loads it now", () => {
const devDir = join(scratch, "CottonDev");
const result = run(["install"], { COTTON_DEV_DIR: devDir });
expect(result.status, result.stderr).toBe(0);
const plist = join(scratch, "LaunchAgents", "com.cottondb.dev-household.plist");
const xml = readFileSync(plist, "utf8");
expect(xml).toContain("/bin/bash");
expect(xml).toContain(`${SCRIPT}up`);
expect(xml).toContain("RunAtLoad");
expect(xml).toContain(`COTTON_DEV_DIR${devDir}`);
expect(xml).toContain(`COTTON_HEADLESS${stub}`);
expect(xml).toContain("COTTON_DEV_PORT19790");
expect(xml).toContain("PATH/opt/homebrew/bin:");
const asked = readFileSync(launchctlCalled, "utf8").trim().split("\n");
expect(asked).toContain(`bootstrap gui/${process.getuid?.()} ${plist}`);
expect(result.stdout).toContain("Installed");
// The stub headless never ran: launchd (stubbed) is what runs `up`, not install itself.
expect(existsSync(called)).toBe(false);
// The second agent keeps the dev-defects pass running against the same folder.
const watcher = join(scratch, "LaunchAgents", "com.cottondb.dev-defects.plist");
const watcherXml = readFileSync(watcher, "utf8");
expect(watcherXml).toContain("KeepAlive");
expect(watcherXml).toContain(`scripts/dev-defects.ts--watch--data-dir${devDir}`);
expect(watcherXml).toContain("node_modules/.bin/tsx");
expect(asked.at(-1)).toBe(`bootstrap gui/${process.getuid?.()} ${watcher}`);
});
it("uninstall boots the agent out and removes the plist, leaving the server alone", () => {
const devDir = join(scratch, "CottonDev");
run(["install"], { COTTON_DEV_DIR: devDir });
const result = run(["uninstall"], { COTTON_DEV_DIR: devDir, COTTON_HEADLESS: join(scratch, "not-built") });
expect(result.status, result.stderr).toBe(0);
const plist = join(scratch, "LaunchAgents", "com.cottondb.dev-household.plist");
expect(existsSync(plist)).toBe(false);
expect(existsSync(join(scratch, "LaunchAgents", "com.cottondb.dev-defects.plist"))).toBe(false);
const asked = readFileSync(launchctlCalled, "utf8").trim().split("\n");
expect(asked.at(-1)).toBe(`bootout gui/${process.getuid?.()}/com.cottondb.dev-household`);
expect(asked.at(-2)).toBe(`bootout gui/${process.getuid?.()}/com.cottondb.dev-defects`);
expect(result.stdout).toContain("Removed");
});
it("seed writes PORT and an admin token into env BEFORE the binary runs, then announces itself", () => {
const devDir = join(scratch, "CottonDev");
const result = run(["seed", "--size", "small", "--seed", "7"], { COTTON_DEV_DIR: devDir });
expect(result.status, result.stderr).toBe(0);
const env = readFileSync(join(devDir, "env"), "utf8");
expect(env).toMatch(/^PORT=19790$/m);
expect(env).toMatch(/^COTTON_ADMIN_TOKEN=[0-9a-f]{64}$/m);
expect(env).toMatch(/^COTTON_DEV_TOOLS=1$/m);
expect(statSync(join(devDir, "env")).mode & 0o777).toBe(0o600);
expect(readFileSync(called, "utf8")).toMatch(new RegExp(`^seed --data-dir ${devDir} --size small --seed 7 --name \\S+-dev$`, "m"));
expect(result.stdout.trim().split("\n").at(-1)).toBe("DEV HOUSEHOLD down · not served yet");
});
it("seed defaults to a large household from seed 1", () => {
const devDir = join(scratch, "CottonDev");
expect(run(["seed"], { COTTON_DEV_DIR: devDir }).status).toBe(0);
expect(readFileSync(called, "utf8")).toContain("--size large --seed 1 ");
});
it("reset refuses to wipe a folder neither it nor cotton-headless made", () => {
const devDir = join(scratch, "Documents");
mkdirSync(devDir);
writeFileSync(join(devDir, "keep.txt"), "mine");
const result = run(["reset"], { COTTON_DEV_DIR: devDir });
expect(result.status, result.stderr).toBe(2);
expect(readFileSync(join(devDir, "keep.txt"), "utf8")).toBe("mine");
expect(existsSync(called)).toBe(false);
});
it("pending and approve pass through to cotton-headless on the dev folder", () => {
const devDir = join(scratch, "CottonDev");
expect(run(["pending"], { COTTON_DEV_DIR: devDir }).status).toBe(0);
expect(run(["approve", "pair-123"], { COTTON_DEV_DIR: devDir }).status).toBe(0);
expect(readFileSync(called, "utf8").trim().split("\n")).toEqual([
`pending --data-dir ${devDir}`,
`approve pair-123 --data-dir ${devDir}`,
]);
});
});
/**
* `follow ` — the household follows each shipped Cotton Dev build. The
* decisions are the point: already on S and answering → nothing; S's schema is
* the one the household serves → restart on S's binary with the data kept;
* a different schema → reset + reseed. S's binary is pre-placed where the
* build would put it, so no test compiles anything, and `curl` is a stub
* answering the household's /health from a file.
*/
// Each case runs the whole script, several stubs and a reset: seconds on a loaded Mac, not milliseconds.
describe("dev-household.sh follow ", { timeout: 60_000 }, () => {
const SHA = "0123456789abcdef0123456789abcdef01234567";
let devDir: string;
let followDir: string;
let source: string;
let health: string;
let stubPath: string;
function placeBinary(sha: string) {
const bin = join(followDir, "bin", `cotton-headless-${sha}`);
mkdirSync(join(followDir, "bin"), { recursive: true });
// seed founds registry.db; serve prints BOUND and leaves, as a detached server would.
writeFileSync(
bin,
`#!/usr/bin/env bash\nprintf '%s\\n' "$*" >>"${called}"\ncase "$1" in seed) mkdir -p "$3"; touch "$3/registry.db" ;; serve) echo "BOUND 19790" ;; esac\n`,
);
chmodSync(bin, 0o755);
return bin;
}
function follow(sha: string, servingSchema: number | null) {
if (servingSchema === null) rmSync(health, { force: true });
else writeFileSync(health, `{"ok":true,"schemaVersion":${servingSchema},"flavor":"dev"}`);
return run(["follow", sha], {
COTTON_DEV_DIR: devDir,
COTTON_DEV_FOLLOW_DIR: followDir,
COTTON_DEV_SOURCE: source,
COTTON_DEV_BOUND_TIMEOUT: "30",
PATH: `${stubPath}:${process.env.PATH ?? "/usr/bin:/bin"}`,
});
}
function calls(): string[] {
return existsSync(called) ? readFileSync(called, "utf8").trim().split("\n") : [];
}
beforeEach(() => {
devDir = join(scratch, "CottonDevHousehold");
followDir = join(scratch, "follow");
source = join(scratch, "tree");
mkdirSync(join(source, "crates", "cotton-store", "src", "schema"), { recursive: true });
writeFileSync(join(source, "crates", "cotton-store", "src", "schema", "ddl.rs"), "pub const SCHEMA_VERSION: u32 = 55;\n");
// A household that exists, with data in it.
mkdirSync(devDir, { recursive: true });
writeFileSync(join(devDir, ".dev-household"), "");
writeFileSync(join(devDir, "registry.db"), "dev data");
health = join(scratch, "health.json");
stubPath = join(scratch, "stub-path");
mkdirSync(stubPath);
writeFileSync(join(stubPath, "curl"), `#!/usr/bin/env bash\n[ -f "${health}" ] || exit 7\ncat "${health}"\n`);
chmodSync(join(stubPath, "curl"), 0o755);
});
it("same schema: restarts on S's binary, keeps the data, pins the binary", () => {
const bin = placeBinary(SHA);
const result = follow(SHA, 55);
expect(result.status, result.stderr).toBe(0);
expect(calls()).toEqual([`serve --data-dir ${devDir} --name ${spawnSync("hostname", ["-s"], { encoding: "utf8" }).stdout.trim()}`]);
expect(readFileSync(join(devDir, "registry.db"), "utf8")).toBe("dev data");
expect(readFileSync(join(followDir, "sha"), "utf8").trim()).toBe(SHA);
const plist = readFileSync(join(scratch, "LaunchAgents", "com.cottondb.dev-household.plist"), "utf8");
expect(plist).toContain(`COTTON_HEADLESS${bin}`);
expect(result.stdout.trim().split("\n").at(-1)).toMatch(/^DEV HOUSEHOLD .* · restarted on 012345678, schema 55, data kept$/);
});
it("a different schema: resets and reseeds, then serves", () => {
placeBinary(SHA);
const result = follow(SHA, 53);
expect(result.status, result.stderr).toBe(0);
const asked = calls();
expect(asked[0]).toMatch(new RegExp(`^seed --data-dir ${devDir} --size large --seed 1 `));
// The second database comes right after the seed, from the next seed number.
expect(asked[1]).toMatch(new RegExp(`^add-database --data-dir ${devDir} --database Allotment --size small --seed 2 --name \\S+-dev$`));
expect(asked[2]).toMatch(/^serve --data-dir /);
expect(readFileSync(join(devDir, "registry.db"), "utf8")).toBe("");
expect(result.stdout.trim().split("\n").at(-1)).toMatch(/· reset \+ reseeded on 012345678: schema 53 → 55/);
});
it("already on S and answering: nothing runs", () => {
placeBinary(SHA);
mkdirSync(followDir, { recursive: true });
writeFileSync(join(followDir, "sha"), `${SHA}\n`);
const result = follow(SHA, 55);
expect(result.status, result.stderr).toBe(0);
expect(calls()).toEqual([]);
expect(existsSync(join(scratch, "LaunchAgents"))).toBe(false);
expect(result.stdout.trim().split("\n").at(-1)).toMatch(/· already on 012345678, schema 55$/);
});
it("down: the schema it last followed decides — the same one restarts, data kept", () => {
placeBinary(SHA);
mkdirSync(followDir, { recursive: true });
writeFileSync(join(followDir, "schema"), "55\n");
const result = follow(SHA, null);
expect(result.status, result.stderr).toBe(0);
expect(calls().some((line) => line.startsWith("seed "))).toBe(false);
expect(readFileSync(join(devDir, "registry.db"), "utf8")).toBe("dev data");
});
it("refuses a sha that is not one", () => {
const result = follow("main; rm -rf ~", 55);
expect(result.status).toBe(1);
expect(calls()).toEqual([]);
});
it("refuses a follow folder inside the app's own data folder", () => {
const result = run(["follow", SHA], { COTTON_DEV_DIR: devDir, COTTON_DEV_FOLLOW_DIR: join(home, "CottonDB", "follow") });
expect(result.status).toBe(2);
expect(result.stderr).toContain("app's own data folder");
expect(existsSync(join(home, "CottonDB", "follow"))).toBe(false);
});
});
describe("dev-household.sh approve --all", () => {
it("approves every device pending lists", () => {
const devDir = join(scratch, "CottonDev");
writeFileSync(
stub,
`#!/usr/bin/env bash\nprintf '%s\\n' "$*" >>"${called}"\n[ "$1" = pending ] && printf 'p-1 iPhone digits 123456 expires 2026-10-04T10:00:00Z\\np-2 Mac digits 654321 expires 2026-10-04T10:00:00Z\\n'\nexit 0\n`,
);
const result = run(["approve", "--all"], { COTTON_DEV_DIR: devDir });
expect(result.status, result.stderr).toBe(0);
expect(readFileSync(called, "utf8").trim().split("\n")).toEqual([
`pending --data-dir ${devDir}`,
`approve p-1 --data-dir ${devDir}`,
`approve p-2 --data-dir ${devDir}`,
]);
expect(result.stdout).toContain("Approved 2 waiting device(s).");
});
});