test: overhaul deterministic suite architecture

This commit is contained in:
morluto
2026-07-29 22:00:38 +00:00
parent 7f2348619a
commit 513d9b1555
371 changed files with 30879 additions and 24389 deletions
@@ -0,0 +1,94 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js";
describe("configuration parsing integration", () => {
it("returns defaults when no environment variables are set", () => {
const result = parseConfig({});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperLauncherPath).toBe(
process.platform === "linux"
? "/opt/hopper/bin/Hopper"
: "/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
);
expect(result.value.hopperTargetPath).toBeUndefined();
expect(result.value.hopperTargetKind).toBe("executable");
expect(result.value.hopperLoaderArgs).toEqual([]);
expect(result.value.analysisProvider).toBe("auto");
});
it("parses a complete target-bound configuration", () => {
const result = parseConfig({
HOPPER_TARGET_PATH: "/usr/bin/true",
HOPPER_TARGET_KIND: "executable",
HOPPER_LOADER_ARGS_JSON: '["-l","Mach-O","--aarch64"]',
REA_ANALYSIS_PROVIDER: "hopper",
REA_EVIDENCE_ROOTS_JSON: '["/tmp/evidence"]',
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/tmp/releases"]',
REA_ANALYSIS_SNAPSHOT_ROOTS_JSON: '["/tmp/analysis"]',
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperTargetPath).toBe("/usr/bin/true");
expect(result.value.hopperTargetKind).toBe("executable");
expect(result.value.analysisProvider).toBe("hopper");
expect(result.value.hopperLoaderArgs).toEqual([
"-l",
"Mach-O",
"--aarch64",
]);
expect(result.value.evidenceFilePolicy.roots).toEqual(["/tmp/evidence"]);
expect(result.value.investigationInputRoots).toEqual(["/tmp/releases"]);
expect(result.value.analysisSnapshotFilePolicy.roots).toEqual([
"/tmp/analysis",
]);
});
it("rejects target kind values outside the enum", () => {
const result = parseConfig({
HOPPER_TARGET_KIND: "archive",
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("unreachable");
expect(result.error.message).toContain("Invalid REA environment");
});
it("rejects invalid JSON in loader arguments", () => {
const result = parseConfig({
HOPPER_LOADER_ARGS_JSON: "not json",
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("unreachable");
expect(result.error.message).toContain("valid JSON");
});
it("rejects non-array types in loader arguments JSON", () => {
const result = parseConfig({
HOPPER_LOADER_ARGS_JSON: '"just a string"',
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("unreachable");
expect(result.error.message).toContain("array of strings");
});
it("allows overriding the launcher path while keeping other defaults", () => {
const result = parseConfig({
HOPPER_LAUNCHER_PATH: "/custom/hopper",
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperLauncherPath).toBe("/custom/hopper");
expect(result.value.hopperTargetPath).toBeUndefined();
});
it("parses database target kind correctly", () => {
const result = parseConfig({
HOPPER_TARGET_PATH: "/path/to/file.hop",
HOPPER_TARGET_KIND: "database",
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperTargetKind).toBe("database");
});
});
@@ -0,0 +1,99 @@
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { spawnSync } from "node:child_process";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const roots: string[] = [];
const script = join(process.cwd(), "scripts", "check-dependency-install.mjs");
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true })),
);
});
const fixture = async (
installedVersion?: string,
omitDevDependency = false,
) => {
const root = await createTestTempDirectory("rea-deps-");
roots.push(root);
await mkdir(join(root, "node_modules"));
await writeFile(
join(root, "package-lock.json"),
JSON.stringify({
packages: {
"": {
dependencies: { alpha: "1.0.0" },
devDependencies: { beta: "2.0.0" },
},
"node_modules/alpha": { version: "1.0.0" },
"node_modules/beta": { version: "2.0.0" },
},
}),
);
await writeFile(
join(root, "node_modules", ".package-lock.json"),
JSON.stringify({
packages: {
"node_modules/alpha": { version: installedVersion ?? "1.0.0" },
...(omitDevDependency
? {}
: { "node_modules/beta": { version: "2.0.0" } }),
"node_modules/unrelated": { version: "9.0.0" },
},
}),
);
return root;
};
describe("dependency install freshness", () => {
it("accepts matching direct packages and ignores extraneous packages", async () => {
const result = spawnSync(process.execPath, [script], {
cwd: await fixture(),
encoding: "utf8",
});
expect(result.status, result.stderr).toBe(0);
});
it("reports a direct version mismatch with one remediation", async () => {
const result = spawnSync(process.execPath, [script], {
cwd: await fixture("0.9.0"),
encoding: "utf8",
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("alpha: installed 0.9.0, expected 1.0.0");
expect(result.stderr.match(/npm ci/gu)).toHaveLength(1);
});
it("reports a missing direct development dependency", async () => {
const result = spawnSync(process.execPath, [script], {
cwd: await fixture(undefined, true),
encoding: "utf8",
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"beta: missing from the installed dependency lockfile",
);
expect(result.stderr.match(/npm ci/gu)).toHaveLength(1);
});
it("runs from a script path containing URL-escaped characters", async () => {
const root = await fixture("0.9.0");
const scriptDirectory = join(root, "path with spaces");
const copiedScript = join(scriptDirectory, "check-dependency-install.mjs");
await mkdir(scriptDirectory);
await copyFile(script, copiedScript);
const result = spawnSync(process.execPath, [copiedScript], {
cwd: root,
encoding: "utf8",
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("alpha: installed 0.9.0, expected 1.0.0");
});
});
@@ -0,0 +1,178 @@
import { mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
readEvidenceBundle,
writeEvidenceBundle,
} from "../../../src/application/EvidenceBundleFiles.js";
import { compareEvidenceBundlesCommand } from "../../../src/application/EvidenceBundleCommands.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
createEvidenceBundle,
serializeEvidenceBundle,
type EvidenceFilePolicy,
} from "../../../src/domain/evidenceBundle.js";
let directory: string | undefined;
afterEach(async () => {
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
const bundle = () =>
createEvidenceBundle([
createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "health", parameters: {}, result: true },
),
]);
const policy = (root: string): EvidenceFilePolicy => ({
roots: [root],
maxBytes: 1024 * 1024,
maxDepth: 64,
maxStringLength: 1024,
maxNodes: 10_000,
});
describe("evidence bundle filesystem adapter", () => {
it("round trips canonical bytes and requires explicit overwrite", async () => {
directory = await createTestTempDirectory("rea-evidence-");
const path = join(directory, "bundle.json");
const evidenceBundle = bundle();
const first = await writeEvidenceBundle(
evidenceBundle,
path,
false,
policy(directory),
);
expect(first).toMatchObject({ ok: true, value: { path } });
expect(await readFile(path, "utf8")).toBe(
serializeEvidenceBundle(evidenceBundle),
);
expect(await readEvidenceBundle(path, policy(directory))).toEqual({
ok: true,
value: evidenceBundle,
});
expect(
await compareEvidenceBundlesCommand({
leftPath: path,
rightPath: path,
offset: 0,
limit: 100,
policy: policy(directory),
}),
).toMatchObject({
ok: true,
value: {
status: "unchanged",
summary: { records_unchanged: 1 },
},
});
expect(
await writeEvidenceBundle(evidenceBundle, path, false, policy(directory)),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "exists" },
});
expect(
await writeEvidenceBundle(evidenceBundle, path, true, policy(directory)),
).toMatchObject({ ok: true });
});
it("uses valid evidence roots when another configured root is missing", async () => {
directory = await createTestTempDirectory("rea-evidence-roots-");
const path = join(directory, "bundle.json");
const configured = {
...policy(directory),
roots: [join(directory, "missing"), directory],
};
expect(
await writeEvidenceBundle(bundle(), path, false, configured),
).toMatchObject({ ok: true });
expect(await readEvidenceBundle(path, configured)).toMatchObject({
ok: true,
});
});
it("rejects traversal and symlink escape from approved roots", async () => {
directory = await createTestTempDirectory("rea-evidence-");
const root = join(directory, "approved");
const outside = join(directory, "outside");
await mkdir(root);
await mkdir(outside);
const outsidePath = join(outside, "bundle.json");
await writeFile(outsidePath, serializeEvidenceBundle(bundle()));
const link = join(root, "escaped.json");
await symlink(outsidePath, link);
expect(await readEvidenceBundle(link, policy(root))).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "outside-root" },
});
expect(
await writeEvidenceBundle(bundle(), outsidePath, true, policy(root)),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "outside-root" },
});
});
it("rejects malformed, tampered, oversized, and deeply nested input", async () => {
directory = await createTestTempDirectory("rea-evidence-");
const malformed = join(directory, "malformed.json");
await writeFile(malformed, "{");
expect(
await readEvidenceBundle(malformed, policy(directory)),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "invalid-json" },
});
const tampered = bundle();
const tamperedPath = join(directory, "tampered.json");
await writeFile(
tamperedPath,
JSON.stringify({
...tampered,
records: [{ ...tampered.records[0], normalized_result: "changed" }],
}),
);
expect(
await readEvidenceBundle(tamperedPath, policy(directory)),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
const oversized = join(directory, "oversized.json");
await writeFile(oversized, "x".repeat(100));
expect(
await readEvidenceBundle(oversized, {
...policy(directory),
maxBytes: 10,
}),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "too-large" },
});
const deep = join(directory, "deep.json");
await writeFile(deep, JSON.stringify({ one: { two: { three: null } } }));
expect(
await readEvidenceBundle(deep, {
...policy(directory),
maxDepth: 1,
}),
).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "too-large" },
});
});
});
@@ -0,0 +1,249 @@
import { execFile } from "node:child_process";
import {
chmod,
mkdir,
readFile,
readdir,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execFileAsync = promisify(execFile);
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
describe("curl installer scenarios", { timeout: 20_000 }, () => {
it("installs only a pinned REA CLI with closed stdin", async () => {
const fixture = await createFixture();
const result = await runInstaller(fixture, ["--version", "0.3.0"]);
expect(result.stdout).toContain("REA 0.3.0 is installed");
expect(result.stdout).toContain("Run ");
expect(await readFile(fixture.npmLog, "utf8")).toContain(
"install --global --prefix",
);
expect(await readFile(fixture.reaLog, "utf8")).toBe("--version\n");
expect(await readdir(fixture.temporary)).toEqual([]);
});
it("accepts Node 25 without installing or replacing it", async () => {
const fixture = await createFixture();
const result = await runInstaller(fixture, ["--version", "0.3.0"], {
FAKE_NODE_VERSION: "25.1.0",
});
expect(result.stdout).toContain("Runtime: Node.js 25.1.0");
});
it("resolves and validates the latest REA release tag", async () => {
const fixture = await createFixture();
const result = await runInstaller(fixture);
expect(result.stdout).toContain("Version: 0.3.0");
});
it("prints a dry run without invoking npm", async () => {
const fixture = await createFixture();
const result = await runInstaller(fixture, [
"--version",
"0.3.0",
"--dry-run",
]);
expect(result.stdout).toContain("no changes made");
await expect(readFile(fixture.npmLog, "utf8")).rejects.toMatchObject({
code: "ENOENT",
});
});
it.each([
[
"unsupported Node",
{ FAKE_NODE_VERSION: "20.0.0" },
"REA installation failed: Node.js 20.0.0 is unsupported; use Node.js 22.19+ or 24.11+.\n",
],
[
"npm failure",
{ FAKE_NPM_FAIL: "1" },
"REA installation failed: npm could not install REA. Check registry access and npm permissions, then retry.\n",
],
[
"version mismatch",
{ FAKE_REA_VERSION: "9.9.9" },
"REA installation failed: installed version 9.9.9 does not match 0.3.0.\n",
],
] as const)("fails closed on %s", async (_name, overrides, message) => {
const fixture = await createFixture();
await expect(
runInstaller(fixture, ["--version", "0.3.0"], overrides),
).rejects.toMatchObject({ stderr: message });
});
it.each([
[
"unreadable Node version",
["--version", "0.3.0"],
{ FAKE_NODE_VERSION: "invalid" },
"REA installation failed: the active Node.js version could not be read. Check that node works and is on PATH, then retry.\n",
],
[
"release lookup",
[],
{ FAKE_CURL_FAIL: "1" },
"REA installation failed: the latest REA release could not be resolved. Check network access or pass --version VERSION, then retry.\n",
],
[
"release response",
[],
{ FAKE_CURL_BODY: "not-json" },
"REA installation failed: the release response was invalid. Retry later or pass --version VERSION.\n",
],
[
"release tag",
[],
{ FAKE_CURL_BODY: '{"tag_name":"unrelated-1.0.0"}' },
"REA installation failed: the latest release tag was invalid. Retry later or pass --version VERSION.\n",
],
[
"npm prefix",
["--version", "0.3.0"],
{ FAKE_PLATFORM: "Darwin", FAKE_NPM_PREFIX_FAIL: "1" },
"REA installation failed: the npm global prefix could not be read. Repair the npm configuration, then retry.\n",
],
[
"missing installed command",
["--version", "0.3.0"],
{ FAKE_NPM_SKIP_BINARY: "1" },
"REA installation failed: npm completed without installing the rea command. Check the npm global bin directory and PATH, then retry.\n",
],
[
"unreadable installed version",
["--version", "0.3.0"],
{ FAKE_REA_VERSION_FAIL: "1" },
"REA installation failed: the installed REA version could not be read. Reinstall the requested version, then retry.\n",
],
] as const)(
"reports exact recovery for %s failure",
async (_name, args, overrides, message) => {
const fixture = await createFixture();
await expect(
runInstaller(fixture, args, overrides),
).rejects.toMatchObject({
stderr: message,
});
},
);
it("reports exact recovery when curl is missing", async () => {
const fixture = await createFixture();
await rm(join(fixture.bin, "curl"));
await expect(
runInstaller(fixture, ["--version", "0.3.0"], {
PATH: fixture.bin,
}),
).rejects.toMatchObject({
stderr:
"REA installation failed: curl is required. Install curl, then rerun this installer.\n",
});
});
});
interface InstallerFixture {
readonly home: string;
readonly bin: string;
readonly temporary: string;
readonly npmLog: string;
readonly reaLog: string;
}
const createFixture = async (): Promise<InstallerFixture> => {
const root = await createTestTempDirectory("rea-install-test-");
roots.push(root);
const home = join(root, "home");
const bin = join(root, "bin");
const temporary = join(root, "tmp");
const npmLog = join(root, "npm.log");
const reaLog = join(root, "rea.log");
await Promise.all([mkdir(home), mkdir(bin), mkdir(temporary)]);
await executable(
join(bin, "uname"),
'#!/bin/sh\n[ "$1" = "-m" ] && echo x86_64 || printf \'%s\\n\' "${FAKE_PLATFORM:-Linux}"\n',
);
await executable(
join(bin, "node"),
`#!/bin/sh
if [ "$1" = "-p" ]; then printf '%s\n' "\${FAKE_NODE_VERSION:-24.18.0}"; else exec ${shellQuote(process.execPath)} "$@"; fi
`,
);
await executable(
join(bin, "npm"),
`#!/bin/sh
printf '%s\n' "$*" >> "$FAKE_NPM_LOG"
[ "$1" = "prefix" ] && { [ "\${FAKE_NPM_PREFIX_FAIL:-}" = "1" ] && exit 1; printf '%s\n' "$FAKE_NPM_PREFIX"; exit 0; }
[ "\${FAKE_NPM_FAIL:-}" = "1" ] && exit 1
prefix="$HOME/.local"
while [ "$#" -gt 0 ]; do
if [ "$1" = "--prefix" ]; then shift; prefix="$1"; fi
shift
done
[ "\${FAKE_NPM_SKIP_BINARY:-}" = "1" ] && exit 0
mkdir -p "$prefix/bin"
cp "$FAKE_REA_SOURCE" "$prefix/bin/rea"
chmod +x "$prefix/bin/rea"
`,
);
await executable(
join(bin, "curl"),
`#!/bin/sh
[ "\${FAKE_CURL_FAIL:-}" = "1" ] && exit 1
if [ -n "\${FAKE_CURL_BODY:-}" ]; then printf '%s' "$FAKE_CURL_BODY"; else printf '%s' '{"tag_name":"rea-agents-0.3.0"}'; fi
`,
);
await executable(
join(bin, "rea-source"),
`#!/bin/sh
printf '%s\n' "$*" >> "$FAKE_REA_LOG"
[ "\${FAKE_REA_VERSION_FAIL:-}" = "1" ] && exit 1
[ "$1" = "--version" ] && printf '%s\n' "\${FAKE_REA_VERSION:-0.3.0}"
exit 0
`,
);
for (const command of ["chmod", "cp", "mkdir", "tr"])
await symlink(`/usr/bin/${command}`, join(bin, command));
return { home, bin, temporary, npmLog, reaLog };
};
const executable = async (path: string, source: string): Promise<void> => {
await writeFile(path, source);
await chmod(path, 0o755);
};
const runInstaller = async (
fixture: InstallerFixture,
args: readonly string[] = [],
overrides: Readonly<Record<string, string>> = {},
): Promise<{ readonly stdout: string; readonly stderr: string }> =>
execFileAsync("/bin/bash", [join(process.cwd(), "install.sh"), ...args], {
env: {
...process.env,
HOME: fixture.home,
TMPDIR: fixture.temporary,
PATH: `${fixture.bin}:/usr/bin:/bin`,
FAKE_NPM_LOG: fixture.npmLog,
FAKE_REA_LOG: fixture.reaLog,
FAKE_REA_SOURCE: join(fixture.bin, "rea-source"),
FAKE_NPM_PREFIX: join(fixture.home, ".npm-global"),
...overrides,
},
});
const shellQuote = (value: string): string =>
`'${value.replaceAll("'", `'"'"'`)}'`;
@@ -0,0 +1,222 @@
import fs from "node:fs";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { add, commit, init } from "isomorphic-git";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
importReferenceSource,
normalizeHistoricalSourceParseFailures,
} from "../../../src/application/ReferenceSourceImport.js";
import { projectReferenceSourceEntryFailure } from "../../../src/application/ReferenceSourceImportEntries.js";
import {
projectReferenceSourceImportError,
type ReferenceSourceImportError,
} from "../../../src/application/ReferenceSourceImportTypes.js";
import { createHistoricalSourceManifest } from "../../../src/domain/referenceSourceGraph.js";
const limits = {
maxBytes: 1024 * 1024,
maxEntries: 1_000,
maxDepth: 16,
maxPathBytes: 4_096,
};
const fixture = async (parent: string, name: string): Promise<string> => {
const root = join(parent, name);
await mkdir(join(root, "src"), { recursive: true });
await Promise.all([
writeFile(join(root, "src", "main.ts"), 'import "./dep";\n'),
writeFile(join(root, "src", "dep.ts"), "export const value = 1;\n"),
writeFile(join(root, "src", "broken.ts"), "const = ;\n"),
writeFile(join(root, ".env"), "SECRET_SENTINEL=do-not-record\n"),
writeFile(join(root, "package.json"), '{"name":"fixture"}\n'),
]);
return root;
};
const importTree = (
root: string,
approvedRoot: string | readonly string[],
signal?: AbortSignal,
) =>
importReferenceSource({
root,
caller: "reference-import-test",
policy: {
roots: typeof approvedRoot === "string" ? [approvedRoot] : approvedRoot,
secretPatterns: [".env", ".env.*"],
...limits,
},
limits,
...(signal === undefined ? {} : { signal }),
});
describe("reference source import error projection", () => {
it("deduplicates exact parse failures without collapsing distinct reasons", () => {
const malformed = {
path: "src/main.ts",
parser: "babel",
reason: "Malformed input",
};
const unexpected = {
path: "src/main.ts",
parser: "babel",
reason: "Unexpected token",
};
expect(
normalizeHistoricalSourceParseFailures([
unexpected,
malformed,
unexpected,
]),
).toEqual([malformed, unexpected]);
});
it("projects entry failures without low-level reader diagnostics", () => {
for (const [kind, code] of [
["directory", "io"],
["symlink", "io"],
["file", "io"],
["file", "cancelled"],
["file", "limit"],
["unknown", "unsupported"],
] as const) {
const message = projectReferenceSourceEntryFailure({
status: "failed",
path: "safe/path",
kind,
code,
message: "SECRET internal diagnostic /private/path",
});
expect(message).not.toContain("SECRET");
expect(message).not.toContain("/private/path");
expect(message).toMatch(/Check|try again|when ready|smaller|supported/u);
}
});
it("projects every import failure without raw parser or policy text", () => {
const expectedCategories = {
cancelled: "cancelled",
"invalid-limits": "invalid_input",
"invalid-root": "invalid_input",
io: "execution_failure",
parse: "execution_failure",
policy: "permission_required",
} as const;
for (const [code, category] of Object.entries(expectedCategories)) {
const projected = projectReferenceSourceImportError({
tag: "reference-source-import",
code: code as ReferenceSourceImportError["code"],
message: "SECRET parser stack and /private/path",
});
expect(projected.category).toBe(category);
expect(projected.message).not.toContain("SECRET");
expect(projected.message).not.toContain("/private/path");
expect(projected.message).toMatch(
/try again|when ready|positive integer|Check that|REA_REFERENCE_ROOTS_JSON/u,
);
}
});
});
describe("reference source import behavior", () => {
it("is relocation-stable, resolves imports, and excludes secrets before capture", async () => {
const parent = await createTestTempDirectory("rea-reference-import-");
try {
const leftRoot = await fixture(parent, "left");
const rightRoot = await fixture(parent, "right");
const [left, right] = await Promise.all([
importTree(leftRoot, parent),
importTree(rightRoot, parent),
]);
expect(left.ok).toBe(true);
expect(right.ok).toBe(true);
if (!left.ok || !right.ok) throw new Error("expected imports to pass");
expect(createHistoricalSourceManifest(left.value)).toEqual(
createHistoricalSourceManifest(right.value),
);
expect(left.value.relationships).toContainEqual(
expect.objectContaining({
from_path: "src/main.ts",
to: "src/dep.ts",
resolution: "internal",
}),
);
expect(left.value.parse_failures).toHaveLength(1);
expect(left.value.exclusions).toContainEqual({
path: ".env",
reason: "configured-secret",
});
expect(JSON.stringify(left.value)).not.toContain("SECRET_SENTINEL");
expect(JSON.stringify(left.value)).not.toContain(leftRoot);
} finally {
await rm(parent, { recursive: true, force: true });
}
});
it("fails closed outside policy and honors cancellation", async () => {
const parent = await createTestTempDirectory("rea-reference-policy-");
const outside = await createTestTempDirectory("rea-reference-outside-");
try {
const root = await fixture(outside, "tree");
const denied = await importTree(root, parent);
expect(denied).toMatchObject({
ok: false,
error: { code: "policy" },
});
const controller = new AbortController();
controller.abort();
const cancelled = await importTree(root, outside, controller.signal);
expect(cancelled).toMatchObject({
ok: false,
error: { code: "cancelled" },
});
} finally {
await Promise.all([
rm(parent, { recursive: true, force: true }),
rm(outside, { recursive: true, force: true }),
]);
}
});
it("uses a valid reference root when another configured root is missing", async () => {
const parent = await createTestTempDirectory("rea-reference-roots-");
try {
const root = await fixture(parent, "tree");
const imported = await importTree(root, [
join(parent, "missing"),
parent,
]);
expect(imported).toMatchObject({ ok: true });
} finally {
await rm(parent, { recursive: true, force: true });
}
});
it("records bounded local Git state without invoking Git", async () => {
const parent = await createTestTempDirectory("rea-reference-git-");
try {
const root = await fixture(parent, "repo");
await init({ fs, dir: root, defaultBranch: "main" });
for (const filepath of ["package.json", "src/main.ts", "src/dep.ts"])
await add({ fs, dir: root, filepath });
const oid = await commit({
fs,
dir: root,
author: { name: "REA Test", email: "rea@example.invalid" },
message: "fixture",
});
const result = await importTree(root, parent);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.vcs).toEqual({ kind: "git", head: oid, dirty: null });
} finally {
await rm(parent, { recursive: true, force: true });
}
});
});
@@ -0,0 +1,228 @@
import { mkdir, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { readReferenceSource } from "../../../src/reference/ReferenceSourceReader.js";
const limits = {
maxBytes: 1_024,
maxEntries: 10,
maxDepth: 4,
maxPathBytes: 100,
} as const;
describe("readReferenceSource entries", () => {
it("returns explicit entries in canonical code-point path order", async () => {
const root = await createTestTempDirectory("rea-reference-");
await mkdir(join(root, "nested"));
await writeFile(join(root, "z.js"), "z");
await writeFile(join(root, "a.js"), "a");
await writeFile(join(root, "nested", "b.js"), "b");
await writeFile(join(root, "\u{e000}"), "p");
await writeFile(join(root, "\u{10000}"), "a");
const result = await readReferenceSource(root, limits);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.entries.map(({ path }) => path)).toEqual([
"a.js",
"nested",
"nested/b.js",
"z.js",
"",
"𐀀",
]);
expect(result.value.bytesRead).toBe(5);
expect(result.value.truncated).toBe(false);
expect(
result.value.entries.map((entry) =>
entry.status === "read" && entry.kind === "file"
? Buffer.from(entry.bytes).toString()
: entry.status === "read"
? entry.kind
: entry.code,
),
).toEqual(["a", "directory", "b", "z", "p", "a"]);
expect(result.value.limitations).toHaveLength(1);
});
it("sanitizes internal, external, and missing symlink targets", async () => {
const root = await createTestTempDirectory("rea-reference-");
const outside = await createTestTempDirectory("rea-outside-");
await writeFile(join(outside, "secret"), "secret");
await writeFile(join(root, "local"), "local");
await symlink("local", join(root, "internal"));
await symlink(join(outside, "secret"), join(root, "external"));
await symlink("absent", join(root, "missing"));
const result = await readReferenceSource(root, limits);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.entries).toEqual([
{
status: "read",
kind: "symlink",
path: "external",
target: "<outside-root>",
targetState: "external",
},
{
status: "read",
kind: "symlink",
path: "internal",
target: "local",
targetState: "internal",
},
{
status: "read",
kind: "file",
path: "local",
bytes: expect.any(Uint8Array),
size: 5,
},
{
status: "read",
kind: "symlink",
path: "missing",
target: "absent",
targetState: "missing",
},
]);
expect(result.value.bytesRead).toBe(5);
expect(JSON.stringify(result.value.entries)).not.toContain(outside);
});
it("makes byte, file, depth, and path limits explicit per entry", async () => {
const root = await createTestTempDirectory("rea-reference-");
await writeFile(join(root, "a"), "too large");
await writeFile(join(root, "b"), "b");
await mkdir(join(root, "deep"));
await writeFile(join(root, "deep", "c"), "c");
const result = await readReferenceSource(root, {
maxBytes: 1,
maxEntries: 1,
maxDepth: 1,
maxPathBytes: 4,
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.truncated).toBe(true);
expect(result.value.entries).toEqual([
expect.objectContaining({
path: "a",
kind: "file",
status: "failed",
code: "limit",
size: 9,
}),
]);
expect(result.value.limitations).toContain(
"Traversal stopped because the entry limit was reached.",
);
expect(result.value.entries).not.toContainEqual(
expect.objectContaining({ path: "<tree>" }),
);
});
it("applies maxEntries as a global limit across every entry kind", async () => {
const root = await createTestTempDirectory("rea-reference-");
await writeFile(join(root, "a"), "a");
await writeFile(join(root, "b"), "b");
await writeFile(join(root, "c"), "c");
const result = await readReferenceSource(root, {
...limits,
maxEntries: 1,
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value.entries.map(({ path }) => path)).toEqual(["a"]);
expect(result.value.bytesRead).toBe(1);
expect(result.value.truncated).toBe(true);
});
});
describe("readReferenceSource failures and exclusions", () => {
it("applies exclusions to normalized paths before reading entries", async () => {
const root = await createTestTempDirectory("rea-reference-");
await mkdir(join(root, "ignored"));
await writeFile(join(root, "ignored", "secret"), "secret");
await writeFile(join(root, "kept"), "kept");
const checked: string[] = [];
const result = await readReferenceSource(root, limits, {
shouldExclude: (path) => {
checked.push(path);
return path === "ignored";
},
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(checked).toEqual(["ignored", "kept"]);
expect(result.value.entries.map(({ path }) => path)).toEqual(["kept"]);
});
it("sanitizes exclusion callback failures", async () => {
const root = await createTestTempDirectory("rea-reference-");
await writeFile(join(root, "file"), "value");
const result = await readReferenceSource(root, limits, {
shouldExclude: () => {
throw new Error("private callback detail");
},
});
expect(result).toEqual({
ok: false,
error: {
tag: "reference-source-reader",
code: "io",
message: "Reference source exclusion check failed",
},
});
});
it("sanitizes filesystem errors", async () => {
const missing = join(tmpdir(), "rea-secret-root-that-does-not-exist");
const result = await readReferenceSource(missing, limits);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error.message).toBe(
"Reference source root could not be resolved",
);
expect(result.error.message).not.toContain(missing);
});
it("returns typed failures for cancellation and invalid roots", async () => {
const controller = new AbortController();
controller.abort();
const cancelled = await readReferenceSource("/unused", limits, {
signal: controller.signal,
});
expect(cancelled).toEqual({
ok: false,
error: {
tag: "reference-source-reader",
code: "cancelled",
message: "Reference source traversal cancelled",
},
});
const invalid = await readReferenceSource(
"/path/that/does/not/exist",
limits,
);
expect(invalid.ok).toBe(false);
if (invalid.ok) return;
expect(invalid.error.code).toBe("invalid-root");
});
});
@@ -0,0 +1,70 @@
import { createHash } from "node:crypto";
import { access, readFile, readdir } from "node:fs/promises";
import { join } from "node:path";
import { Readable } from "node:stream";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { SafeOutputTree } from "../../../src/artifacts/SafeOutputTree.js";
const LIMITS = {
maxEntries: 10,
maxTotalBytes: 1_024,
maxEntryBytes: 512,
maxCompressionRatio: 10,
maxDepth: 8,
maxPathBytes: 256,
} as const;
describe("safe artifact output tree", () => {
it("removes only its owned tree after digest failure and proves absence", async () => {
const parent = await createTestTempDirectory("rea-safe-output-");
const output = join(parent, "published");
const tree = await SafeOutputTree.create(output, LIMITS);
await expect(
tree.write(
"nested/file.txt",
Readable.from(Buffer.from("unexpected")),
"0".repeat(64),
),
).rejects.toThrow(/disagrees/u);
expect(await tree.rollback()).toMatchObject({
attempted: true,
verified: true,
residualPaths: [],
});
await expect(access(output)).rejects.toThrow();
expect(await readdir(parent)).toEqual([]);
});
it("publishes files while building and preserves them after sealing", async () => {
const parent = await createTestTempDirectory("rea-safe-output-");
const output = join(parent, "published");
const tree = await SafeOutputTree.create(output, LIMITS);
const bytes = Buffer.from("visible before seal");
const digest = createHash("sha256").update(bytes).digest("hex");
await tree.write("file.txt", Readable.from(bytes), digest);
expect(await readFile(join(output, "file.txt"), "utf8")).toBe(
"visible before seal",
);
await tree.commit();
expect(await tree.rollback()).toMatchObject({ attempted: false });
expect(await readFile(join(output, "file.txt"), "utf8")).toBe(
"visible before seal",
);
});
it("returns detached cleanup reports", async () => {
const parent = await createTestTempDirectory("rea-safe-output-");
const tree = await SafeOutputTree.create(join(parent, "published"), LIMITS);
const cleanup = await tree.rollback();
(cleanup.residualPaths as string[]).push("/forged/path");
expect(tree.cleanup.residualPaths).toEqual([]);
expect((await tree.rollback()).residualPaths).toEqual([]);
});
});
@@ -0,0 +1,36 @@
import { access, realpath, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe.sequential("test temporary directory ownership", () => {
let completedDirectory: string | undefined;
it("creates a canonical directory owned by the current test", async () => {
const directory = await createTestTempDirectory("rea-owned-temp-");
completedDirectory = directory;
expect(directory).toBe(await realpath(directory));
expect(dirname(directory)).toBe(await realpath(tmpdir()));
await writeFile(join(directory, "nested.txt"), "owned");
});
it("removes the prior test directory after that test finishes", async () => {
const directory = completedDirectory;
if (directory === undefined)
throw new Error("Prior test did not create a directory");
await expect(access(directory)).rejects.toMatchObject({
code: "ENOENT",
});
});
it.each(["", "../escape-", "/absolute-", "missing-dash"])(
"rejects unsafe prefix %j",
async (prefix) => {
await expect(createTestTempDirectory(prefix)).rejects.toThrow(TypeError);
},
);
});