fix(apple): distinguish cache loadability and propagate search uncertainty

This commit is contained in:
morluto
2026-10-08 23:16:28 +08:00
129 changed files with 3977 additions and 1588 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ cliTest(
join(root, "files", "modules", "main.js"),
artifacts.source,
);
const manifestPath = join(root, "manifest.json");
const manifestPath = join(root, "manifest.json").replaceAll("\\", "/");
await writeFile(manifestPath, JSON.stringify(manifest));
const environment = {
REA_LOG_LEVEL: "silent",
+42 -2
View File
@@ -1,4 +1,10 @@
import { expect } from "vitest";
import { expect, onTestFinished } from "vitest";
import { Client } from "@modelcontextprotocol/client";
import {
StdioClientTransport,
getDefaultEnvironment,
} from "@modelcontextprotocol/client/stdio";
import { fileURLToPath } from "node:url";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { webSourceLocationFixture } from "../fixtures/webSourceLocation.js";
@@ -12,7 +18,7 @@ cliTest(
const fixture = webSourceLocationFixture();
await mkdir(join(root, "files", "modules"), { recursive: true });
await writeFile(join(root, "files", "modules", "main.js"), fixture.source);
const manifest = join(root, "manifest.json");
const manifest = join(root, "manifest.json").replaceAll("\\", "/");
const map = join(root, "app.js.map");
await writeFile(manifest, JSON.stringify(fixture.manifest));
await writeFile(map, fixture.sourceMap.text);
@@ -44,6 +50,40 @@ cliTest(
runtime: { id: "node-v8" },
},
});
const transport = new StdioClientTransport({
command: process.execPath,
args: [
fileURLToPath(new URL("../../scripts/rea.mjs", import.meta.url)),
"mcp",
],
env: { ...getDefaultEnvironment(), REA_LOG_LEVEL: "silent" },
stderr: "pipe",
});
const client = new Client({
name: "source-location-cli-parity",
version: "1",
});
onTestFinished(async () => {
try {
await client.close();
} finally {
await transport.close();
}
});
await client.connect(transport);
const mcpResponse = await client.callTool({
name: "trace_web_source_location",
arguments: {
manifest_path: manifest,
script_index: 0,
source_map: { path: map, url: fixture.sourceMap.url },
generated_position: { line: 1, column: 0 },
},
});
expect(mcpResponse.isError, JSON.stringify(mcpResponse)).not.toBe(true);
expect(mcpResponse.structuredContent).toMatchObject({
evidence: response.json,
});
const invalid = await cli.run({
arguments: [
"trace-web-source-location",
+27 -6
View File
@@ -38,6 +38,7 @@ const fixtureApp = async (): Promise<string> => {
"<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
"Contents/MacOS/App": machoImage({
commands: [
buildVersionCommand(1),
rpathCommand("@executable_path/../Frameworks"),
dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"),
dylibCommand(LC.LOAD_WEAK_DYLIB, "@rpath/libgone.dylib"),
@@ -45,10 +46,16 @@ const fixtureApp = async (): Promise<string> => {
}),
"Contents/Frameworks/libcore.dylib": machoImage({
fileType: FILE_TYPE.dylib,
commands: [dylibCommand(LC.ID_DYLIB, "@rpath/libcore.dylib")],
commands: [
buildVersionCommand(1),
dylibCommand(LC.ID_DYLIB, "@rpath/libcore.dylib"),
],
}),
"Contents/Helpers/tool": machoImage({
commands: [dylibCommand(LC.LOAD_DYLIB, "@loader_path/libnone.dylib")],
commands: [
buildVersionCommand(1),
dylibCommand(LC.LOAD_DYLIB, "@loader_path/libnone.dylib"),
],
}),
});
return app;
@@ -157,11 +164,15 @@ describe("trace-dylib-resolution CLI inputs", () => {
await writeFiles(directory, {
tool: machoImage({
commands: [
buildVersionCommand(1),
dylibCommand(LC.LOAD_DYLIB, "@loader_path/lib/libhelper.dylib"),
dylibCommand(LC.LOAD_DYLIB, "@loader_path/../escape.dylib"),
],
}),
"lib/libhelper.dylib": machoImage({ fileType: FILE_TYPE.dylib }),
"lib/libhelper.dylib": machoImage({
fileType: FILE_TYPE.dylib,
commands: [buildVersionCommand(1)],
}),
"unrelated.txt": "not traversed",
});
const result = await cli.run({
@@ -221,11 +232,17 @@ describe("trace-dylib-resolution CLI inputs", () => {
dyld_shared_cache_arm64e: dyldCacheFixture([
{
path: "/usr/lib/libSystem.B.dylib",
bytes: machoImage({ fileType: FILE_TYPE.dylib }),
bytes: machoImage({
fileType: FILE_TYPE.dylib,
commands: [buildVersionCommand(1)],
}),
},
{
path: "/usr/lib/swift/libswiftCore.dylib",
bytes: machoImage({ fileType: FILE_TYPE.dylib }),
bytes: machoImage({
fileType: FILE_TYPE.dylib,
commands: [buildVersionCommand(1)],
}),
inSubcache: true,
},
]).main,
@@ -272,10 +289,14 @@ describe.skipIf(process.getuid?.() === 0)(
await writeFiles(directory, {
tool: machoImage({
commands: [
buildVersionCommand(1),
dylibCommand(LC.LOAD_DYLIB, "@loader_path/libsecret.dylib"),
],
}),
"libsecret.dylib": machoImage({ fileType: FILE_TYPE.dylib }),
"libsecret.dylib": machoImage({
fileType: FILE_TYPE.dylib,
commands: [buildVersionCommand(1)],
}),
});
await chmod(join(directory, "libsecret.dylib"), 0o000);
try {
+8 -3
View File
@@ -95,7 +95,7 @@ describe("canonical product catalog", () => {
);
});
it("matches every source-derived checked-in product fact", async () => {
it("matches every source-derived build-generated product fact", async () => {
const catalog = await createProductCatalog(root);
expect(catalog.tools.total).toBe(TOOL_CONTRACTS.length);
expect(
@@ -195,14 +195,19 @@ describe("canonical product catalog", () => {
"project_managed_application_graph",
"verify_managed_native_boundaries",
]);
// Runtime schema commitments must not fan out into checked-in documentation.
// Provider commitments cover the facts actually present in this projection.
expect(Object.keys(catalog.runtime_catalog.digests)).toEqual([
"providers_sha256",
]);
expect(catalog.runtime_catalog.digests.providers_sha256).toBe(
providerCatalogDigest(catalog.providers),
);
expect(
JSON.parse(await readFile("docs/product-catalog.json", "utf8")),
JSON.parse(await readFile("docs/public/product-catalog.json", "utf8")),
).toEqual(catalog);
expect(await serializeProductCatalog(catalog)).toBe(
await readFile("docs/product-catalog.json", "utf8"),
await readFile("docs/public/product-catalog.json", "utf8"),
);
await expect(
assertDocumentationFacts(root, catalog),
@@ -164,7 +164,7 @@ const createBuildCacheFixture = async (): Promise<string> => {
"scripts/clean-build-output.mjs",
"scripts/generate-package-metadata.mjs",
"scripts/lib/generated-file.mjs",
"skills/reverse-engineer-anything/SKILL.md",
"skill-src/reverse-engineer-anything/SKILL.md",
"src/generatedPackageMetadata.ts",
];
await Promise.all(
@@ -10,6 +10,7 @@ import {
} from "../../../src/artifacts/apple/DyldSharedCache.fixture.js";
import {
FILE_TYPE,
CPU,
buildVersionCommand,
LC,
dylibCommand,
@@ -51,10 +52,19 @@ it("rejects a directory and overlapping combined VM mappings with specific reaso
});
});
const dylib = (installName: string, dependencies: readonly Uint8Array[] = []) =>
const dylib = (
installName: string,
dependencies: readonly Uint8Array[] = [],
platform = 1,
) =>
machoImage({
fileType: FILE_TYPE.dylib,
commands: [dylibCommand(LC.ID_DYLIB, installName), ...dependencies],
cpu: CPU.arm64e,
commands: [
buildVersionCommand(platform),
dylibCommand(LC.ID_DYLIB, installName),
...dependencies,
],
});
it("rejects a same-UUID subcache whose architecture or VM offset disagrees", async () => {
@@ -354,7 +364,12 @@ it.each([
])(
"decodes simulator cache family %i into platform %i and retains raw metadata",
async (raw, normalized) => {
const fixture = dyldCacheFixture(IMAGES.slice(0, 1));
const fixture = dyldCacheFixture([
{
path: "/usr/lib/libSystem.B.dylib",
bytes: dylib("/usr/lib/libSystem.B.dylib", [], normalized),
},
]);
const main = Buffer.from(fixture.main);
main.writeUInt32LE(raw, 0xd8);
main.writeUInt32LE(1 << 9, 0xdc);
@@ -10,6 +10,7 @@ import {
writeEvidenceBundle,
} from "../../../src/application/EvidenceBundleFiles.js";
import { compareEvidenceBundlesCommand } from "../../../src/application/EvidenceBundleCommands.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
createEvidenceBundle,
@@ -116,6 +117,32 @@ describe("evidence bundle filesystem adapter", () => {
});
});
it("reports a missing file or output directory with the selected path", async () => {
const directory = await createTestTempDirectory("rea-evidence-");
const absent = join(directory, "absent.json");
const read = await readEvidenceBundle(absent);
expect(read).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "missing", path: absent },
});
if (read.ok) throw new Error("Expected a missing-file failure");
expect(projectAnalysisError(read.error)).toMatchObject({
message: expect.stringContaining("does not exist at the selected path"),
details: { operation: "read", reason: "missing", path: absent },
});
const orphan = join(directory, "absent", "bundle.json");
const written = await writeEvidenceBundle(bundle(), orphan, false);
expect(written).toMatchObject({
ok: false,
error: { _tag: "EvidenceFileError", reason: "missing", path: orphan },
});
if (written.ok) throw new Error("Expected a missing-directory failure");
expect(projectAnalysisError(written.error).message).toContain(
"output directory does not exist",
);
});
it("rejects malformed and tampered input", async () => {
const directory = await createTestTempDirectory("rea-evidence-");
const malformed = join(directory, "malformed.json");
@@ -136,7 +163,55 @@ describe("evidence bundle filesystem adapter", () => {
);
expect(await readEvidenceBundle(tamperedPath)).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
error: {
_tag: "EvidenceIntegrityError",
userMessage: expect.stringContaining(
"Evidence semantic identifier does not match its record",
),
},
});
});
it("names the failed bundle constraint for a single record or schema mismatch", async () => {
const directory = await createTestTempDirectory("rea-evidence-");
const record = bundle().records[0];
const single = join(directory, "record.json");
await writeFile(single, JSON.stringify(record));
expect(await readEvidenceBundle(single)).toMatchObject({
ok: false,
error: {
_tag: "EvidenceIntegrityError",
userMessage: expect.stringContaining(
`this JSON is one Evidence record (${String(record?.evidence_id)})`,
),
},
});
const partial = join(directory, "partial.json");
await writeFile(partial, JSON.stringify({ evidence_id: "typo" }));
const rejected = await readEvidenceBundle(partial);
expect(rejected).toMatchObject({
ok: false,
error: {
userMessage: expect.stringContaining(
"does not match the bundle schema",
),
},
});
expect(rejected).not.toMatchObject({
error: { userMessage: expect.stringContaining("one Evidence record") },
});
const mismatched = join(directory, "mismatched.json");
await writeFile(mismatched, JSON.stringify({ ...bundle(), records: {} }));
expect(await readEvidenceBundle(mismatched)).toMatchObject({
ok: false,
error: {
_tag: "EvidenceIntegrityError",
userMessage: expect.stringContaining(
"does not match the bundle schema at records:",
),
},
});
});
});
@@ -0,0 +1,125 @@
import { execFile } from "node:child_process";
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const exec = promisify(execFile);
const repositoryRoot = fileURLToPath(new URL("../../..", import.meta.url));
const authored =
'---\nname: reverse-engineer-anything\nmetadata:\n version: "33"\n---\n\n# Instructions\n\nInspect the caller-selected artifact.\n';
async function fixture(eol = "\n") {
const root = await createTestTempDirectory("rea-generated-skill-");
for (const path of [
"scripts/generate-skill-metadata.mjs",
"scripts/lib/generated-file.mjs",
]) {
await mkdir(dirname(join(root, path)), { recursive: true });
await copyFile(join(repositoryRoot, path), join(root, path));
}
const sourceRoot = join(root, "skill-src/reverse-engineer-anything");
const outputRoot = join(root, "skills/reverse-engineer-anything");
await mkdir(join(sourceRoot, "references"), { recursive: true });
await mkdir(join(root, "dist"));
await writeFile(join(root, "package.json"), '{"type":"module"}\n');
await writeFile(join(sourceRoot, "SKILL.md"), authored.replaceAll("\n", eol));
await writeFile(
join(sourceRoot, "references/guide.md"),
`# Guide${eol}Preserve evidence.${eol}`,
);
const identity = async (count: number, digest: string) =>
writeFile(
join(root, "dist/catalogIdentity.js"),
`export const CATALOG_IDENTITY = ${JSON.stringify({ counts: { mcp_tools: count }, digests: { combined_sha256: digest } })};\n`,
);
await identity(139, "a".repeat(64));
const generate = (...args: string[]) =>
exec(
process.execPath,
[join(root, "scripts/generate-skill-metadata.mjs"), ...args],
{ cwd: root },
);
return { sourceRoot, outputRoot, identity, generate };
}
it.each(["\n", "\r\n"])(
"generates revision-specific metadata without rewriting authored instructions (%j)",
async (eol) => {
const f = await fixture(eol);
await f.generate();
const first = await readFile(join(f.outputRoot, "SKILL.md"), "utf8");
expect(first).not.toContain("catalog_digest:");
expect(first).toContain("tool_count: 139");
expect(
first.replace(/^ {2}(?:tool_count|catalog_digest):[^\n]*\n/gmu, ""),
).toBe(authored);
expect(
await readFile(join(f.outputRoot, "references/guide.md"), "utf8"),
).toBe("# Guide\nPreserve evidence.\n");
await f.identity(139, "b".repeat(64));
await f.generate();
expect(await readFile(join(f.outputRoot, "SKILL.md"), "utf8")).toBe(first);
await f.identity(140, "b".repeat(64));
await expect(f.generate("--check")).rejects.toMatchObject({
stderr: expect.stringContaining("missing or stale"),
});
await f.generate();
expect(await readFile(join(f.outputRoot, "SKILL.md"), "utf8")).toContain(
"tool_count: 140",
);
expect(await readFile(join(f.sourceRoot, "SKILL.md"), "utf8")).toBe(
authored.replaceAll("\n", eol),
);
expect(
await readFile(join(f.sourceRoot, "references/guide.md"), "utf8"),
).toBe(`# Guide${eol}Preserve evidence.${eol}`);
await expect(f.generate("--check")).resolves.toMatchObject({ stderr: "" });
},
);
it("rejects missing, stale, and extra packaged references and removes deleted source files on rebuild", async () => {
const f = await fixture();
await f.generate();
const guide = join(f.outputRoot, "references/guide.md");
await rm(guide);
await expect(f.generate("--check")).rejects.toMatchObject({
stderr: expect.stringContaining("guide.md is missing or stale"),
});
await f.generate();
await writeFile(guide, "modified reference\n");
await expect(f.generate("--check")).rejects.toMatchObject({
stderr: expect.stringContaining("guide.md is missing or stale"),
});
await f.generate();
await writeFile(
join(f.outputRoot, "references/removed.md"),
"obsolete instructions\n",
);
await expect(f.generate("--check")).rejects.toMatchObject({
stderr: expect.stringContaining("file inventory drifted"),
});
await rm(join(f.sourceRoot, "references/guide.md"));
await f.generate();
await expect(readFile(guide)).rejects.toMatchObject({ code: "ENOENT" });
await expect(
readFile(join(f.outputRoot, "references/removed.md")),
).rejects.toMatchObject({ code: "ENOENT" });
await f.generate("--check");
});
it("rejects catalog-dependent metadata in the authored source", async () => {
const f = await fixture();
await writeFile(
join(f.sourceRoot, "SKILL.md"),
authored.replace(' version: "33"', ' version: "33"\n tool_count: 139'),
);
await expect(f.generate()).rejects.toMatchObject({
stderr: expect.stringContaining(
"Catalog metadata belongs in the generated skill",
),
});
});
@@ -0,0 +1,99 @@
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { build } from "plist";
import { expect, it } from "vitest";
import { ArtifactReaderFailure } from "../../../src/artifacts/ArtifactReader.js";
import { inspectBundleKeyedArchive } from "../../../src/artifacts/apple/KeyedArchiveReader.js";
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const archive = build({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: ["$null", "value"],
$top: { root: { CF$UID: 1 }, other: { CF$UID: 1 } },
});
const bundle = async () => {
const root = await createTestTempDirectory("rea-keyed-selection-");
await mkdir(join(root, "Contents", "Resources"), { recursive: true });
await writeFile(
join(root, "Contents", "Resources", "Model.plist"),
Buffer.from(archive),
);
return root;
};
const inspect = (bundlePath: string, parameters: Record<string, unknown>) =>
inspectBundleKeyedArchive({
bundlePath,
targetSha256: "a".repeat(64),
parameters,
});
it.each([
[".", "invalid_format", "relative to the active app bundle"],
["Contents/../Model.plist", "invalid_format", "canonical relative"],
["Contents//Model.plist", "invalid_format", "canonical relative"],
["Contents/Resources", "invalid_value", "selects a directory"],
["Contents/Resources/Missing.plist", "invalid_value", "No regular file"],
] as const)(
"reports caller-selected archive path %j as invalid input",
async (path, reason, message) => {
const root = await bundle();
const rejected = await inspect(root, { path }).catch(
(cause: unknown) => cause,
);
expect(rejected).toBeInstanceOf(AnalysisInputError);
expect(rejected).toMatchObject({
issues: [
{
path: ["path"],
reason,
message: expect.stringContaining(message),
},
],
});
},
);
it("reports an absent named root with the archive's available roots", async () => {
const root = await bundle();
await expect(
inspect(root, { path: "Contents/Resources/Model.plist", root: "missing" }),
).rejects.toMatchObject({
issues: [
{
path: ["root"],
reason: "invalid_value",
message: expect.stringContaining("missing"),
expected: ["root", "other"],
},
],
});
});
it.each([
["plain plist", Buffer.from(build({ plain: true })), "NSKeyedArchiver"],
[
"compiled NIBArchive",
Buffer.concat([Buffer.from("NIBArchive"), Buffer.alloc(40)]),
"decode_interface_builder",
],
])(
"keeps the decoder reason for a selected %s",
async (_label, bytes, detail) => {
const root = await bundle();
await writeFile(join(root, "Contents", "Resources", "Other.nib"), bytes);
const rejected = await inspect(root, {
path: "Contents/Resources/Other.nib",
}).catch((cause: unknown) => cause);
expect(rejected).toBeInstanceOf(ArtifactReaderFailure);
expect(rejected).toMatchObject({
reason: "format",
message: expect.stringContaining(detail),
});
},
);
@@ -50,7 +50,6 @@ async function metadata(directory: string, version: string, notes: string) {
version,
packages: [{ identifier: "rea-agents", version }],
},
"docs/product-catalog.json": { package: { version } },
"release-please-config.json": {
"changelog-sections": [
{ type: "feat", hidden: false },
@@ -371,7 +370,6 @@ it("validates candidate options before inspecting the working directory", async
it.each([
"package-lock.json",
"server.json",
"docs/product-catalog.json",
"src/generatedPackageMetadata.ts",
])("rejects inconsistent version metadata in %s", async (path) => {
const f = await fixture();
@@ -103,11 +103,11 @@ it("requires explicit release preparation or publication instead of main pushes"
"skip-github-release": "${{ inputs.phase == 'prepare' }}",
"skip-github-pull-request": "${{ inputs.phase == 'publish' }}",
});
const catalogCommit = workflow.jobs["release-please"].steps.find(
(step) => step.name === "Commit canonical release catalog",
const catalogValidation = workflow.jobs["release-please"].steps.find(
(step) => step.name === "Validate generated release documentation",
);
expect(catalogCommit?.env?.GH_TOKEN).toBe(
"${{ secrets.RELEASE_PLEASE_TOKEN || secrets.GITHUB_TOKEN }}",
expect(catalogValidation?.run).toBe(
"npm run docs:check && git diff --exit-code",
);
});
@@ -203,7 +203,7 @@ it("binds npm and MCP publication to the same immutable release SHA", async () =
"Set up Node.js for generated documentation",
"Install dependencies",
"Regenerate release documentation",
"Commit canonical release catalog",
"Validate generated release documentation",
];
for (const name of preparation) {
expect(
+107 -1
View File
@@ -1,4 +1,5 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { createHash } from "node:crypto";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -7,8 +8,14 @@ import {
canonicalSkillNeedsInstall,
installCanonicalSkill,
} from "../../../src/application/SetupSkill.js";
import {
runDoctor,
systemDoctorHost,
} from "../../../src/application/Doctor.js";
import { createDoctorHostFixture } from "../../../src/application/Doctor.fixture.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { z } from "zod";
import { skillReferenceIssues } from "../../../scripts/lib/docs-facts.mjs";
describe("canonical skill transaction", () => {
@@ -83,6 +90,7 @@ describe("canonical skill transaction", () => {
expect(installedSkill).toContain(
`tool_count: ${String(TOOL_CONTRACTS.length)}`,
);
expect(installedSkill).not.toContain("catalog_digest:");
expect(await readFile(sibling, "utf8")).toBe("unrelated skill\n");
expect(
await readFile(
@@ -97,4 +105,102 @@ describe("canonical skill transaction", () => {
expect(await installCanonicalSkill(home)).toBe("unchanged");
expect(await skillReferenceIssues(dirname(destination))).toEqual([]);
});
it("binds portable conformance to the generated skill bytes that setup installs", async () => {
const home = await createTestTempDirectory("rea-skill-commitment-");
expect(await installCanonicalSkill(home)).toBe("installed");
const paths = [
"SKILL.md",
"references/android-applications.md",
"references/evidence-workflows.md",
"references/javascript-applications.md",
"references/native-and-artifacts.md",
"references/runtime-observation.md",
];
const records = await Promise.all(
paths.map(async (path) => {
const bytes = await readFile(
join(home, ".agents/skills/reverse-engineer-anything", path),
);
return `${path}\0${createHash("sha256").update(bytes).digest("hex")}\n`;
}),
);
const manifest = z
.object({
skill_digests: z.array(
z.object({ skill_id: z.string(), sha256: z.string() }),
),
})
.parse(
JSON.parse(
await readFile(
"docs/verification/managed-conformance-manifest.json",
"utf8",
),
),
);
expect(manifest.skill_digests).toContainEqual({
skill_id: "reverse-engineer-anything",
sha256: createHash("sha256").update(records.join("")).digest("hex"),
});
});
});
it("doctor verifies installed instructions and references even when metadata is current", async () => {
const home = await createTestTempDirectory("rea-skill-doctor-");
const destination = join(
home,
".agents/skills/reverse-engineer-anything/SKILL.md",
);
const reference = join(
dirname(destination),
"references/evidence-workflows.md",
);
const system = systemDoctorHost({
environment: { HOME: home, USERPROFILE: home },
});
const host = createDoctorHostFixture({
installedSkillIdentity: () =>
system.installedSkillIdentity?.() ?? Promise.resolve(undefined),
});
expect((await runDoctor(undefined, host)).identity?.skill.state).toBe(
"missing",
);
expect(await installCanonicalSkill(home)).toBe("installed");
expect((await runDoctor(undefined, host)).identity?.skill).toMatchObject({
state: "aligned",
installed_catalog_digest: null,
});
const legacyDigest = "0".repeat(64);
await writeFile(
destination,
(await readFile(destination, "utf8")).replace(
` tool_count: ${String(TOOL_CONTRACTS.length)}`,
` tool_count: ${String(TOOL_CONTRACTS.length)}\n catalog_digest: "${legacyDigest}"`,
),
);
expect((await runDoctor(undefined, host)).identity?.skill).toMatchObject({
state: "stale",
installed_catalog_digest: legacyDigest,
});
expect(await installCanonicalSkill(home)).toBe("installed");
for (const path of [destination, reference]) {
const canonical = await readFile(path, "utf8");
await writeFile(path, `${canonical}\nLocally changed instructions.\n`);
expect((await runDoctor(undefined, host)).identity?.skill.state).toBe(
"stale",
);
expect(await installCanonicalSkill(home)).toBe("installed");
expect((await runDoctor(undefined, host)).identity?.skill.state).toBe(
"aligned",
);
}
await rm(reference);
expect((await runDoctor(undefined, host)).identity?.skill.state).toBe(
"stale",
);
expect(await installCanonicalSkill(home)).toBe("installed");
expect((await runDoctor(undefined, host)).identity?.skill.state).toBe(
"aligned",
);
});
@@ -0,0 +1,77 @@
import { mkdir, writeFile } from "node:fs/promises";
import { isAbsolute, join, relative, sep } from "node:path";
import { expect, it } from "vitest";
import { LocalWebScriptArtifacts } from "../../../src/browser/assets/LocalWebScriptArtifacts.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { webModuleArtifactsFixture } from "../../fixtures/webModuleTrace.js";
const materialize = async () => {
const root = join(
await createTestTempDirectory("rea-script-manifest-path-"),
"export with spaces",
);
const artifact = webModuleArtifactsFixture();
await mkdir(join(root, "files", "modules"), { recursive: true });
await mkdir(join(root, "nested"));
const sourcePath = join(root, "files", "modules", "main.js");
const manifestPath = join(root, "manifest.json");
await writeFile(sourcePath, artifact.source);
await writeFile(manifestPath, JSON.stringify(artifact.manifest));
return { root, artifact, sourcePath, manifestPath };
};
it("reads equivalent local manifest spellings without changing reported identity", async () => {
const fixture = await materialize();
const paths = new Set([
fixture.manifestPath,
fixture.manifestPath.replaceAll("\\", "/"),
`${fixture.root}${sep}nested${sep}..${sep}manifest.json`,
]);
const fromWorkingDirectory = relative(process.cwd(), fixture.manifestPath);
// A target on another Windows drive has no relative path from this cwd.
if (!isAbsolute(fromWorkingDirectory))
paths.add(`.${sep}${fromWorkingDirectory}`);
for (const operation of [
"trace_web_module_imports",
"trace_web_source_location",
] as const) {
for (const manifestPath of paths) {
const response = await new LocalWebScriptArtifacts(operation).load({
manifest_path: manifestPath,
script_index: 0,
});
if (!response.ok) throw response.error;
expect(response.value.source).toBe(fixture.artifact.source);
expect(response.value.sourceFile).toEqual({
...fixture.artifact.sourceFile,
path: fixture.sourcePath,
});
expect(response.value.manifestFile.path).toBe(manifestPath);
expect(response.value.manifest.output_directory).toBe(
fixture.artifact.manifest.output_directory,
);
expect(response.value.manifest.scripts[0]?.url).toBe(
fixture.artifact.manifest.scripts[0]?.url,
);
}
}
});
it("still rejects changed source bytes after normalizing the selected manifest path", async () => {
const fixture = await materialize();
await writeFile(fixture.sourcePath, "tampered source");
const response = await new LocalWebScriptArtifacts(
"trace_web_module_imports",
).load({
manifest_path: `${fixture.root}/nested/../manifest.json`.replaceAll(
"\\",
"/",
),
script_index: 0,
});
if (response.ok) throw new Error("Expected source integrity mismatch");
expect(projectAnalysisError(response.error).code).toBe(
"artifact_integrity_mismatch",
);
});
@@ -0,0 +1,168 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { Client } from "@modelcontextprotocol/client";
import {
StdioClientTransport,
getDefaultEnvironment,
} from "@modelcontextprotocol/client/stdio";
import { expect, it } from "vitest";
import { z } from "zod";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { setupRegistrationCommand } from "../../../src/application/SetupHost.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const configurationSchema = z.object({
mcpServers: z.object({
rea: z.object({ command: z.string(), args: z.array(z.string()) }),
}),
});
it("migrates bare Windows npx registrations idempotently and uninstalls only REA", async () => {
const home = await createTestTempDirectory("rea-windows-registration-");
const configPath = join(home, ".claude.json");
const original = JSON.stringify({
theme: "dark",
mcpServers: {
other: { command: "another-server" },
rea: {
command: "npx",
args: ["-y", PRODUCT_IDENTITY.registrationPackageSpecifier, "mcp"],
},
},
});
await writeFile(configPath, original);
expect(
await readClientRegistrationStatuses(home, undefined, {
platform: "win32",
environment: {},
}),
).toContainEqual(
expect.objectContaining({ client: "claude_code", state: "stale" }),
);
const client = { name: "claude_code", configPath, format: "json" } as const;
const command = setupRegistrationCommand("win32", true);
expect(await configureClientConfiguration(client, {}, command)).toMatchObject(
{ status: "configured" },
);
expect(
await readClientRegistrationStatuses(home, undefined, {
platform: "win32",
environment: {},
}),
).toContainEqual(
expect.objectContaining({ client: "claude_code", state: "aligned" }),
);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
expect(await systemUninstallHost(home).removeClient(client)).toMatchObject({
status: "removed",
});
const remaining: unknown = JSON.parse(await readFile(configPath, "utf8"));
expect(remaining).toEqual({
theme: "dark",
mcpServers: { other: { command: "another-server" } },
});
});
it("keeps the Windows launcher aligned through Codex TOML setup and removal", async () => {
const home = await createTestTempDirectory("rea-windows-codex-");
await mkdir(join(home, ".codex"));
const configPath = join(home, ".codex", "config.toml");
const original = '[mcp_servers.other]\ncommand = "another-server"\n';
await writeFile(configPath, original);
const client = { name: "codex", configPath, format: "toml" } as const;
const command = setupRegistrationCommand("win32", true);
expect(await configureClientConfiguration(client, {}, command)).toMatchObject(
{ status: "configured" },
);
expect(
await readClientRegistrationStatuses(home, undefined, {
platform: "win32",
environment: {},
}),
).toContainEqual(
expect.objectContaining({ client: "codex", state: "aligned" }),
);
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
expect(await systemUninstallHost(home).removeClient(client)).toMatchObject({
status: "removed",
});
const remaining = await readFile(configPath, "utf8");
expect(remaining).toContain("[mcp_servers.other]");
expect(remaining).toContain('command = "another-server"');
expect(remaining).not.toContain("mcp_servers.rea");
});
it.skipIf(process.platform !== "win32")(
"starts the written Windows registration through a native npx.cmd shim",
async () => {
const root = await createTestTempDirectory("rea-windows-mcp-");
const home = join(root, "home with spaces");
await mkdir(home);
const configPath = join(home, ".claude.json");
const setupClient = {
name: "claude_code",
configPath,
format: "json",
} as const;
// The default writer and npm-run setup must produce the same native launcher.
expect(await configureClientConfiguration(setupClient)).toMatchObject({
status: "configured",
});
const decoded: unknown = JSON.parse(await readFile(configPath, "utf8"));
const registration = configurationSchema.parse(decoded).mcpServers.rea;
expect([registration.command, ...registration.args]).toEqual(
setupRegistrationCommand("win32", true),
);
const entry = fileURLToPath(
new URL("../../../scripts/rea.mjs", import.meta.url),
);
// Exercise the actual batch-shim boundary without registry access or package installation.
await writeFile(
join(home, "npx.cmd"),
[
"@echo off",
'if not "%~1"=="-y" exit /b 11',
`if not "%~2"=="${PRODUCT_IDENTITY.registrationPackageSpecifier}" exit /b 12`,
'if not "%~3"=="mcp" exit /b 13',
`"${process.execPath}" "${entry}" mcp`,
"",
].join("\r\n"),
);
const transport = new StdioClientTransport({
command: registration.command,
args: registration.args,
cwd: home,
env: getDefaultEnvironment(),
stderr: "pipe",
});
const client = new Client({ name: "windows-setup-launcher", version: "1" });
try {
await client.connect(transport);
expect(client.getServerVersion()?.version).toBe(
PRODUCT_IDENTITY.packageVersion,
);
const status = await client.callTool({
name: "binary_session",
arguments: {},
});
expect(status.isError).not.toBe(true);
expect(status.structuredContent).toMatchObject({
result: { open: false },
});
} finally {
await client.close();
await transport.close();
}
},
30_000,
);
@@ -62,6 +62,40 @@ it("inspects a standalone keyed archive through MCP with original object identit
arguments: { path: "other.plist" },
});
expect(rejected.isError).toBe(true);
expect(rejected.structuredContent).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [
{
path: ["path"],
reason: "invalid_value",
expected: "archive.plist",
},
],
},
},
});
const missingRoot = await client.callTool({
name: "inspect_keyed_archive",
arguments: { root: "missing" },
});
expect(missingRoot.isError).toBe(true);
expect(missingRoot.structuredContent).toMatchObject({
error: {
code: "invalid_request",
details: {
issues: [
{
path: ["root"],
reason: "invalid_value",
message: expect.stringContaining("missing"),
expected: Object.keys(graph.roots),
},
],
},
},
});
} finally {
await client.close();
await server.close();
@@ -106,6 +106,42 @@ describe("bundle comparison MCP integration", () => {
await connected.close();
}
});
it("explains that a single Evidence record is not a bundle", async () => {
const root = await createTestTempDirectory("rea-bundle-record-");
roots.push(root);
const record = sourceEvidence("single");
const recordPath = join(root, "record.json");
const bundlePath = join(root, "bundle.json");
await Promise.all([
writeFile(recordPath, JSON.stringify(record)),
writeFile(
bundlePath,
serializeEvidenceBundle(createEvidenceBundle([record])),
),
]);
const connected = await connect();
try {
const result = await connected.client.callTool({
name: "compare_bundles",
arguments: {
left_bundle_path: recordPath,
right_bundle_path: bundlePath,
},
});
expect(result.isError).toBe(true);
expect(result.structuredContent).toMatchObject({
error: {
code: "evidence_integrity_mismatch",
message: expect.stringContaining(
`this JSON is one Evidence record (${record.evidence_id})`,
),
},
});
} finally {
await connected.close();
}
});
});
const connect = async () => {
+14 -3
View File
@@ -8,6 +8,7 @@ import { z } from "zod";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import {
FILE_TYPE,
buildVersionCommand,
LC,
dylibCommand,
machoImage,
@@ -55,6 +56,7 @@ it("traces dylib resolution for an opened app bundle and rejects a changed targe
executable,
machoImage({
commands: [
buildVersionCommand(1),
rpathCommand("@executable_path/../Frameworks"),
dylibCommand(LC.LOAD_DYLIB, "@rpath/libcore.dylib"),
],
@@ -62,7 +64,10 @@ it("traces dylib resolution for an opened app bundle and rejects a changed targe
);
await writeFile(
join(app, "Contents/Frameworks/libcore.dylib"),
machoImage({ fileType: FILE_TYPE.dylib }),
machoImage({
fileType: FILE_TYPE.dylib,
commands: [buildVersionCommand(1)],
}),
);
await withClient(async (client) => {
const opened = await client.callTool({
@@ -129,12 +134,18 @@ it("traces a standalone Mach-O file whose name ends in .app", async () => {
await writeFile(
join(directory, "Tool.app"),
machoImage({
commands: [dylibCommand(LC.LOAD_DYLIB, "@loader_path/libcore.dylib")],
commands: [
buildVersionCommand(1),
dylibCommand(LC.LOAD_DYLIB, "@loader_path/libcore.dylib"),
],
}),
);
await writeFile(
join(directory, "libcore.dylib"),
machoImage({ fileType: FILE_TYPE.dylib }),
machoImage({
fileType: FILE_TYPE.dylib,
commands: [buildVersionCommand(1)],
}),
);
await withClient(async (client) => {
const opened = await client.callTool({
@@ -31,12 +31,15 @@ const providerNames = [
"REA deterministic process harness",
];
const captureEvidence = (side: "left" | "right") =>
const captureEvidence = (
side: "left" | "right",
result: Evidence["normalized_result"] = EMPTY_PROCESS_CAPTURE_EXAMPLE,
) =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: { side },
result: EMPTY_PROCESS_CAPTURE_EXAMPLE,
result,
confidence: "observed",
authority: "controlled-replay",
environment: {
@@ -335,3 +338,34 @@ it("separately rejects a tampered digest before admission to any consumer or ses
});
}
});
it("keeps withheld ownership unknown through CLI and MCP comparison", async () => {
const { client, right } = await connectedComparison();
const left = captureEvidence("left", {
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
cleanup: {
...EMPTY_PROCESS_CAPTURE_EXAMPLE.cleanup,
unverified_processes: [
{ pid: 900, reason: "platform_binary_environment_withheld" },
],
},
residual_unknowns: [
{ scope: "process", reason: "Ownership of process 900 was withheld" },
],
});
const response = await client.callTool({
name: "compare_process_captures",
arguments: { left, right },
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const comparison = inlineEvidence(response);
expect(comparison.normalized_result).toMatchObject({ status: "unknown" });
const root = await createTestTempDirectory("rea-withheld-ownership-");
const leftPath = join(root, "left.json");
const rightPath = join(root, "right.json");
await writeFile(leftPath, JSON.stringify(left));
await writeFile(rightPath, JSON.stringify(right));
expect(
parseEvidence(await compareProcessEvidenceFiles(leftPath, rightPath)),
).toEqual(comparison);
});
@@ -5,6 +5,7 @@ import { WebNetworkCaptureService } from "../../../src/application/WebNetworkCap
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { ok } from "../../../src/domain/result.js";
import { webNetworkCaptureSchema } from "../../../src/domain/webNetworkCapture.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
@@ -17,7 +18,7 @@ it("publishes valid SDK schemas and retains historical inline Evidence with the
format: "har",
decoder: { id: "test-capture-port", name: "test port", version: "1" },
container: {
reported: { creator: "fixture" },
reported: { creator: "fixture", ["__proto__"]: { preserved: 7 } },
numeric_literals: [],
redactions: [],
records_pointer: "/log/entries",
@@ -72,6 +73,15 @@ it("publishes valid SDK schemas and retains historical inline Evidence with the
);
const evidence = parseEvidence(parsed.evidence);
expect(parsed.result).toEqual(evidence.normalized_result);
const capture = webNetworkCaptureSchema.parse(parsed.result);
expect(capture.container.reported).toEqual({
creator: "fixture",
["__proto__"]: { preserved: 7 },
});
expect(Object.getPrototypeOf(capture.container.reported)).toBe(
Object.prototype,
);
expect(Reflect.get(Object.prototype, "preserved")).toBeUndefined();
expect(session.evidenceById(evidence.evidence_id)).toEqual(evidence);
const invalid = await client.callTool({
name: "inspect_web_network_capture",
@@ -25,7 +25,7 @@ describe("analysis error projection contract", () => {
).map(
(reason) => new ArtifactOperationError("inventory_artifact", reason),
),
...(["not-file", "exists", "invalid-json", "io"] as const).map(
...(["not-file", "exists", "invalid-json", "missing", "io"] as const).map(
(reason) => new EvidenceFileError("read", reason),
),
...(
@@ -47,11 +47,6 @@ describe("release configuration", () => {
path: "server.json",
jsonpath: "$.packages[0].version",
},
{
type: "json",
path: "docs/product-catalog.json",
jsonpath: "$.package.version",
},
],
},
},