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,50 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import {
generateLargeFixture,
HOPPER_C_ORACLE,
LARGE_FIXTURE_COUNT,
sha256,
sourceDigest,
} from "../../../scripts/lib/conformance-fixtures.mjs";
describe("source-built conformance fixtures", () => {
it("grounds the Hopper semantic oracle in the source-owned C fixture", async () => {
const source = await readFile("tests/conformance/c/fixture.c", "utf8");
for (const procedure of [
HOPPER_C_ORACLE.mainProcedure,
HOPPER_C_ORACLE.entryProcedure,
HOPPER_C_ORACLE.branchProcedure,
HOPPER_C_ORACLE.leafProcedure,
])
expect(source).toContain(`int ${procedure}`);
expect(source).toContain(HOPPER_C_ORACLE.entryString);
expect(source).toContain(HOPPER_C_ORACLE.leafString);
expect(source).toContain(HOPPER_C_ORACLE.globalName);
});
it("generates a deterministic large pagination fixture", () => {
const first = generateLargeFixture();
const second = generateLargeFixture();
expect(first).toBe(second);
expect(first.match(/int rea_page_/gu)).toHaveLength(LARGE_FIXTURE_COUNT);
expect(first).toContain("rea_page_0000");
expect(first).toContain("rea_page_1204");
expect(() => generateLargeFixture(0)).toThrow(/positive integer/u);
});
it("hashes source manifests independently of input ordering", () => {
const left = [
{ path: "b.c", content: "b" },
{ path: "a.c", content: "a" },
];
const right = [...left].reverse();
expect(sourceDigest(left)).toBe(sourceDigest(right));
expect(sourceDigest(left)).toMatch(/^[0-9a-f]{64}$/u);
expect(sha256("fixture")).not.toBe(sha256("changed"));
});
});
@@ -0,0 +1,181 @@
import { describe, expect, it } from "vitest";
import {
CONFORMANCE_PACKAGE_VERSION,
conformancePackageSchema,
computePackageId,
createConformancePackage,
validateConformancePackage,
type ScenarioManifest,
type ReplayPlan,
type ShimPlan,
type ExpectedEvidence,
} from "../../../src/domain/conformancePackage.js";
const validPackage = createConformancePackage({
schema_version: CONFORMANCE_PACKAGE_VERSION,
name: "test-fixture",
description: "A test conformance fixture",
created_at: "2026-07-28T00:00:00Z",
scenarios: [
{
scenario_id: "s1",
name: "Simple spawn",
description: "A simple process spawn scenario",
fixture_path: "tests/conformance/c/fixture.c",
expected_exit_code: 0,
expected_patterns: ["Hello", "World"],
},
],
replay_plans: [
{
scenario_id: "s1",
steps: [
{
step_id: "step1",
action: "compile",
arguments: ["gcc", "fixture.c"],
timeout_ms: 5000,
},
],
environment: {},
},
],
shim_plans: [],
expected_evidence: [
{
scenario_id: "s1",
envelopes: [],
bundle: null,
required_dimensions: ["exit_code", "stdout"],
},
],
verifier_contracts: [
{
scenario_id: "s1",
dimensions: [
{
name: "exit_code",
required: true,
comparison: "exact",
},
],
timing_tolerance_ms: 100,
},
],
});
describe("conformance package format", () => {
it("validates a well-formed package", () => {
const result = validateConformancePackage(validPackage);
expect(result.ok).toBe(true);
});
it("rejects invalid schema version", () => {
const result = validateConformancePackage({
...validPackage,
schema_version: 999,
});
expect(result.ok).toBe(false);
});
it("rejects duplicate scenario IDs", () => {
const result = validateConformancePackage({
...validPackage,
scenarios: [validPackage.scenarios[0], validPackage.scenarios[0]],
});
expect(result.ok).toBe(false);
});
it("rejects replay plan referencing non-existent scenario", () => {
const result = validateConformancePackage({
...validPackage,
replay_plans: [
{
scenario_id: "nonexistent",
steps: [
{
step_id: "step1",
action: "run",
arguments: [],
timeout_ms: 1000,
},
],
environment: {},
},
],
});
expect(result.ok).toBe(false);
});
it("rejects verifier contract referencing non-existent scenario", () => {
const result = validateConformancePackage({
...validPackage,
verifier_contracts: [
{
scenario_id: "nonexistent",
dimensions: [
{ name: "exit_code", required: true, comparison: "exact" },
],
timing_tolerance_ms: 0,
},
],
});
expect(result.ok).toBe(false);
});
it("rejects expected evidence referencing non-existent scenario", () => {
const result = validateConformancePackage({
...validPackage,
expected_evidence: [
{
scenario_id: "nonexistent",
envelopes: [],
bundle: null,
required_dimensions: [],
},
],
});
expect(result.ok).toBe(false);
});
it("computes a deterministic package ID", () => {
const id = computePackageId({
...validPackage,
});
expect(id).toMatch(/^cp_[a-f0-9]{64}$/u);
// Same input yields same ID
const id2 = computePackageId({
...validPackage,
});
expect(id).toBe(id2);
});
it("produces different IDs for different packages", () => {
const id1 = computePackageId({ ...validPackage, name: "packageA" });
const id2 = computePackageId({ ...validPackage, name: "packageB" });
expect(id1).not.toBe(id2);
});
it("uses all exported types", () => {
const scenario: ScenarioManifest = validPackage.scenarios[0]!;
expect(scenario.scenario_id).toBe("s1");
const replay: ReplayPlan = validPackage.replay_plans[0]!;
expect(replay.scenario_id).toBe("s1");
const shim: ShimPlan = validPackage.shim_plans[0] ?? {
scenario_id: "s1",
shims: [],
};
expect(shim.scenario_id).toBe("s1");
const evidence: ExpectedEvidence = validPackage.expected_evidence[0]!;
expect(evidence.scenario_id).toBe("s1");
});
it("parses via zod schema", () => {
const result = conformancePackageSchema.safeParse(validPackage);
expect(result.success).toBe(true);
});
});
@@ -0,0 +1,190 @@
import { describe, expect, it } from "vitest";
import {
CONFORMANCE_PACKAGE_VERSION,
createConformancePackage,
type ConformancePackage,
} from "../../../src/domain/conformancePackage.js";
import {
replayConformancePackage,
type ScenarioReplayResult,
} from "../../../src/domain/conformanceReplay.js";
const validPackage = createConformancePackage({
schema_version: CONFORMANCE_PACKAGE_VERSION,
name: "test-fixture",
description: "A test conformance fixture",
created_at: "2026-07-28T00:00:00Z",
scenarios: [
{
scenario_id: "s1",
name: "Simple spawn",
description: "A simple process spawn scenario",
fixture_path: "tests/conformance/c/fixture.c",
expected_exit_code: 0,
expected_patterns: [],
},
],
replay_plans: [
{
scenario_id: "s1",
steps: [
{
step_id: "step1",
action: "run",
arguments: [],
timeout_ms: 1000,
},
],
environment: {},
},
],
shim_plans: [],
expected_evidence: [
{
scenario_id: "s1",
envelopes: [],
bundle: null,
required_dimensions: [],
},
],
verifier_contracts: [
{
scenario_id: "s1",
dimensions: [{ name: "exit_code", required: true, comparison: "exact" }],
timing_tolerance_ms: 0,
},
],
});
async function passingRunner(
scenarioId: string,
): Promise<ScenarioReplayResult> {
return {
scenario_id: scenarioId,
status: "pass",
exit_code: 0,
duration_ms: 10,
output: "ok",
error: null,
};
}
async function failingRunner(
scenarioId: string,
): Promise<ScenarioReplayResult> {
return {
scenario_id: scenarioId,
status: "fail",
exit_code: 1,
duration_ms: 10,
output: "fail",
error: null,
};
}
describe("conformance CI replay", () => {
it("replays a package with passing scenarios", async () => {
const result = await replayConformancePackage(
validPackage,
{},
passingRunner,
);
expect(result.total_scenarios).toBe(1);
expect(result.passed).toBe(1);
expect(result.failed).toBe(0);
expect(result.errored).toBe(0);
});
it("replays a package with failing scenarios", async () => {
const result = await replayConformancePackage(
validPackage,
{},
failingRunner,
);
expect(result.failed).toBe(1);
expect(result.passed).toBe(0);
});
it("does not detect drift when expected and actual match", async () => {
const result = await replayConformancePackage(
validPackage,
{},
passingRunner,
);
expect(result.drift_detected).toBe(false);
});
it("throws on invalid package", async () => {
await expect(replayConformancePackage({}, {})).rejects.toThrow(
/invalid conformance package/u,
);
});
it("counts all result types", async () => {
const base: ConformancePackage = validPackage;
const multiPackage = createConformancePackage({
...base,
scenarios: [
base.scenarios[0]!,
{
scenario_id: "s2",
name: "Second scenario",
description: "Second",
fixture_path: "tests/conformance/c/fixture2.c",
expected_exit_code: 1,
expected_patterns: [],
},
],
replay_plans: [
base.replay_plans[0]!,
{
scenario_id: "s2",
steps: [
{
step_id: "step1",
action: "run",
arguments: [],
timeout_ms: 1000,
},
],
environment: {},
},
],
expected_evidence: [
base.expected_evidence[0]!,
{
scenario_id: "s2",
envelopes: [],
bundle: null,
required_dimensions: [],
},
],
verifier_contracts: [
base.verifier_contracts[0]!,
{
scenario_id: "s2",
dimensions: [
{ name: "exit_code", required: true, comparison: "exact" },
],
timing_tolerance_ms: 0,
},
],
});
const result = await replayConformancePackage(
multiPackage,
{},
async (scenarioId) => ({
scenario_id: scenarioId,
status: scenarioId === "s1" ? "pass" : "fail",
exit_code: scenarioId === "s1" ? 0 : 1,
duration_ms: 10,
output: "",
error: null,
}),
);
expect(result.total_scenarios).toBe(2);
expect(result.passed).toBe(1);
expect(result.failed).toBe(1);
});
});
@@ -0,0 +1,113 @@
import { describe, expect, it } from "vitest";
import type { VerifierContract } from "../../../src/domain/conformancePackage.js";
import {
compareDimension,
evaluateTrustGate,
isSemanticDimension,
isVolatileDimension,
} from "../../../src/domain/conformanceTrustGate.js";
const contract: VerifierContract = {
scenario_id: "s1",
dimensions: [
{ name: "exit_code", required: true, comparison: "exact" },
{ name: "stdout", required: true, comparison: "semantic" },
{ name: "timing", required: true, comparison: "fuzzy" },
],
timing_tolerance_ms: 100,
};
describe("conformance trust gates", () => {
it("classifies volatile dimensions correctly", () => {
expect(isVolatileDimension("timing")).toBe(true);
expect(isVolatileDimension("timestamp")).toBe(true);
expect(isVolatileDimension("pid")).toBe(true);
expect(isVolatileDimension("exit_code")).toBe(false);
});
it("classifies semantic dimensions correctly", () => {
expect(isSemanticDimension("exit_code")).toBe(true);
expect(isSemanticDimension("stdout")).toBe(true);
expect(isSemanticDimension("timing")).toBe(false);
});
it("matches identical values", () => {
const result = compareDimension("exit_code", 0, 0);
expect(result.status).toBe("match");
});
it("detects mismatches", () => {
const result = compareDimension("exit_code", 0, 1);
expect(result.status).toBe("mismatch");
});
it("ignores volatile dimensions", () => {
const result = compareDimension("timing", 100, 200);
expect(result.status).toBe("match");
expect(result.message).toContain("volatile");
});
it("handles truncated evidence", () => {
const result = compareDimension("exit_code", 0, null, {
truncated: true,
});
expect(result.status).toBe("truncated");
});
it("handles undefined values", () => {
const result = compareDimension("exit_code", undefined, undefined);
expect(result.status).toBe("unknown");
});
it("handles missing actual", () => {
const result = compareDimension("exit_code", 0, undefined);
expect(result.status).toBe("mismatch");
});
it("passes when all dimensions match", () => {
const result = evaluateTrustGate(
contract,
{ exit_code: 0, stdout: "hello" },
{ exit_code: 0, stdout: "hello" },
);
expect(result.verdict).toBe("pass");
});
it("fails when a required dimension mismatches", () => {
const result = evaluateTrustGate(
contract,
{ exit_code: 0, stdout: "hello" },
{ exit_code: 1, stdout: "hello" },
);
expect(result.verdict).toBe("fail");
expect(result.first_divergence).not.toBeNull();
expect(result.first_divergence!.dimension).toBe("exit_code");
});
it("reports unknown when both dimensions are undefined", () => {
const result = evaluateTrustGate(contract, {}, {});
// exit_code and stdout are both undefined -> unknown
// timing is volatile -> match
expect(result.verdict).toBe("unknown");
});
it("ignores volatile dimension differences", () => {
const result = evaluateTrustGate(
contract,
{ exit_code: 0, stdout: "hello", timing: 100 },
{ exit_code: 0, stdout: "hello", timing: 200 },
);
expect(result.verdict).toBe("pass");
});
it("truncated evidence is not treated as equivalence", () => {
const result = evaluateTrustGate(
contract,
{ exit_code: 0, stdout: "hello" },
{ exit_code: 0, stdout: "hello" },
{ truncated: true },
);
expect(result.verdict).toBe("fail");
});
});
@@ -0,0 +1,260 @@
import { createHash } from "node:crypto";
import { fc, it } from "@fast-check/vitest";
import { describe, expect } from "vitest";
import type { BinaryTarget } from "../../../src/domain/binaryTarget.js";
import {
assessManagedGraphOmissions,
managedGraphEvidenceCoverage,
totalManagedGraphOmitted,
type ManagedGraphProjectionLimits,
} from "../../../src/domain/managedApplicationGraphCoverage.js";
import {
assessKnownPageCoverage,
type KnownCollectionPage,
} from "../../../src/domain/knownPageCoverage.js";
import { inspectManagedMembersBytes } from "../../../src/dotnet/ManagedMemberInspector.js";
import { inspectManagedNativeBoundariesBytes } from "../../../src/dotnet/ManagedNativeBoundaryInspector.js";
import { buildManagedPeFixture } from "../../fixtures/managedPe.js";
const MEMBER_LIMITS = {
typeOffset: 0,
typeLimit: 100,
methodOffset: 0,
methodLimit: 100,
fieldOffset: 0,
fieldLimit: 100,
memberRefOffset: 0,
memberRefLimit: 100,
edgeOffset: 0,
edgeLimit: 100,
instructionAnchorLimit: 100,
maxMetadataBytes: 1024 * 1024,
maxTableRows: 1_000,
maxHeapItemBytes: 1024 * 1024,
maxMethodBodyBytes: 1024 * 1024,
maxMethodInstructions: 1_000,
};
const BOUNDARY_LIMITS = {
moduleRefOffset: 0,
moduleRefLimit: 100,
importOffset: 0,
importLimit: 100,
implementationOffset: 0,
implementationLimit: 100,
maxMetadataBytes: 1024 * 1024,
maxTableRows: 1_000,
maxHeapItemBytes: 1024 * 1024,
};
const limitPair = fc
.tuple(fc.integer({ min: 1, max: 12 }), fc.integer({ min: 1, max: 12 }))
.map(
([first, second]) =>
[Math.min(first, second), Math.max(first, second)] as const,
);
describe("coverage monotonicity", () => {
it.prop([fc.integer({ min: 0, max: 200 }), limitPair])(
"never makes a smaller source page more complete",
(total, [smallerLimit, largerLimit]) => {
const smaller = assessKnownPageCoverage(sourcePage(total, smallerLimit));
const larger = assessKnownPageCoverage(sourcePage(total, largerLimit));
expect(smaller.includedCount).toBeLessThanOrEqual(larger.includedCount);
expect(smaller.omittedCount).toBeGreaterThanOrEqual(larger.omittedCount);
expect(smaller.sourceOmittedCount).toBeGreaterThanOrEqual(
larger.sourceOmittedCount,
);
if (smaller.complete) expect(larger.complete).toBe(true);
},
);
it.prop([fc.integer({ min: 0, max: 200 }), limitPair])(
"never makes a smaller downstream projection more complete",
(total, [smallerLimit, largerLimit]) => {
const page = sourcePage(total, Math.max(1, total));
const smaller = assessKnownPageCoverage(page, smallerLimit);
const larger = assessKnownPageCoverage(page, largerLimit);
expect(smaller.includedCount).toBeLessThanOrEqual(larger.includedCount);
expect(smaller.omittedCount).toBeGreaterThanOrEqual(larger.omittedCount);
expect(smaller.sourceComplete).toBe(larger.sourceComplete);
if (smaller.complete) expect(larger.complete).toBe(true);
},
);
it.prop([
fc.array(fc.integer({ min: 0, max: 12 }), {
minLength: 5,
maxLength: 5,
}),
fc.array(limitPair, { minLength: 5, maxLength: 5 }),
])(
"does not improve aggregate managed graph coverage when projection limits shrink",
(totals, pairs) => {
const sources = managedSources(totals);
const smaller = assessManagedGraphOmissions(
sources,
graphLimits(pairs, 0),
);
const larger = assessManagedGraphOmissions(
sources,
graphLimits(pairs, 1),
);
const smallerCoverage = managedGraphEvidenceCoverage(smaller);
const largerCoverage = managedGraphEvidenceCoverage(larger);
expect(totalManagedGraphOmitted(smaller)).toBeGreaterThanOrEqual(
totalManagedGraphOmitted(larger),
);
expect(smaller.types).toBeGreaterThanOrEqual(larger.types);
expect(smaller.methods).toBeGreaterThanOrEqual(larger.methods);
expect(smaller.fields).toBeGreaterThanOrEqual(larger.fields);
expect(smaller.pinvokeImports).toBeGreaterThanOrEqual(
larger.pinvokeImports,
);
expect(smaller.nativeImplementations).toBeGreaterThanOrEqual(
larger.nativeImplementations,
);
if (smallerCoverage.status === "complete")
expect(largerCoverage.status).toBe("complete");
},
);
it("does not let wider projection limits repair parser-unknown input", () => {
const sources = managedSources([2, 2, 2, 2, 2]);
const partialSources = {
...sources,
members: {
...sources.members,
coverage: {
state: "partial" as const,
issues: [
{
code: "limit-exceeded" as const,
scope: "method.0x06000001.body.instructions",
offset: 0x0a00,
detail: "instruction limit reached",
},
],
},
},
};
const narrow = managedGraphEvidenceCoverage(
assessManagedGraphOmissions(partialSources, constantGraphLimits(1)),
);
const wide = managedGraphEvidenceCoverage(
assessManagedGraphOmissions(partialSources, constantGraphLimits(100)),
);
expect(narrow).toMatchObject({
status: "partial",
truncated: false,
omitted_count: null,
});
expect(wide).toEqual(narrow);
});
});
const sourcePage = (
total: number,
limit: number,
): KnownCollectionPage<number> => {
const returned = Math.min(total, limit);
return {
items: Array.from({ length: returned }, (_, index) => index),
offset: 0,
limit,
total,
returned,
complete: returned === total,
};
};
const fixtureBytes = buildManagedPeFixture({
pinvoke: {
moduleName: "user32.dll",
importName: "MessageBoxW",
mappingFlags: 0x0345,
},
readyToRun: true,
});
const fixtureTarget: BinaryTarget = {
path: "/fixture/ManagedCoverage.exe",
sha256: createHash("sha256").update(fixtureBytes).digest("hex"),
kind: "executable",
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
};
const fixtureMembers = inspectManagedMembersBytes(
fixtureBytes,
fixtureTarget,
MEMBER_LIMITS,
);
const fixtureBoundaries = inspectManagedNativeBoundariesBytes(
fixtureBytes,
fixtureTarget,
BOUNDARY_LIMITS,
);
const managedSources = (totals: readonly number[]) => ({
artifact: null,
members: {
...fixtureMembers,
types: repeatPage(fixtureMembers.types, totals[0] ?? 0),
methods: repeatPage(fixtureMembers.methods, totals[1] ?? 0),
fields: repeatPage(fixtureMembers.fields, totals[2] ?? 0),
},
boundaries: {
...fixtureBoundaries,
pinvoke_imports: repeatPage(
fixtureBoundaries.pinvoke_imports,
totals[3] ?? 0,
),
native_implementations: repeatPage(
fixtureBoundaries.native_implementations,
totals[4] ?? 0,
),
},
});
const repeatPage = <Item, Page extends KnownCollectionPage<Item>>(
page: Page,
total: number,
) => {
const first = page.items[0];
const items =
first === undefined ? [] : Array.from({ length: total }, () => first);
return {
...page,
items,
offset: 0,
limit: Math.max(1, total),
total,
returned: total,
complete: true,
};
};
const graphLimits = (
pairs: readonly (readonly [number, number])[],
index: 0 | 1,
): ManagedGraphProjectionLimits => ({
max_types: pairs[0]?.[index] ?? 1,
max_methods: pairs[1]?.[index] ?? 1,
max_fields: pairs[2]?.[index] ?? 1,
max_pinvoke_imports: pairs[3]?.[index] ?? 1,
max_native_implementations: pairs[4]?.[index] ?? 1,
});
const constantGraphLimits = (value: number): ManagedGraphProjectionLimits => ({
max_types: value,
max_methods: value,
max_fields: value,
max_pinvoke_imports: value,
max_native_implementations: value,
});
@@ -0,0 +1,37 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { parseExecutableHeader } from "../../../../src/domain/binaryTarget.js";
const exec = promisify(execFile);
const root = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..");
const generator = resolve(root, "scripts", "create-ghidra-windows-fixture.mjs");
const fixture = resolve(root, "build", "fixtures", "rea-ghidra-windows.exe");
const expectedSha256 =
"732ec6083ae3b63bcbda33f2d0fd7e1a6539babade07cbdae4fc20d3394faf49";
describe("controlled Windows Ghidra fixture", () => {
it("generates one deterministic native x86-64 PE application", async () => {
await exec(process.execPath, [generator]);
const bytes = await readFile(fixture);
expect(createHash("sha256").update(bytes).digest("hex")).toBe(
expectedSha256,
);
expect(parseExecutableHeader(bytes, "x64")).toMatchObject({
ok: true,
value: {
format: "pe",
architecture: "x86_64",
executableRole: "application",
managed: false,
},
});
});
});
@@ -0,0 +1,32 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
describe("real Windows Ghidra workflow trust boundary", () => {
it("runs only default-branch code on the fixed self-hosted environment", async () => {
const workflow = await readFile(
new URL(
"../../../../.github/workflows/real-ghidra-windows.yml",
import.meta.url,
),
"utf8",
);
expect(workflow).toContain("types: [real-ghidra-windows]");
expect(workflow).not.toContain("workflow_dispatch:");
expect(workflow).toContain("contents: read");
expect(workflow).toContain("if: github.ref == 'refs/heads/main'");
expect(workflow).toContain("environment: real-ghidra-windows");
expect(workflow).toContain(
"runs-on: [self-hosted, Windows, x64, ghidra-12-1-2]",
);
expect(workflow).not.toMatch(
/\$\{\{\s*(?:inputs|github\.event\.(?:inputs|client_payload))\b/u,
);
expect(workflow).toContain("REA_ANALYSIS_PROVIDER: ghidra");
expect(workflow).not.toContain("cache: npm");
expect(workflow).not.toContain("npm run rebuild:native");
expect(workflow).toContain("npm run verify:ghidra:windows");
expect(workflow).toContain("windows-ghidra-proof.log");
});
});
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import {
probeWindowsCapabilities,
systemNoFollowOpenCapability,
type WindowsCapabilityDependencies,
} from "../../../../src/application/WindowsCapabilities.js";
const dependencies = (
overrides: Partial<WindowsCapabilityDependencies> = {},
): WindowsCapabilityDependencies => ({
platform: "win32",
architecture: "x64",
probeSymlinkCreation: () =>
Promise.resolve({ available: false, reason: "EPERM" }),
probeNoFollowOpen: () => ({
available: false,
reason: "O_NOFOLLOW is unavailable in this Node runtime",
}),
probePrivateAcl: () => ({
available: false,
reason: "Windows ACL enforcement is not implemented by this REA build",
}),
probeUnixDomainSocket: () => ({
available: false,
reason: "Node path-based IPC uses named pipes on Windows",
}),
probePty: () =>
Promise.resolve({
available: false,
backend: "node-pty",
reason: "probe unavailable",
}),
...overrides,
});
describe("Windows host capability report", () => {
it("never treats a numeric POSIX flag as Windows reparse authority", () => {
expect(systemNoFollowOpenCapability("win32", 0x20_000)).toEqual({
available: false,
reason: "Windows reparse-safe handle admission is not implemented",
});
expect(systemNoFollowOpenCapability("linux", 0x20_000)).toEqual({
available: true,
reason: null,
});
});
it("keeps unavailable security controls explicit", async () => {
await expect(probeWindowsCapabilities(dependencies())).resolves.toEqual({
platform: "win32",
architecture: "x64",
capabilities: {
symlink_creation: { available: false, reason: "EPERM" },
no_follow_open: {
available: false,
reason: "O_NOFOLLOW is unavailable in this Node runtime",
},
private_acl: {
available: false,
reason:
"Windows ACL enforcement is not implemented by this REA build",
},
unix_domain_socket: {
available: false,
reason: "Node path-based IPC uses named pipes on Windows",
},
pty: { available: false, reason: "probe unavailable" },
},
});
});
it("reports successful probes independently", async () => {
const result = await probeWindowsCapabilities(
dependencies({
probeSymlinkCreation: () =>
Promise.resolve({ available: true, reason: null }),
probePty: () =>
Promise.resolve({ available: true, backend: "node-pty" }),
}),
);
expect(result.capabilities.symlink_creation).toEqual({
available: true,
reason: null,
});
expect(result.capabilities.pty).toEqual({
available: true,
reason: null,
});
expect(result.capabilities.private_acl.available).toBe(false);
});
});
@@ -0,0 +1,274 @@
import { describe, expect, it } from "vitest";
import {
firstProcedureAddress,
requireDistinctTargetHashes,
requireAddressArray,
requireFunctionDossierOracle,
requireFunctionDossier,
requirePseudocode,
} from "../../../../src/application/RealHopperAssertions.js";
describe("real Hopper semantic assertions", () => {
it("rejects two target paths containing the same binary", () => {
expect(() => requireDistinctTargetHashes("same", "same")).toThrow(
/distinct binaries/u,
);
expect(() => requireDistinctTargetHashes("", "other")).toThrow();
expect(() => requireDistinctTargetHashes("first", "second")).not.toThrow();
});
it("extracts only a real procedure address from a structured page", () => {
expect(
firstProcedureAddress({
items: [{ address: "0x1000", name: "main" }],
offset: 0,
limit: 100,
total: 1,
next_offset: null,
has_more: false,
}),
).toBe("0x1000");
expect(() =>
firstProcedureAddress({ items: { address: "0x1000" } }),
).toThrow();
expect(() =>
firstProcedureAddress({ items: [{ address: "items" }] }),
).toThrow();
});
it("rejects empty and embedded per-item decompilation failures", () => {
expect(requirePseudocode("return 0;", "batch_decompile")).toBe("return 0;");
for (const invalid of ["", " ", "No output", "Error: invalid address"])
expect(() => requirePseudocode(invalid, "batch_decompile")).toThrow();
});
it("requires address-shaped relationship evidence", () => {
expect(requireAddressArray(["0x1000"], "xrefs")).toEqual(["0x1000"]);
expect(() => requireAddressArray(["main"], "xrefs")).toThrow();
});
it("rejects success-shaped dossiers without truthful semantic content", () => {
const dossier = validDossier();
expect(requireFunctionDossier(dossier, "0x1000")).toEqual(dossier);
expect(() =>
requireFunctionDossier(
{
...dossier,
pseudocode: {
text: "Error: failed",
returned_chars: 13,
total_chars: 13,
},
},
"0x1000",
),
).toThrow(/embedded failure/u);
expect(() =>
requireFunctionDossier(
{ ...dossier, instruction_scan: { scanned: 0, truncated: false } },
"0x1000",
),
).toThrow(/instruction scan/u);
});
it("counts Unicode code points and accepts terminal scan truncation", () => {
const dossier = validDossier();
const scanLimited = {
...dossier,
pseudocode: { text: "😀", returned_chars: 1, total_chars: 1 },
comments: {
items: [],
total: null,
returned: 0,
truncated: true,
next_offset: null,
},
instruction_scan: { scanned: 1, truncated: true },
};
expect(requireFunctionDossier(scanLimited, "0x1000")).toEqual(scanLimited);
});
});
describe("real Hopper fixture assertions", () => {
it("requires fixture-specific positive dossier evidence", () => {
const entry = fixtureDossier({
address: "0x1000",
name: "rea_entry",
callee: { address: "0x2000", name: "rea_branch" },
caller: { address: "0x0900", name: "main" },
referencedString: "REA_C_ENTRY",
comment: "REA real-Hopper verifier",
successor: "0x1010",
});
expect(
requireFunctionDossierOracle(entry, {
procedure_address: "0x1000",
callee_address: "0x2000",
caller_address: "0x0900",
referenced_string: "REA_C_ENTRY",
referenced_name: "rea_c_global",
comment: "REA real-Hopper verifier",
require_cfg_successor: true,
require_assembly: true,
}),
).toEqual(entry);
for (const field of [
"callees",
"callers",
"outgoing_references",
"referenced_strings",
"referenced_names",
"comments",
"assembly",
] as const) {
expect(() =>
requireFunctionDossierOracle(
{ ...entry, [field]: emptyCollection() },
{
procedure_address: "0x1000",
callee_address: "0x2000",
caller_address: "0x0900",
referenced_string: "REA_C_ENTRY",
referenced_name: "rea_c_global",
comment: "REA real-Hopper verifier",
require_cfg_successor: true,
require_assembly: true,
},
),
).toThrow();
}
expect(() =>
requireFunctionDossierOracle(
{
...entry,
referenced_names: bounded([
{
address: "0x4000",
value: "_rea_c_global",
source_address: "0x2000",
},
]),
},
{
procedure_address: "0x1000",
referenced_name: "rea_c_global",
},
),
).toThrow();
expect(() =>
requireFunctionDossierOracle(
{
...entry,
basic_blocks: bounded([{ start: "0x1000", successors: [] }]),
},
{
procedure_address: "0x1000",
callee_address: "0x2000",
referenced_string: "REA_C_ENTRY",
comment: "REA real-Hopper verifier",
require_cfg_successor: true,
},
),
).toThrow(/CFG successor/u);
});
});
const fixtureDossier = (input: {
readonly address: string;
readonly name: string;
readonly callee: { readonly address: string; readonly name: string };
readonly caller: { readonly address: string; readonly name: string };
readonly referencedString: string;
readonly comment: string;
readonly successor: string;
}) => ({
...validDossier(),
procedure: { address: input.address, name: input.name },
assembly: bounded(["mov eax, eax"]),
comments: bounded([
{ address: input.address, kind: "comment", text: input.comment },
]),
callees: bounded([input.callee]),
callers: bounded([input.caller]),
outgoing_references: bounded([
{
source_address: input.address,
target_address: input.callee.address,
source_procedure: { address: input.address, name: input.name },
target_procedure: input.callee,
kind: { available: false, reason: "public API did not classify kind" },
},
{
source_address: "0x1004",
target_address: "0x3000",
source_procedure: { address: input.address, name: input.name },
target_procedure: null,
kind: { available: false, reason: "public API did not classify kind" },
},
{
source_address: "0x1008",
target_address: "0x4000",
source_procedure: { address: input.address, name: input.name },
target_procedure: null,
kind: { available: false, reason: "public API did not classify kind" },
},
]),
referenced_strings: bounded([
{
address: "0x3000",
value: input.referencedString,
source_address: "0x1004",
},
]),
referenced_names: bounded([
{
address: "0x4000",
value: "_rea_c_global",
source_address: "0x1008",
},
]),
basic_blocks: bounded([
{ start: input.address, successors: [input.successor] },
{ start: input.successor, successors: [] },
]),
});
const bounded = (items: readonly unknown[]) => ({
items,
total: items.length,
returned: items.length,
truncated: false,
next_offset: null,
});
const emptyCollection = () => bounded([]);
const validDossier = () => {
const collection = {
items: [],
total: 0,
returned: 0,
truncated: false,
next_offset: null,
};
return {
procedure: { address: "0x1000", name: "main" },
pseudocode: { text: "return 0;", returned_chars: 9, total_chars: 9 },
assembly: collection,
comments: collection,
callers: collection,
callees: collection,
incoming_references: collection,
outgoing_references: collection,
referenced_strings: collection,
referenced_names: collection,
basic_blocks: {
...collection,
items: [{ successors: [] }],
total: 1,
returned: 1,
},
instruction_scan: { scanned: 1, truncated: false },
};
};
@@ -0,0 +1,136 @@
import { createHash } from "node:crypto";
import { 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 { loadRealHopperFixtureTargets } from "../../../../scripts/lib/real-hopper-fixture.mjs";
let root: string | undefined;
afterEach(async () => {
if (root !== undefined) await rm(root, { recursive: true, force: true });
root = undefined;
});
describe("real Hopper fixture binding", () => {
it("binds exact source-owned artifacts and their semantic oracle", async () => {
const manifest = await fixtureManifest();
await expect(loadRealHopperFixtureTargets(manifest)).resolves.toMatchObject(
{
primary: { path: join(root ?? "", "c") },
secondary: { path: join(root ?? "", "version-v2") },
large: { path: join(root ?? "", "large") },
largeOracle: {
symbolPrefix: "_rea_page_",
symbolCount: 1_205,
stringPrefix: "REA_PAGE_",
stringCount: 1_205,
},
oracle: {
mainProcedure: "main",
entryProcedure: "rea_entry",
branchProcedure: "rea_branch",
leafProcedure: "rea_leaf",
entryString: "REA_C_ENTRY",
leafString: "REA_C_LEAF",
globalName: "rea_c_global",
},
},
);
});
it("rejects digest drift and artifacts escaping the manifest root", async () => {
const manifest = await fixtureManifest();
await writeFile(join(root ?? "", "c"), "changed");
await expect(loadRealHopperFixtureTargets(manifest)).rejects.toThrow(
/digest/u,
);
const outside = await createTestTempDirectory("rea-hopper-outside-");
try {
await writeFile(join(outside, "c"), "primary");
await rm(join(root ?? "", "c"));
await symlink(join(outside, "c"), join(root ?? "", "c"));
await expect(loadRealHopperFixtureTargets(manifest)).rejects.toThrow(
/escapes/u,
);
} finally {
await rm(outside, { recursive: true, force: true });
}
});
it("rejects manifest entries that alias the same artifact", async () => {
const manifest = await fixtureManifest();
const parsed = JSON.parse(await readFile(manifest, "utf8")) as {
fixtures: { name: string; artifact: string; artifactSha256: string }[];
};
const primary = parsed.fixtures.find(({ name }) => name === "c");
const secondary = parsed.fixtures.find(({ name }) => name === "version-v2");
if (primary === undefined || secondary === undefined)
throw new Error("Fixture manifest setup failed");
secondary.artifact = primary.artifact;
secondary.artifactSha256 = primary.artifactSha256;
await writeFile(manifest, JSON.stringify(parsed));
await expect(loadRealHopperFixtureTargets(manifest)).rejects.toThrow(
/distinct artifacts/u,
);
});
});
const fixtureManifest = async (): Promise<string> => {
root = await createTestTempDirectory("rea-hopper-fixture-");
const primary = Buffer.from("primary");
const secondary = Buffer.from("secondary");
await Promise.all([
writeFile(join(root, "c"), primary),
writeFile(join(root, "version-v2"), secondary),
writeFile(join(root, "large"), Buffer.from("large")),
]);
const manifest = join(root, "manifest.json");
await writeFile(
manifest,
JSON.stringify({
schemaVersion: 1,
fixtures: [
{
name: "c",
artifact: "c",
artifactSha256: digest(primary),
expectations: {
hopperOracle: {
mainProcedure: "main",
entryProcedure: "rea_entry",
branchProcedure: "rea_branch",
leafProcedure: "rea_leaf",
entryString: "REA_C_ENTRY",
leafString: "REA_C_LEAF",
globalName: "rea_c_global",
},
},
},
{
name: "version-v2",
artifact: "version-v2",
artifactSha256: digest(secondary),
},
{
name: "large",
artifact: "large",
artifactSha256: digest(Buffer.from("large")),
expectations: {
symbolPrefix: "_rea_page_",
symbolCount: 1_205,
stringPrefix: "REA_PAGE_",
stringCount: 1_205,
},
},
],
}),
);
return manifest;
};
const digest = (value: Buffer): string =>
createHash("sha256").update(value).digest("hex");
@@ -0,0 +1,72 @@
import { describe, expect, it } from "vitest";
import { verifyLargeFixturePagination } from "../../../../scripts/lib/real-hopper-pagination.mjs";
const normalize = (value: unknown): unknown => value;
describe("real Hopper large-fixture pagination", () => {
it("proves every procedure and string across exact search pages", async () => {
await expect(
verifyLargeFixturePagination({
client: fixtureClient(205),
options: {},
normalizedResult: normalize,
expectedCount: 205,
symbolPrefix: "_rea_page_",
stringPrefix: "REA_PAGE_",
}),
).resolves.toEqual({
procedures: { count: 205, pages: 3 },
strings: { count: 205, pages: 3 },
});
});
it.each(["truncated", "duplicate", "wrong-total"] as const)(
"rejects %s positive evidence",
async (fault) => {
await expect(
verifyLargeFixturePagination({
client: fixtureClient(205, fault),
options: {},
normalizedResult: normalize,
expectedCount: 205,
symbolPrefix: "_rea_page_",
stringPrefix: "REA_PAGE_",
}),
).rejects.toThrow();
},
);
});
const fixtureClient = (
count: number,
fault?: "truncated" | "duplicate" | "wrong-total",
) => ({
callTool: async (request: unknown) => {
const parsed = request as {
name: string;
arguments: { offset: number; limit: number };
};
const { offset, limit } = parsed.arguments;
const returned = Math.min(limit, count - offset);
const procedure = parsed.name === "search_procedures";
const items = Array.from({ length: returned }, (_, pageIndex) => {
const index = offset + pageIndex;
const evidenceIndex = fault === "duplicate" && index === 1 ? 0 : index;
return {
address: `0x${(0x1000 + index).toString(16)}`,
value: `${procedure ? "_rea_page_" : "REA_PAGE_"}${String(evidenceIndex).padStart(4, "0")}`,
value_truncated: fault === "truncated" && index === 0,
};
});
const next = offset + returned < count ? offset + returned : null;
return {
items,
offset,
limit,
total: fault === "wrong-total" ? count + 1 : count,
next_offset: next,
has_more: next !== null,
};
},
});
@@ -0,0 +1,106 @@
import { describe, expect, it } from "vitest";
import {
analyzeFixtureProcedure,
requireCurrentDocument,
resolveFixtureProcedure,
} from "../../../../scripts/lib/real-hopper-semantic.mjs";
const normalize = (value: unknown): unknown => value;
describe("real Hopper semantic fixture resolution", () => {
it("requests assembly when analyzing fixture procedures", async () => {
const requests: unknown[] = [];
const result = await analyzeFixtureProcedure(
{
callTool: async (request: unknown) => {
requests.push(request);
return { dossier: true };
},
},
{},
{ address: "0x1000", name: "rea_entry" },
normalize,
);
expect(result).toEqual({ dossier: true });
expect(requests).toEqual([
{
name: "analyze_function",
arguments: { procedure: "0x1000", include_assembly: true },
},
]);
});
it("binds mutations to the active document, not the first listed one", async () => {
await expect(
requireCurrentDocument(
clientReturning("active"),
{},
["unrelated", "active"],
normalize,
),
).resolves.toBe("active");
await expect(
requireCurrentDocument(
clientReturning("unknown"),
{},
["unrelated", "active"],
normalize,
),
).rejects.toThrow(/current_document/u);
});
it("resolves the public search value and preserves its reported name", async () => {
const procedure = await resolveFixtureProcedure(
clientWithItems([
{
address: "0x1000",
value: "_rea_entry",
value_truncated: false,
},
]),
{},
"rea_entry",
normalize,
);
expect(procedure).toEqual({ address: "0x1000", name: "_rea_entry" });
});
it.each([
["empty", []],
[
"truncated",
[{ address: "0x1000", value: "rea_entry", value_truncated: true }],
],
[
"duplicate",
[
{ address: "0x1000", value: "rea_entry", value_truncated: false },
{ address: "0x2000", value: "_rea_entry", value_truncated: false },
],
],
[
"wrong name",
[{ address: "0x1000", value: "rea_other", value_truncated: false }],
],
])("rejects %s search evidence", async (_label, items) => {
await expect(
resolveFixtureProcedure(
clientWithItems(items),
{},
"rea_entry",
normalize,
),
).rejects.toThrow(/exactly one Hopper procedure/u);
});
});
const clientWithItems = (items: readonly unknown[]) => ({
callTool: async () => ({ items }),
});
const clientReturning = (value: unknown) => ({
callTool: async () => value,
});
@@ -0,0 +1,37 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { buildManagedPeFixture } from "../../../../scripts/lib/managed-pe-fixture.mjs";
import { parseBinaryTarget } from "../../../../src/domain/binaryTarget.js";
const workspaces: string[] = [];
afterEach(async () => {
await Promise.all(
workspaces.splice(0).map((path) => rm(path, { recursive: true })),
);
});
describe("managed conformance fixture", () => {
it("emits PE32+ headers when the COFF machine is x86-64", async () => {
const workspace = await createTestTempDirectory("rea-managed-fixture-");
workspaces.push(workspace);
const path = join(workspace, "fixture.exe");
await writeFile(path, buildManagedPeFixture({ machine: 0x8664 }));
const parsed = await parseBinaryTarget(path);
expect(parsed).toMatchObject({
ok: true,
value: {
format: "pe",
architecture: "x86_64",
managed: true,
},
});
});
});
@@ -0,0 +1,208 @@
import { describe, expect, it } from "vitest";
import { verifyManagedNativeBoundariesEvidence } from "../../../../src/application/ManagedNativeVerificationService.js";
import { MANAGED_NATIVE_VERIFICATION_EXAMPLE } from "../../../../src/contracts/managedWorkflowExamples.js";
import { createEvidence } from "../../../../src/domain/evidence.js";
import {
managedNativeVerificationInputSchema,
verifyManagedNativeBoundaries,
} from "../../../../src/domain/managedNativeVerification.js";
import { inspectMachoSchema } from "../../../../src/domain/nativeInspection.js";
const exampleInput = () =>
managedNativeVerificationInputSchema.parse(
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
);
const nativeEvidenceWithExports = (names: readonly string[]) => {
const input = exampleInput();
const native = input.native_observations[0];
if (native === undefined || native.subject === null)
throw new Error("missing native example");
const macho = inspectMachoSchema.parse(native.normalized_result);
return createEvidence(
{
path: native.subject.local_path,
sha256: native.subject.digest.sha256,
format: native.subject.format,
...(native.subject.architecture === null
? {}
: { architecture: native.subject.architecture }),
},
native.provider,
{
operation: native.operation,
parameters: native.parameters,
result: {
...macho,
exports: {
...macho.exports,
items: names.map((name, index) => ({
name,
address: `0x${(0x1000 + index).toString(16)}`,
weak: false,
reexport: false,
source: "nm",
})),
total: names.length,
},
},
rawResult: native.raw_result,
confidence: native.confidence,
authority: native.authority,
environment: native.environment,
limitations: native.limitations,
locations: native.locations,
evidenceLinks: native.evidence_links,
},
);
};
describe("managed/native boundary verification", () => {
it("verifies a P/Invoke declaration against native export Evidence", () => {
const result = verifyManagedNativeBoundaries(exampleInput());
expect(result).toMatchObject({
schema_version: 1,
algorithm: {
name: "rea-managed-native-verification",
token_to_address_mapping: "not-inferred",
},
managed_boundary: {
artifact_sha256: "6".repeat(64),
mvid: "00112233-4455-4677-8899-aabbccddeeff",
pinvoke_imports_total: 1,
},
native_observations: {
total: 1,
accepted: 1,
unsupported: 0,
symbols: 1,
},
summary: {
verified: 1,
inferred: 0,
unresolved: 0,
contradicted: 0,
},
pinvoke_imports: [
{
managed: {
import_name: "open_native",
import_scope_name: "nativehelper.dll",
declaration_verification: "managed-declaration-only",
},
status: "verified",
basis: "exact-export-name",
confidence: "observed",
matched_native: {
name: "open_native",
source: "macho-export",
},
},
],
});
expect(result.verification_id).toMatch(/^mnv_[a-f0-9]{64}$/u);
expect(result.limitations.join(" ")).toContain(
"does not prove CLR binding",
);
});
it("reports module mismatch as a contradiction within supplied Evidence", () => {
const input = exampleInput();
const native = input.native_observations[0];
if (native === undefined || native.subject === null)
throw new Error("missing native example");
const mismatched = createEvidence(
{
path: "/examples/other.dll",
sha256: native.subject.digest.sha256,
format: "pe",
...(native.subject.architecture === null
? {}
: { architecture: native.subject.architecture }),
},
native.provider,
{
operation: native.operation,
parameters: native.parameters,
result: native.normalized_result,
rawResult: native.raw_result,
confidence: native.confidence,
authority: native.authority,
environment: native.environment,
limitations: native.limitations,
locations: native.locations,
evidenceLinks: native.evidence_links,
},
);
const result = verifyManagedNativeBoundaries({
...input,
native_observations: [mismatched],
});
expect(result.summary).toMatchObject({
verified: 0,
contradicted: 1,
});
expect(result.pinvoke_imports[0]).toMatchObject({
status: "contradicted",
basis: "module-mismatch",
});
});
it("treats supported native Evidence with no symbols as unresolved", () => {
const result = verifyManagedNativeBoundaries({
...exampleInput(),
native_observations: [nativeEvidenceWithExports([])],
});
expect(result.native_observations).toMatchObject({
accepted: 1,
unsupported: 0,
symbols: 0,
});
expect(result.summary).toMatchObject({
verified: 0,
unresolved: 1,
});
expect(result.pinvoke_imports[0]).toMatchObject({
status: "unresolved",
basis: "no-native-candidate",
});
});
it("reports omitted native candidates when candidate limits truncate matches", () => {
const result = verifyManagedNativeBoundaries({
...exampleInput(),
native_observations: [
nativeEvidenceWithExports(["open_native", "_open_native"]),
],
limits: { max_native_observations: 20, max_candidates_per_import: 1 },
});
expect(result.coverage).toMatchObject({
status: "truncated",
omitted_candidates: 1,
});
expect(result.pinvoke_imports[0]?.candidates).toHaveLength(1);
});
it("wraps verification in derived workflow Evidence", () => {
const evidence = verifyManagedNativeBoundariesEvidence(exampleInput());
expect(evidence.ok).toBe(true);
if (!evidence.ok) return;
expect(evidence.value).toMatchObject({
operation: "verify_managed_native_boundaries",
provider: { id: "rea-dotnet-workflows" },
confidence: "inferred",
authority: "analyst-inference",
normalized_result: {
summary: { verified: 1 },
},
});
expect(evidence.value.evidence_links).toHaveLength(2);
});
});
+110
View File
@@ -0,0 +1,110 @@
import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import {
ENHANCED_TOOL_CONTRACTS,
OFFICIAL_TOOL_CONTRACTS,
SESSION_TOOL_CONTRACTS,
} from "../../src/contracts/toolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "../../src/contracts/nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "../../src/contracts/artifactToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "../../src/contracts/managedToolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../src/contracts/managedWorkflowToolContracts.js";
import { BROWSER_PROVIDER_TOOL_CONTRACTS } from "../../src/contracts/browserProviderToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "../../src/contracts/electronToolContracts.js";
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "../../src/contracts/javascriptRuntimeObservationToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "../../src/contracts/applicationToolContracts.js";
import { SUPPORTED_CLIENT_DEFINITIONS } from "../../src/application/SupportedClients.js";
import { PRODUCT_IDENTITY } from "../../src/identity.js";
const readmes = [
"README.md",
"README_zh.md",
"README_ja.md",
"README_ko.md",
"README_ar.md",
] as const;
const expectedToolCounts = [
OFFICIAL_TOOL_CONTRACTS.length,
ENHANCED_TOOL_CONTRACTS.length,
NATIVE_TOOL_CONTRACTS.length,
ARTIFACT_TOOL_CONTRACTS.length,
MANAGED_TOOL_CONTRACTS.length + MANAGED_WORKFLOW_TOOL_CONTRACTS.length,
BROWSER_PROVIDER_TOOL_CONTRACTS.length,
ELECTRON_TOOL_CONTRACTS.length,
JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS.length,
APPLICATION_TOOL_CONTRACTS.length,
SESSION_TOOL_CONTRACTS.length,
] as const;
const toolCountsFromReadme = (content: string, path: string): number[] => {
const lines = content.split(/\r?\n/u);
for (const [index, line] of lines.entries()) {
if (!/^\|\s*-/u.test(line)) continue;
const counts: number[] = [];
for (const row of lines.slice(index + 1)) {
if (!row.trim().startsWith("|")) break;
const count = Number(row.split("|")[2]?.trim());
if (!Number.isInteger(count)) break;
counts.push(count);
}
if (counts.length === expectedToolCounts.length) return counts;
}
throw new Error(`Missing tool-family inventory table in ${path}`);
};
describe("localized README product facts", () => {
it.each(readmes)(
"keeps commands and requirements aligned in %s",
async (path) => {
const content = await readFile(resolve(path), "utf8");
expect(content).toContain(
"curl -fsSL https://raw.githubusercontent.com/morluto/rea/main/install.sh | bash",
);
expect(content).toContain("npx rea-agents setup");
expect(content).toContain("npx -y rea-agents@latest doctor");
expect(content).toContain("rea uninstall");
expect(content).toContain(
`"args": ["-y", "${PRODUCT_IDENTITY.registrationPackageSpecifier}", "mcp"]`,
);
expect(content).toContain("Node.js 22");
expect(content).toContain("macOS 12");
expect(content).toContain("Ubuntu 24.04");
expect(content).toContain("Fedora 41");
expect(content).toContain("Arch Linux");
for (const client of SUPPORTED_CLIENT_DEFINITIONS)
expect(content).toContain(client.displayName);
if (path === "README_ar.md")
expect(content).toContain("Windows غير مدعوم حاليًا");
expect(content).toContain("MCP-tool_catalog");
expect(toolCountsFromReadme(content, path)).toEqual(expectedToolCounts);
},
);
it("keeps both English CLI onboarding paths discoverable", async () => {
const content = await readFile(resolve("README.md"), "utf8");
expect(content).toContain("npx -y rea-agents@latest analyze");
expect(content).toContain("npm install rea-agents` without `--global`");
expect(content).toContain("npm install --global rea-agents");
expect(content).toContain("rea setup");
expect(content).toContain("--install-hopper");
expect(content).toContain("docs/installation.md");
expect(content).toContain("You do not need both");
expect(content).toContain(
"npx -y rea-agents@latest setup` once to repair registrations",
);
});
it("documents stale bootstrap recovery and explicit rollback", async () => {
const content = await readFile(resolve("docs/installation.md"), "utf8");
expect(content).toContain("before REA plans or writes configuration");
expect(content).toContain(
"npm exec --yes --package=rea-agents@2.4.0 -- rea setup",
);
expect(content).toContain(
"pin persistent MCP registrations to the exact version",
);
});
});
@@ -0,0 +1,70 @@
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
const readJson = async (path: string): Promise<unknown> =>
JSON.parse(await readFile(path, "utf8")) as unknown;
const readmes = [
"README.md",
"README_zh.md",
"README_ja.md",
"README_ko.md",
"README_ar.md",
] as const;
describe("release configuration", () => {
it("updates every package-version artifact in release PRs", async () => {
const configuration = await readJson("release-please-config.json");
expect(configuration).toMatchObject({
packages: {
".": {
"extra-files": [
...readmes.map((path) => ({ type: "generic", path })),
{
type: "generic",
path: "src/generatedPackageMetadata.ts",
},
{
type: "json",
path: "docs/product-catalog.json",
jsonpath: "$.package.version",
},
],
},
},
});
});
it.each(readmes)(
"marks the versioned package example in %s",
async (path) => {
const content = await readFile(path, "utf8");
const versionBlock =
/<!-- x-release-please-start-version -->[\s\S]*?<!-- x-release-please-end -->/u.exec(
content,
)?.[0];
expect(versionBlock).toMatch(/rea-agents@\d+\.\d+\.\d+/u);
},
);
it("keeps generated metadata compatible with the generic updater", async () => {
const generator = await readFile(
"scripts/generate-package-metadata.mjs",
"utf8",
);
const generated = await readFile("src/generatedPackageMetadata.ts", "utf8");
expect(generator).toContain("x-release-please-version");
expect(generated).toContain("x-release-please-version");
});
it("keeps TypeDoc unversioned and outside the tracked documentation tree", async () => {
await expect(readJson("typedoc.json")).resolves.toMatchObject({
includeVersion: false,
out: "build/api-docs",
});
});
});
+33
View File
@@ -0,0 +1,33 @@
import { execFile } from "node:child_process";
import { copyFile, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
const execute = promisify(execFile);
describe("tech-debt marker scan", () => {
it("passes a clean tree and rejects a tree containing a marker", async () => {
const root = await createTestTempDirectory("rea-scan-todos-");
const scripts = join(root, "scripts");
const source = join(root, "src");
await Promise.all([mkdir(scripts), mkdir(source)]);
const scanner = join(scripts, "scan-todos.mjs");
await copyFile(join(process.cwd(), "scripts/scan-todos.mjs"), scanner);
await writeFile(join(source, "clean.ts"), "export const clean = true;\n");
await expect(execute(process.execPath, [scanner])).resolves.toMatchObject({
stdout: "No tech-debt markers found.\n",
});
const marker = `TO${"DO"}`;
await writeFile(join(scripts, "debt.mts"), `// ${marker}: close the gap\n`);
await expect(execute(process.execPath, [scanner])).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining(`${marker} - close the gap`),
});
});
});