chore: integrate main for process progress verification

This commit is contained in:
N0zoM1z0
2026-10-10 17:33:17 +08:00
252 changed files with 13258 additions and 1040 deletions
@@ -7,6 +7,8 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import { analysisViewLayoutEvidence } from "../../fixtures/analysisView.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
cliTest(
"projects one section from a JSON file of inline layout Evidence",
async ({ cli }) => {
@@ -43,6 +45,48 @@ cliTest(
},
);
cliTest(
"projects native function pseudocode without requiring Ghidra",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-native-view-cli-");
const parent = createEvidence(
{ path: "/fixtures/native.exe", format: "pe", sha256: "a".repeat(64) },
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
{
operation: "analyze_function",
parameters: { address: "0x401000" },
result: ghidraFunctionDossier(),
},
);
const input = join(root, "native-view.json");
await writeFile(
input,
JSON.stringify({
source: { kind: "inline", evidence: parent },
view: { kind: "native", facet: "pseudocode", offset: 0, limit: 12 },
}),
);
const result = await cli.run({
arguments: ["inspect-analysis-view", input, "--json"],
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
});
expect(result.exitCode).toBe(0);
expect(result.json).toMatchObject({
operation: "inspect_analysis_view",
normalized_result: {
kind: "native",
parent_evidence_id: parent.evidence_id,
procedure_address: "0x401000",
item: { text: "int fixture_", unit: "utf16-code-units" },
},
locations: [
{ kind: "artifact-path", path: "/fixtures/native.exe" },
{ kind: "address", address: "0x401000" },
],
});
},
);
cliTest("rejects malformed JSON before projection", async ({ cli }) => {
const root = await createTestTempDirectory("rea-analysis-view-cli-bad-");
const result = await cli.run({
@@ -80,3 +124,48 @@ cliTest("rejects a request that omits source", async ({ cli }) => {
details: { operation: "inspect-analysis-view" },
});
});
for (const [view, reason] of [
[{ kind: "unknown-view" }, "invalid_value"],
[{}, "missing_argument"],
] as const) {
cliTest(
`reports correction details for ${reason} view kind`,
async ({ cli }) => {
const root = await createTestTempDirectory("rea-view-variant-");
const input = join(root, "view.json");
await writeFile(
input,
JSON.stringify({
source: {
kind: "inline",
evidence: analysisViewLayoutEvidence(),
},
view,
}),
);
const result = await cli.run({
arguments: ["inspect-analysis-view", input, "--json"],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: {
issues: [
{
path: ["view", "kind"],
reason,
expected: expect.arrayContaining(["summary", "page"]),
},
],
},
});
expect(JSON.stringify(result.json)).not.toContain("unknown-view");
},
);
}
@@ -0,0 +1,76 @@
import { execFile } from "node:child_process";
import { mkdir } 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);
const MARKER = "REA_TEST_RESOLVED ";
// Dependencies that only one command uses; startup must not resolve them.
const DEFERRED_PACKAGES = ["playwright-core", "isomorphic-git"] as const;
// Report each resolved deferred package on stderr without changing resolution.
const RESOLUTION_HOOK = `data:text/javascript,${encodeURIComponent(`
import { registerHooks } from "node:module";
const packages = ${JSON.stringify(DEFERRED_PACKAGES)};
registerHooks({
resolve(specifier, context, next) {
const resolved = next(specifier, context);
const name = packages.find((item) =>
resolved.url.includes("/node_modules/" + item + "/"),
);
if (name !== undefined)
process.stderr.write(${JSON.stringify(MARKER)} + name + "\\n");
return resolved;
},
});
`)}`;
const resolvedPackages = async (
arguments_: readonly string[],
): Promise<ReadonlySet<string>> => {
const { stderr } = await execute(
process.execPath,
[`--import=${RESOLUTION_HOOK}`, ...arguments_],
{ cwd: process.cwd(), maxBuffer: 16 * 1_024 * 1_024 },
);
return new Set(
stderr
.split("\n")
.filter((line) => line.startsWith(MARKER))
.map((line) => line.slice(MARKER.length)),
);
};
const evaluate = (source: string): readonly string[] => [
"--input-type=module",
"--eval",
source,
];
describe("CLI startup imports", () => {
it("detects each deferred package when its command code loads", async () => {
await expect(
resolvedPackages(
evaluate('await import("./dist/composition/browserScenario.js");'),
),
).resolves.toContain("playwright-core");
const source = await createTestTempDirectory("rea-startup-imports-");
await mkdir(join(source, ".git"));
await expect(
resolvedPackages(
evaluate(
`const { readReferenceSourceVcs } = await import("./dist/application/ReferenceSourceVcsAdapter.js"); await readReferenceSourceVcs(${JSON.stringify(source)});`,
),
),
).resolves.toContain("isomorphic-git");
});
it("does not load command-specific packages to register commands", async () => {
await expect(
resolvedPackages(["scripts/rea.mjs", "--help"]),
).resolves.toEqual(new Set());
});
});
+786
View File
@@ -0,0 +1,786 @@
import { access, mkdir, readFile, writeFile, rm } from "node:fs/promises";
import { dirname, join } from "node:path";
import { expect } from "vitest";
import { parse } from "jsonc-parser";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const cases = [
{
client: "gemini_cli",
env: { GEMINI_CLI_HOME: "profile" },
config: "profile/.gemini/settings.json",
skill: "profile/.agents/skills",
},
{
client: "opencode",
env: { OPENCODE_CONFIG_DIR: "profile" },
config: "profile/opencode.json",
skill: ".agents/skills",
},
{
client: "opencode",
env: { OPENCODE_CONFIG_DIR: "" },
config: ".config/opencode/opencode.json",
skill: ".agents/skills",
},
{
client: "codex",
env: { CODEX_HOME: "" },
config: ".codex/config.toml",
skill: ".agents/skills",
},
{
client: "grok_build",
env: { GROK_HOME: "" },
config: ".grok/config.toml",
skill: ".agents/skills",
},
{
client: "omp",
env: { PI_CODING_AGENT_DIR: "profile" },
config: "profile/mcp.json",
skill: ".agents/skills",
},
{
client: "devin",
env: { XDG_CONFIG_HOME: "profile" },
config: "profile/devin/mcp_config.json",
skill: ".agents/skills",
},
{
client: "antigravity",
env: {},
config: ".gemini/config/mcp_config.json",
skill: ".gemini/config/skills",
},
];
for (const testCase of cases.filter(
({ client }) => process.platform !== "win32" || client !== "devin",
)) {
cliTest(
`${testCase.client} lifecycle follows the selected roots (${testCase.config})`,
async ({ cli }) => {
const home = await createTestTempDirectory("rea-client-profile-");
const environment: NodeJS.ProcessEnv = { HOME: home, USERPROFILE: home };
for (const [key, value] of Object.entries(testCase.env))
environment[key] = value === "profile" ? join(home, value) : value;
// OMP's relative override is relative to the caller, not silently ignored.
if (testCase.client === "omp")
environment.PI_CODING_AGENT_DIR = "profile";
const config = join(home, testCase.config);
const skillDirectory = join(
home,
testCase.skill,
"reverse-engineer-anything",
);
const run = (arguments_: readonly string[]) =>
cli.run({
arguments: arguments_,
cwd: home,
environment,
timeoutMs: 20_000,
});
const planned = await run([
"setup",
"--client",
testCase.client,
"--dry-run",
"--json",
]);
expect(planned.exitCode).toBe(0);
expect(planned.json).toMatchObject({
status: "planned",
plannedActions: expect.arrayContaining([
expect.objectContaining({ target: config }),
expect.objectContaining({ target: skillDirectory }),
]),
});
await expect(access(config)).rejects.toMatchObject({ code: "ENOENT" });
const setup = await run([
"setup",
"--client",
testCase.client,
"--yes",
"--json",
]);
expect(setup.exitCode).toBe(0);
expect(setup.json).toMatchObject({ status: "ready" });
await expect(access(config)).resolves.toBeUndefined();
expect(
await readFile(join(skillDirectory, "SKILL.md"), "utf8"),
).toContain("reverse-engineer-anything");
await expect(access(join(home, "config.toml"))).rejects.toMatchObject({
code: "ENOENT",
});
const doctor = await run([
"doctor",
"--client",
testCase.client,
"--skill",
"--json",
]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({
healthy: true,
identity: { skill: { state: "aligned" } },
});
if (testCase.client === "grok_build") {
const original = await readFile(config, "utf8");
await writeFile(
config,
original.replace(
"[mcp_servers.rea]",
"[mcp_servers.rea]\ndisabled = true",
),
);
expect(
(await run(["doctor", "--client", "grok_build", "--json"])).exitCode,
).toBe(0);
await writeFile(config, original);
}
const repeat = await run([
"setup",
"--client",
testCase.client,
"--yes",
"--json",
]);
expect(repeat.json).toMatchObject({
status: "ready",
appliedActions: [],
});
const uninstall = await run(["uninstall", "--json"]);
expect(uninstall.exitCode).toBe(0);
expect(uninstall.json).toMatchObject({ status: "complete" });
await expect(
access(join(skillDirectory, "SKILL.md")),
).rejects.toMatchObject({ code: "ENOENT" });
},
);
}
for (const policy of [{ excluded: ["rea"] }, { allowed: ["other"] }]) {
cliTest(
`Gemini refuses a registration blocked by ${Object.keys(policy)[0]}`,
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-policy-");
const config = join(home, ".gemini/settings.json");
const original = JSON.stringify({
mcp: policy,
mcpServers: {
rea: {
command: "npx",
args: ["-y", PRODUCT_IDENTITY.registrationPackageSpecifier, "mcp"],
},
},
});
await mkdir(dirname(config), { recursive: true });
await writeFile(config, original);
const run = (arguments_: readonly string[]) =>
cli.run({
arguments: arguments_,
cwd: home,
environment: { HOME: home, USERPROFILE: home },
timeoutMs: 20_000,
});
const setup = await run([
"setup",
"--client",
"gemini_cli",
"--yes",
"--json",
]);
expect(setup.exitCode).toBe(1);
expect(setup.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining("mcp." + Object.keys(policy)[0]),
});
expect(await readFile(config, "utf8")).toBe(original);
await expect(access(config + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
const doctor = await run(["doctor", "--client", "gemini_cli", "--json"]);
expect(doctor.exitCode).toBe(1);
expect(doctor.json).toMatchObject({
healthy: false,
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client: "gemini_cli",
state: "stale",
remediation: expect.stringContaining("mcp."),
}),
]),
},
});
},
);
}
cliTest(
"OpenCode diagnoses merged JSON/JSONC and removes owned entries from both files",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-opencode-layers-");
const directory = join(home, ".config/opencode");
await mkdir(directory, { recursive: true });
const lower = join(directory, "opencode.json");
const higher = join(directory, "opencode.jsonc");
const originalLower = JSON.stringify({
mcp: {
rea: {
type: "local",
command: [
"npx",
"-y",
PRODUCT_IDENTITY.registrationPackageSpecifier,
"mcp",
],
enabled: true,
},
other: { type: "local", command: ["other"] },
},
});
const originalHigher =
'// keep this comment\n{"mcp":{"rea":{"enabled":false}},"theme":"system"}\n';
await writeFile(lower, originalLower);
await writeFile(higher, originalHigher);
const run = (arguments_: readonly string[]) =>
cli.run({
arguments: arguments_,
cwd: home,
environment: { HOME: home, USERPROFILE: home },
timeoutMs: 20_000,
});
const before = await run(["doctor", "--client", "opencode", "--json"]);
expect(before.exitCode).toBe(1);
expect(before.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "opencode", state: "stale" }),
]),
},
});
const setup = await run([
"setup",
"--client",
"opencode",
"--yes",
"--json",
]);
expect(setup.exitCode).toBe(0);
expect(setup.json).toMatchObject({ status: "ready" });
expect(await readFile(lower, "utf8")).toBe(originalLower);
expect(await readFile(higher + ".rea.backup", "utf8")).toBe(originalHigher);
expect(await readFile(higher, "utf8")).toContain("// keep this comment");
expect(
(await run(["doctor", "--client", "opencode", "--json"])).exitCode,
).toBe(0);
const uninstall = await run(["uninstall", "--json"]);
expect(uninstall.exitCode).toBe(0);
const report = uninstall.json as {
items?: readonly { name: string; status: string }[];
};
const opencodeItems = report.items?.filter(
({ name }) => name === "opencode",
);
expect(opencodeItems).toEqual([
expect.objectContaining({ status: "removed" }),
]);
expect(parse(await readFile(lower, "utf8"))).toEqual({
mcp: { other: { type: "local", command: ["other"] } },
});
expect(parse(await readFile(higher, "utf8"))).toEqual({
mcp: {},
theme: "system",
});
},
);
cliTest(
"malformed lower-priority OpenCode config blocks setup before any writes",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-opencode-invalid-layer-");
const directory = join(home, ".config/opencode");
await mkdir(directory, { recursive: true });
const lower = join(directory, "opencode.json");
const higher = join(directory, "opencode.jsonc");
await writeFile(lower, "malformed");
await writeFile(higher, "{}");
const result = await cli.run({
arguments: ["setup", "--client", "opencode", "--yes", "--json"],
cwd: home,
environment: { HOME: home, USERPROFILE: home },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
});
expect(await readFile(lower, "utf8")).toBe("malformed");
expect(await readFile(higher, "utf8")).toBe("{}");
await expect(access(higher + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"Gemini system policy blocks a new registration without modifying managed files",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-managed-");
const policy = join(home, "managed.json");
const original = JSON.stringify({
mcp: { excluded: ["rea"] },
unrelated: true,
});
await writeFile(policy, original);
const environment = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: policy,
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: join(home, "defaults.json"),
};
const setup = await cli.run({
arguments: ["setup", "--client", "gemini_cli", "--yes", "--json"],
cwd: home,
environment,
});
expect(setup.exitCode).toBe(1);
expect(setup.json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining("mcp.excluded"),
});
expect(await readFile(policy, "utf8")).toBe(original);
await expect(
access(join(home, ".gemini/settings.json")),
).rejects.toMatchObject({ code: "ENOENT" });
await expect(access(policy + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"Gemini intersects system/default/user allowlists and accepts an empty effective allowlist",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-allowlists-");
const system = join(home, "system.json");
const defaults = join(home, "defaults.json");
const user = join(home, ".gemini/settings.json");
await mkdir(dirname(user), { recursive: true });
await writeFile(
system,
JSON.stringify({ mcp: { allowed: ["rea", "other"] } }),
);
await writeFile(defaults, JSON.stringify({ mcp: { allowed: ["other"] } }));
await writeFile(
user,
JSON.stringify({ mcp: { allowed: ["rea", "other"] } }),
);
const environment = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: system,
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: defaults,
};
const run = () =>
cli.run({
arguments: ["setup", "--client", "gemini_cli", "--yes", "--json"],
cwd: home,
environment,
});
const blocked = await run();
expect(blocked.exitCode).toBe(1);
expect(blocked.json).toMatchObject({
status: "needs_human",
appliedActions: [],
});
await writeFile(defaults, JSON.stringify({ mcp: { allowed: ["rea"] } }));
const allowed = await run();
expect(allowed.exitCode).toBe(0);
expect(allowed.json).toMatchObject({ status: "ready" });
expect(JSON.parse(await readFile(defaults, "utf8"))).toEqual({
mcp: { allowed: ["rea"] },
});
// The consumer treats an empty consolidated allowlist as unrestricted.
await writeFile(defaults, JSON.stringify({ mcp: { allowed: [] } }));
const empty = await run();
expect(empty.exitCode).toBe(0);
expect(empty.json).toMatchObject({ status: "ready", appliedActions: [] });
},
);
cliTest(
"OpenCode doctor sees a global registration when the custom directory is absent",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-opencode-absent-custom-");
const global = join(home, ".config/opencode/opencode.json");
const custom = join(home, "missing-custom");
await mkdir(dirname(global), { recursive: true });
await writeFile(
global,
JSON.stringify({
mcp: {
rea: {
type: "local",
command: [
"npx",
"-y",
PRODUCT_IDENTITY.registrationPackageSpecifier,
"mcp",
],
enabled: true,
},
},
}),
);
const run = (args: readonly string[]) =>
cli.run({
arguments: args,
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
OPENCODE_CONFIG_DIR: custom,
},
});
const doctor = await run(["doctor", "--client", "opencode", "--json"]);
expect(doctor.exitCode).toBe(0);
expect(doctor.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "opencode", state: "aligned" }),
]),
},
});
const planned = await run([
"setup",
"--client",
"opencode",
"--dry-run",
"--json",
]);
expect(planned.json).toMatchObject({
clientStates: expect.arrayContaining([
expect.objectContaining({
client: expect.objectContaining({ name: "opencode" }),
detected: true,
}),
]),
});
await expect(access(custom)).rejects.toMatchObject({ code: "ENOENT" });
},
);
cliTest(
"OpenCode retains the XDG global layer when a custom directory is selected",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-opencode-global-custom-");
const global = join(home, ".config/opencode/opencode.json");
const custom = join(home, "custom/opencode.jsonc");
await mkdir(dirname(global), { recursive: true });
await mkdir(dirname(custom), { recursive: true });
const owned = {
type: "local",
command: [
"npx",
"-y",
PRODUCT_IDENTITY.registrationPackageSpecifier,
"mcp",
],
enabled: true,
};
const original = JSON.stringify({
mcp: { rea: owned, other: { type: "local", command: ["other"] } },
});
await writeFile(global, original);
await writeFile(custom, "{}");
const run = (args: readonly string[]) =>
cli.run({
arguments: args,
cwd: home,
environment: {
HOME: home,
USERPROFILE: home,
OPENCODE_CONFIG_DIR: dirname(custom),
},
});
const doctor = await run(["doctor", "--client", "opencode", "--json"]);
expect(doctor.json).toMatchObject({
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({ client: "opencode", state: "aligned" }),
]),
},
});
await writeFile(global, "malformed");
expect(
(await run(["setup", "--client", "opencode", "--yes", "--json"])).json,
).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining(global),
});
expect(await readFile(custom, "utf8")).toBe("{}");
await writeFile(global, original);
expect(
(await run(["setup", "--client", "opencode", "--yes", "--json"]))
.exitCode,
).toBe(0);
expect((await run(["uninstall", "--json"])).exitCode).toBe(0);
expect(parse(await readFile(global, "utf8"))).toEqual({
mcp: { other: { type: "local", command: ["other"] } },
});
expect(parse(await readFile(custom, "utf8"))).toEqual({ mcp: {} });
},
);
cliTest(
"Gemini blocks a conflicting system definition and accepts an identical managed entry",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-managed-server-");
const user = join(home, ".gemini/settings.json");
const system = join(home, "system.json");
const defaults = join(home, "defaults.json");
const environment = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: system,
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: defaults,
};
const run = (args: readonly string[]) =>
cli.run({ arguments: args, cwd: home, environment });
const command = ["setup", "--client", "gemini_cli", "--yes", "--json"];
// A user registration overrides a default definition, including its entire env object.
await writeFile(
defaults,
JSON.stringify({
mcpServers: {
rea: { command: "managed-default", env: { EXTRA: "default" } },
},
}),
);
expect((await run(command)).exitCode).toBe(0);
const original = await readFile(user, "utf8");
const managed = JSON.stringify({
mcpServers: { rea: { command: "managed-override", args: [] } },
unrelated: true,
});
await writeFile(system, managed);
expect((await run(command)).json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining(system),
});
expect(
(await run(["doctor", "--client", "gemini_cli", "--json"])).json,
).toMatchObject({
healthy: false,
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client: "gemini_cli",
state: "stale",
remediation: expect.stringContaining("mcpServers.rea"),
}),
]),
},
});
expect(await readFile(user, "utf8")).toBe(original);
expect(await readFile(system, "utf8")).toBe(managed);
const aligned = JSON.stringify({
mcpServers: JSON.parse(original).mcpServers,
});
await writeFile(system, aligned);
expect((await run(command)).json).toMatchObject({
status: "ready",
appliedActions: [],
});
expect(
(await run(["doctor", "--client", "gemini_cli", "--json"])).exitCode,
).toBe(0);
expect(await readFile(system, "utf8")).toBe(aligned);
await expect(access(system + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"Gemini workspace policy follows persisted trust and explicit trust overrides",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-workspace-policy-");
const project = join(home, "project");
const workspace = join(project, ".gemini/settings.json");
const trust = join(home, "trust.json");
await mkdir(dirname(workspace), { recursive: true });
const environment: NodeJS.ProcessEnv = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: join(home, "system.json"),
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: join(home, "defaults.json"),
GEMINI_CLI_TRUSTED_FOLDERS_PATH: trust,
};
const run = (args: readonly string[]) =>
cli.run({ arguments: args, cwd: project, environment });
const command = ["setup", "--client", "gemini_cli", "--yes", "--json"];
const original = JSON.stringify({
mcp: { excluded: ["rea"] },
unrelated: true,
});
await writeFile(workspace, original);
await writeFile(
trust,
JSON.stringify({ [home]: "TRUST_FOLDER", [project]: "DO_NOT_TRUST" }),
);
expect((await run(command)).exitCode).toBe(0);
await writeFile(
trust,
JSON.stringify({ [join(project, "child")]: "TRUST_PARENT" }),
);
expect((await run(command)).json).toMatchObject({
status: "needs_human",
appliedActions: [],
remediation: expect.stringContaining(workspace),
});
expect(
(await run(["doctor", "--client", "gemini_cli", "--json"])).json,
).toMatchObject({
healthy: false,
identity: {
registrations: expect.arrayContaining([
expect.objectContaining({
client: "gemini_cli",
state: "stale",
remediation: expect.stringContaining("mcp.excluded"),
}),
]),
},
});
environment.GEMINI_CLI_TRUST_WORKSPACE = "false";
expect((await run(command)).json).toMatchObject({
status: "ready",
appliedActions: [],
});
environment.GEMINI_CLI_TRUST_WORKSPACE = "true";
await writeFile(workspace, JSON.stringify({ mcp: { allowed: ["other"] } }));
expect((await run(command)).json).toMatchObject({
status: "needs_human",
remediation: expect.stringContaining("mcp.allowed"),
});
// Restricted mode takes precedence over an explicit trust opt-in.
environment.GEMINI_RESTRICTED_MODE = "true";
expect((await run(command)).json).toMatchObject({
status: "ready",
appliedActions: [],
});
expect(JSON.parse(await readFile(workspace, "utf8"))).toEqual({
mcp: { allowed: ["other"] },
});
await expect(access(workspace + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"Gemini workspace definitions use shallow precedence and remain read-only",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-workspace-server-");
const project = join(home, "project");
const workspace = join(project, ".gemini/settings.json");
const system = join(home, "system.json");
await mkdir(dirname(workspace), { recursive: true });
const environment: NodeJS.ProcessEnv = {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: system,
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: join(home, "defaults.json"),
GEMINI_CLI_TRUST_WORKSPACE: "true",
};
const run = (args: readonly string[]) =>
cli.run({ arguments: args, cwd: project, environment });
const command = ["setup", "--client", "gemini_cli", "--yes", "--json"];
const original = JSON.stringify({
mcpServers: { rea: { command: "project-server", args: [] } },
});
await writeFile(workspace, original);
expect((await run(command)).json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining(workspace),
});
await expect(
access(join(home, ".gemini/settings.json")),
).rejects.toMatchObject({ code: "ENOENT" });
// Obtain this setup invocation's actual command while workspace settings are untrusted.
environment.GEMINI_CLI_TRUST_WORKSPACE = "false";
expect((await run(command)).exitCode).toBe(0);
const user = JSON.parse(
await readFile(join(home, ".gemini/settings.json"), "utf8"),
);
environment.GEMINI_CLI_TRUST_WORKSPACE = "true";
// System's entire entry wins over the workspace entry.
await writeFile(system, JSON.stringify({ mcpServers: user.mcpServers }));
expect((await run(command)).exitCode).toBe(0);
expect(
(await run(["doctor", "--client", "gemini_cli", "--json"])).exitCode,
).toBe(0);
expect(await readFile(workspace, "utf8")).toBe(original);
await expect(access(workspace + ".rea.backup")).rejects.toMatchObject({
code: "ENOENT",
});
},
);
cliTest(
"Gemini validates trust configuration and honors a disabled folder trust feature",
async ({ cli }) => {
const home = await createTestTempDirectory("rea-gemini-trust-invalid-");
const project = join(home, "project");
const workspace = join(project, ".gemini/settings.json");
const user = join(home, ".gemini/settings.json");
const trust = join(home, ".gemini/trustedFolders.json");
await mkdir(dirname(workspace), { recursive: true });
await mkdir(dirname(user), { recursive: true });
await writeFile(workspace, JSON.stringify({ mcp: { excluded: ["rea"] } }));
await writeFile(trust, JSON.stringify({ [project]: "INVALID" }));
const run = () =>
cli.run({
arguments: ["setup", "--client", "gemini_cli", "--yes", "--json"],
cwd: project,
environment: {
HOME: home,
USERPROFILE: home,
GEMINI_CLI_SYSTEM_SETTINGS_PATH: join(home, "system.json"),
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: join(home, "defaults.json"),
},
});
expect((await run()).json).toMatchObject({
status: "needs_human",
plannedActions: [],
appliedActions: [],
remediation: expect.stringContaining(trust),
});
await expect(access(user)).rejects.toMatchObject({ code: "ENOENT" });
await rm(trust);
await writeFile(
user,
JSON.stringify({ security: { folderTrust: { enabled: false } } }),
);
expect((await run()).json).toMatchObject({
status: "needs_human",
remediation: expect.stringContaining("mcp.excluded"),
});
},
);
+15
View File
@@ -16,6 +16,7 @@ import { silentLogger } from "../../../src/logger.js";
const collect = async (
value: unknown,
format: "json" | "jsonl" = "json",
terminal = true,
): Promise<string> => {
const chunks: Buffer[] = [];
const destination = new Writable({
@@ -28,6 +29,7 @@ const collect = async (
callback();
},
});
if (terminal) Object.defineProperty(destination, "isTTY", { value: true });
await writeJsonOutput(value, destination, format);
return Buffer.concat(chunks).toString("utf8");
};
@@ -52,6 +54,16 @@ describe("incremental CLI JSON", () => {
expect(await collect(value)).toBe(`${JSON.stringify(value, null, 2)}\n`);
});
it("indents JSON only for a terminal and writes piped JSON compactly", async () => {
const value = { nested: [{ value: null }], text: "雪𝟠" };
expect(await collect(value, "json", true)).toBe(
`${JSON.stringify(value, null, 2)}\n`,
);
expect(await collect(value, "json", false)).toBe(
`${JSON.stringify(value)}\n`,
);
});
it("writes compact JSONL records and preserves an empty record set", async () => {
const value = [{ text: "first\nrecord" }, { text: "雪𝟠" }];
expect(await collect(value, "jsonl")).toBe(
@@ -78,6 +90,7 @@ describe("incremental CLI JSON", () => {
}, 1);
},
});
Object.defineProperty(destination, "isTTY", { value: true });
await writeJsonOutput({ leaf }, destination);
expect(largestChunk).toBeLessThan(Buffer.byteLength(leaf));
const actual = Buffer.concat(chunks).toString("utf8");
@@ -212,6 +225,8 @@ describe("streamed CLI result surface", () => {
expect(operation).toBe("inspect_managed_members");
return value;
});
// A terminal destination exercises the indented encoding past the limit.
Object.defineProperty(destination, "isTTY", { value: true });
const argv = ["inspect-managed-members", "fixture.dll", "--json"];
const output = createStreamedCliJsonOutput(argv, destination);
if (output === undefined) throw new Error("Missing JSON output surface");
@@ -50,10 +50,9 @@ describe("artifact inventory entry order", () => {
const parent = artifactOccurrenceAt(observed, parentPath);
expect(observed.edges).toContainEqual(
expect.objectContaining({
logical_path: path,
occurrence_id: occurrence.occurrence_id,
relation: "contains",
parent_artifact_id: parent.artifact_id,
child_artifact_id: occurrence.artifact_id,
}),
);
}
@@ -100,7 +99,6 @@ describe("entry-order validation and reader controls", () => {
it.each([
["pkg/data.txt", "pkg/data.txt/"],
["pkg/data.txt/", "pkg/data.txt"],
["pkg/data.txt", "PKG/other.txt"],
["pkg/data.txt", "pkg"],
["../escape.txt"],
])("keeps invalid/colliding paths rejected for %j", async (...entries) => {
@@ -112,6 +110,25 @@ describe("entry-order validation and reader controls", () => {
});
});
it("keeps case-distinct directory names separate in either entry order", async () => {
const root = await createTestTempDirectory("rea-entry-order-case-");
const archive = join(root, "case-distinct.zip");
const entries = ["pkg/", "pkg/data.txt", "PKG/", "PKG/other.txt"];
const parents = {
".": null,
pkg: ".",
"pkg/data.txt": "pkg",
PKG: ".",
"PKG/other.txt": "PKG",
};
for (const ordered of [entries, entries.toReversed()]) {
await writeOrderedZip(archive, ordered);
expect(artifactParentPaths(await inventoryArtifact(archive))).toEqual(
parents,
);
}
});
it("preserves ordinary directory and ASAR structure", async () => {
const root = await createTestTempDirectory("rea-entry-order-readers-");
const directory = join(root, "source");
@@ -75,10 +75,9 @@ describe("expanded ASAR inventory containment", () => {
const child = artifactOccurrenceAt(nested, path);
expect(nested.edges).toContainEqual(
expect.objectContaining({
logical_path: path,
occurrence_id: child.occurrence_id,
relation: "contains",
parent_artifact_id: artifactOccurrenceAt(nested, parent).artifact_id,
child_artifact_id: child.artifact_id,
}),
);
if (path.startsWith("resources/app.asar/"))
@@ -9,6 +9,7 @@ import { createCli } from "../../../src/cli.js";
import { parseCliJsonInput } from "../../../src/cliJsonInput.js";
import { readCliJsonFile } from "../../../src/cliJsonFile.js";
import { analysisCliErrorEnvelopeSchema } from "../../../src/contracts/errorSchemas.js";
import { JSON_BYTE_ORDER_MARK_MESSAGE } from "../../../src/application/Utf8JsonInput.js";
import { readWithoutFifoWriter } from "../../fixtures/fifoInput.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -160,6 +161,21 @@ describe("CLI JSON streamed input", () => {
}
});
it("names a leading byte-order mark in small and streamed files", async () => {
const root = await createTestTempDirectory("rea-json-input-bom-");
const path = join(root, "input.json");
for (const body of ["{}", `${" ".repeat(9 * 1024 * 1024)}{}`]) {
await writeFile(path, `\uFEFF${body}`);
expect(await parseCliJsonInput(path, "test-input")).toMatchObject({
ok: false,
error: {
input_reason: "invalid-json",
details: { issues: [{ message: JSON_BYTE_ORDER_MARK_MESSAGE }] },
},
});
}
});
it.each([Buffer.from([0xf0, 0x28, 0x8c, 0xbc]), Buffer.from([0xe2, 0x82])])(
"rejects malformed and incomplete UTF-8 at a read boundary (%j)",
async (invalid) => {
@@ -32,6 +32,7 @@ const getClients = (home: string) =>
"vscode",
"devin",
"omp",
"pi",
].includes(name),
);
@@ -44,6 +45,7 @@ describe("additional client configuration dialects", () => {
"vscode",
"devin",
"omp",
"pi",
] as const)("registers, reads back, and uninstalls %s", async (name) => {
const home = await createTestTempDirectory("rea-client-dialect-");
const client = getClients(home).find(
@@ -78,7 +80,7 @@ describe("additional client configuration dialects", () => {
command,
enabled: true,
});
if (name === "vscode" || name === "omp")
if (name === "vscode" || name === "omp" || name === "pi")
expect(registration).toMatchObject({
type: "stdio",
command: "npx",
@@ -59,9 +59,12 @@ describe("client configuration filesystem lifecycle", () => {
"antigravity",
"copilot_cli",
"commandcode",
"qwen_code",
"vscode",
"grok_build",
"omp",
"pi",
"hermes",
"grok_bot",
]);
expect(
@@ -169,7 +169,7 @@ const createBuildCacheFixture = async (): Promise<string> => {
"scripts/clean-build-output.mjs",
"scripts/generate-package-metadata.mjs",
"scripts/lib/generated-file.mjs",
"skill-src/reverse-engineer-anything/SKILL.md",
".agents/skills/reverse-engineer-anything/SKILL.md",
"src/generatedPackageMetadata.ts",
];
await Promise.all(
@@ -21,7 +21,7 @@ async function fixture(eol = "\n") {
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 sourceRoot = join(root, ".agents/skills/reverse-engineer-anything");
const outputRoot = join(root, "skills/reverse-engineer-anything");
await mkdir(join(sourceRoot, "references"), { recursive: true });
await mkdir(join(root, "dist"));
@@ -0,0 +1,165 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { parse as parseYaml } from "yaml";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { npxRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { clearClientLocationEnvironment } from "../../fixtures/clientEnvironment.js";
/**
* The registration command setup writes on the host running the tests. Windows
* wraps it in `cmd.exe /d /c`, so the expected entry follows the host too.
*/
const command = npxRegistrationCommand(process.platform);
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const hermesPath = (
env: Parameters<typeof supportedClients>[2],
platform: NodeJS.Platform = "linux",
) =>
supportedClients(join("/home/a"), platform, env).find(
({ name }) => name === "hermes",
);
describe("Hermes configuration paths", () => {
it("resolves config.yaml under the platform Hermes home", () => {
expect(hermesPath({})).toEqual({
name: "hermes",
displayName: "Hermes",
configPath: join("/home/a", ".hermes", "config.yaml"),
markerPath: join("/home/a", ".hermes"),
format: "hermes",
});
// Windows uses the native data directory, matching Hermes's own resolver.
expect(
hermesPath({ LOCALAPPDATA: "C:\\Users\\a\\AppData\\Local" }, "win32")
?.configPath,
).toBe(join("C:\\Users\\a\\AppData\\Local", "hermes", "config.yaml"));
});
it("expands and trims Hermes overrides without changing the suffix", () => {
expect(hermesPath({ HERMES_HOME: " ~/profile " })?.markerPath).toBe(
join("/home/a", "profile"),
);
expect(
hermesPath({
HERMES_HOME: "${PROFILE_ROOT}/agent",
PROFILE_ROOT: "/custom",
})?.markerPath,
).toBe(join("/custom", "agent"));
expect(
hermesPath({
HERMES_HOME: "$PROFILE_ROOT/agent",
PROFILE_ROOT: "/custom",
})?.markerPath,
).toBe(join("/custom", "agent"));
expect(hermesPath({ LOCALAPPDATA: " " }, "win32")?.markerPath).toBe(
join("/home/a", "AppData", "Local", "hermes"),
);
});
it("honours HERMES_HOME and Hermes's data-directory suffix", () => {
expect(
hermesPath({ HERMES_HOME: join("/srv", "hermes") })?.configPath,
).toBe(join("/srv", "hermes", "config.yaml"));
// A blank override falls through to the platform default.
expect(hermesPath({ HERMES_HOME: " " })?.configPath).toBe(
join("/home/a", ".hermes", "config.yaml"),
);
// Hermes appends the suffix to the literal directory name.
expect(hermesPath({ HERMES_DATA_DIR_SUFFIX: "-dev" })?.configPath).toBe(
join("/home/a", ".hermes-dev", "config.yaml"),
);
expect(
hermesPath(
{
HERMES_DATA_DIR_SUFFIX: "-dev",
LOCALAPPDATA: "C:\\Users\\a\\AppData\\Local",
},
"win32",
)?.configPath,
).toBe(join("C:\\Users\\a\\AppData\\Local", "hermes-dev", "config.yaml"));
});
});
describe("Hermes YAML registration", () => {
const hermesClient = async () => {
const home = await createTestTempDirectory("rea-hermes-");
const client = supportedClients(home, process.platform, {}).find(
({ name }) => name === "hermes",
);
if (client?.markerPath === undefined)
throw new Error("missing Hermes client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("writes mcp_servers, preserves comments, reads back, and uninstalls", async () => {
const { home, client } = await hermesClient();
await writeFile(
client.configPath,
`# Hermes configuration
display:
language: en
mcp_servers:
# An independently managed server.
other:
command: other-server
`,
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const text = await readFile(client.configPath, "utf8");
expect(text).toContain("# Hermes configuration");
expect(text).toContain("# An independently managed server.");
expect(parseYaml(text)).toEqual({
display: { language: "en" },
mcp_servers: {
other: { command: "other-server" },
rea: { command: command[0], args: command.slice(1), enabled: true },
},
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect(
(
await readClientRegistrationStatuses(home, undefined, {
platform: process.platform,
environment: {},
})
).find(({ client: name }) => name === "hermes"),
).toMatchObject({ state: "aligned", command });
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual({
display: { language: "en" },
mcp_servers: { other: { command: "other-server" } },
});
});
it("creates config.yaml when Hermes has no configuration yet", async () => {
const { client } = await hermesClient();
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
expect(parseYaml(await readFile(client.configPath, "utf8"))).toEqual({
mcp_servers: {
rea: { command: command[0], args: command.slice(1), enabled: true },
},
});
});
});
@@ -0,0 +1,44 @@
import { execFile } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("analyzes direct returns after deep source without exhausting the default process stack", async () => {
const root = await createTestTempDirectory("rea-deep-direct-returns-");
await writeFile(
join(root, "app.js"),
`export function render() { object${".property".repeat(20_000)}; function nested() { return "nested"; } class Inner { method() { return "method"; } } return "ready"; }`,
);
const service = new URL(
"../../../dist/application/javascript/JavaScriptApplicationService.js",
import.meta.url,
).href;
const script = `
import { analyzeJavaScriptApplication } from ${JSON.stringify(service)};
const result = await analyzeJavaScriptApplication({ input_path: ${JSON.stringify(root)}, format: "directory" });
if (!result.ok) throw result.error;
const nodes = result.value.normalized_result.semantic_graph.nodes;
console.log(JSON.stringify(nodes.filter(node => node.kind === "return-site").map(node => node.function_node_id)));
`;
const { stdout, stderr } = await promisify(execFile)(
process.execPath,
["--input-type=module", "-e", script],
{
timeout: 10_000,
// Bound the child heap while retaining Node's default stack size.
env: {
HOME: root,
TMPDIR: root,
NODE_OPTIONS: "--max-old-space-size=768",
},
},
);
expect(stderr).toBe("");
const owners: unknown = JSON.parse(stdout);
expect(owners).toHaveLength(3);
expect(new Set(Array.isArray(owners) ? owners : []).size).toBe(3);
});
@@ -38,9 +38,9 @@ describe("OMP configuration paths", () => {
expect(ompPath({ PI_CODING_AGENT_DIR: "/custom/agent" })?.configPath).toBe(
"/custom/agent/mcp.json",
);
// A relative override names a different file in every working directory.
// Match OMP by resolving the override against the caller working directory.
expect(ompPath({ PI_CODING_AGENT_DIR: "agent" })?.configPath).toBe(
"/home/a/.omp/agent/mcp.json",
resolve("agent", "mcp.json"),
);
});
@@ -0,0 +1,333 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { parseClientConfiguration } from "../../../src/application/ClientConfigurationDocument.js";
import {
configureClientConfiguration,
inspectClientConfiguration,
} from "../../../src/application/SetupClientConfiguration.js";
import { detectClients } from "../../../src/application/SetupHost.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
clearClientLocationEnvironment,
NPX_REGISTRATION_COMMAND,
} from "../../fixtures/clientEnvironment.js";
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const piPath = (
home: string,
platform: NodeJS.Platform,
env: Parameters<typeof supportedClients>[2],
) => supportedClients(home, platform, env).find(({ name }) => name === "pi");
// Catch fallback to OMP paths, loss of relative overrides, and normalization
// that differs from Pi's public getAgentDir()/normalizePath boundary.
describe("Pi user configuration paths", () => {
it.each([
[undefined, "/home/a/.pi/agent"],
["", "/home/a/.pi/agent"],
["/custom/agent", "/custom/agent"],
["~", "/home/a"],
["~/custom/agent", "/home/a/custom/agent"],
["agent", "agent"],
["./agent", "./agent"],
[" agent ", " agent "],
["~other/agent", "~other/agent"],
["file:///custom/agent%20dir", "/custom/agent dir"],
["/mnt/c/agent", "/mnt/c/agent"],
])(
"uses Pi's agent directory for %s, independently of OMP",
(override, expected) => {
const client = piPath("/home/a", "linux", {
PI_CODING_AGENT_DIR: override,
OMP_PROFILE: "work",
PI_PROFILE: "legacy",
PI_CONFIG_DIR: ".omp-other",
});
expect(client?.markerPath).toBe(expected);
expect(client?.configPath).toBe(join(expected, "mcp.json"));
},
);
it.each([
[undefined, "C:\\Users\\a\\.pi\\agent"],
["", "C:\\Users\\a\\.pi\\agent"],
["~", "C:\\Users\\a"],
["~/agent", "C:\\Users\\a\\agent"],
["~\\agent", "C:\\Users\\a\\agent"],
["C:\\custom\\agent", "C:\\custom\\agent"],
["/c/custom/agent", "C:\\custom\\agent"],
["/mnt/c/custom/agent", "C:\\custom\\agent"],
["/cygdrive/c/custom/agent", "C:\\custom\\agent"],
["/c", "C:\\"],
["//server/share/agent", "//server/share/agent"],
["\\\\server\\share\\agent", "\\\\server\\share\\agent"],
["agent", "agent"],
["file:///C:/custom/agent%20dir", "C:\\custom\\agent dir"],
["file://server/share/agent", "\\\\server\\share\\agent"],
])("normalizes Windows Pi override %s", (override, expected) => {
const client = piPath("C:\\Users\\a", "win32", {
PI_CODING_AGENT_DIR: override,
});
expect(client?.markerPath).toBe(expected);
expect(client?.configPath).toBe(
`${expected.replace(/[\\/]+$/u, "").replaceAll("/", "\\")}\\mcp.json`,
);
});
it("reports malformed file URLs instead of silently choosing the default", async () => {
const home = await createTestTempDirectory("rea-pi-invalid-path-");
const client = piPath(home, "linux", {
PI_CODING_AGENT_DIR: "file:///agent%2fdir",
});
expect(client).toMatchObject({
configPath: "file:///agent%2fdir",
configPathError: expect.stringContaining("PI_CODING_AGENT_DIR"),
});
if (client === undefined) throw new Error("missing Pi client");
expect(await configureClientConfiguration(client)).toEqual({
status: "failed",
reason: "path",
});
expect(await systemUninstallHost(home).removeClient(client)).toMatchObject({
status: "failed",
detail: expect.stringContaining("PI_CODING_AGENT_DIR"),
});
expect(
await detectClients(home, "linux", {
PI_CODING_AGENT_DIR: "file:///agent%2fdir",
}),
).toEqual([]);
});
it("detects the normalized override marker without needing mcp.json", async () => {
const home = await createTestTempDirectory("rea-pi-detection-");
await mkdir(join(home, "custom-agent"));
const detected = await detectClients(home, process.platform, {
PI_CODING_AGENT_DIR: "~/custom-agent",
});
expect(detected.find(({ name }) => name === "pi")?.configPath).toBe(
join(home, "custom-agent", "mcp.json"),
);
});
});
const piClient = async () => {
const home = await createTestTempDirectory("rea-pi-config-");
const client = piPath(home, process.platform, {});
if (client?.markerPath === undefined) throw new Error("missing Pi client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
describe("Pi registration semantics", () => {
it("preserves unrelated content and OMP-only lists during setup, repeat, and uninstall", async () => {
const { home, client } = await piClient();
// Pi loads mcp.json with strict JSON, so the retained unrelated settings
// are valid strict JSON rather than the commented JSONC fixture.
const original = `{"autoEnableCodemode": false,
"mcpServers": { "other": { "command": "other-server" } },
"enabledServers": ["other"],
"disabledServers": ["rea", "other"]
}\n`;
await writeFile(client.configPath, original);
expect(
await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toMatchObject({ status: "configured" });
expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
original,
);
const configured = await readFile(client.configPath, "utf8");
expect(JSON.parse(configured)).toEqual({
autoEnableCodemode: false,
mcpServers: {
other: { command: "other-server" },
rea: {
type: "stdio",
command: "npx",
args: NPX_REGISTRATION_COMMAND.slice(1),
},
},
enabledServers: ["other"],
disabledServers: ["rea", "other"],
});
expect(
await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toEqual({ status: "unchanged" });
expect(await readFile(client.configPath, "utf8")).toBe(configured);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "pi"),
).toMatchObject({ state: "aligned" });
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
expect(JSON.parse(await readFile(client.configPath, "utf8"))).toEqual(
JSON.parse(original),
);
expect(await readFile(`${client.configPath}.rea.backup`, "utf8")).toBe(
original,
);
});
it.each([
[undefined, true, "aligned"],
["stdio", true, "aligned"],
["http", true, "invalid"],
["streamable-http", true, "invalid"],
["sse", true, "invalid"],
[undefined, false, "stale"],
["stdio", false, "stale"],
])(
"doctor handles type %s and enabled %s without OMP allowlist overrides",
async (type, enabled, state) => {
const { home, client } = await piClient();
await writeFile(
client.configPath,
JSON.stringify({
mcpServers: {
rea: {
command: "npx",
args: NPX_REGISTRATION_COMMAND.slice(1),
type,
enabled,
},
},
enabledServers: ["rea"],
}),
);
const statuses = await readClientRegistrationStatuses(home, undefined, {
environment: {},
});
expect(statuses.find(({ client: name }) => name === "pi")).toMatchObject({
state,
});
},
);
});
describe("Pi strict JSON parsing", () => {
it.each([
[
"a comment",
`{ // Pi loads strict JSON only\n"mcpServers": { "other": { "command": "other" } }\n}\n`,
],
[
"a trailing comma",
`{"mcpServers": { "other": { "command": "other" }, },}\n`,
],
[
"a BOM before valid JSON",
`\uFEFF{"mcpServers": { "other": { "command": "other" } }}\n`,
],
["empty text", ""],
["whitespace only", "\n \t\r\n"],
["a BOM only", "\uFEFF"],
])(
"rejects an existing Pi configuration with %s before any mutation",
async (_description, original) => {
const { home, client } = await piClient();
await writeFile(client.configPath, original);
expect(() => parseClientConfiguration(original, "pi")).toThrow();
expect(
await inspectClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toMatchObject({ status: "invalid" });
expect(
await configureClientConfiguration(
client,
{},
NPX_REGISTRATION_COMMAND,
),
).toEqual({ status: "failed", reason: "readback" });
expect(await readFile(client.configPath, "utf8")).toBe(original);
await expect(
readFile(`${client.configPath}.rea.backup`),
).rejects.toMatchObject({ code: "ENOENT" });
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "pi"),
).toMatchObject({ state: "invalid" });
expect(
await systemUninstallHost(home).removeClient(client),
).toMatchObject({
name: "pi",
status: "failed",
detail: expect.stringContaining("not valid JSON"),
});
expect(await readFile(client.configPath, "utf8")).toBe(original);
await expect(
readFile(`${client.configPath}.rea.backup`),
).rejects.toMatchObject({ code: "ENOENT" });
},
);
it("initializes a missing Pi configuration as valid strict JSON without a backup", async () => {
const { home, client } = await piClient();
await expect(readFile(client.configPath)).rejects.toMatchObject({
code: "ENOENT",
});
expect(
await inspectClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toEqual({ status: "create" });
expect(
await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toMatchObject({ status: "configured" });
const created = await readFile(client.configPath, "utf8");
expect(() => JSON.parse(created)).not.toThrow();
expect(JSON.parse(created)).toEqual({
mcpServers: {
rea: {
type: "stdio",
command: "npx",
args: NPX_REGISTRATION_COMMAND.slice(1),
},
},
});
await expect(
readFile(`${client.configPath}.rea.backup`),
).rejects.toMatchObject({ code: "ENOENT" });
expect(
await configureClientConfiguration(client, {}, NPX_REGISTRATION_COMMAND),
).toEqual({ status: "unchanged" });
expect(await readFile(client.configPath, "utf8")).toBe(created);
expect(
(
await readClientRegistrationStatuses(home, undefined, {
environment: {},
})
).find(({ client: name }) => name === "pi"),
).toMatchObject({ state: "aligned" });
expect(await systemUninstallHost(home).removeClient(client)).toMatchObject({
name: "pi",
status: "removed",
});
expect(JSON.parse(await readFile(client.configPath, "utf8"))).toEqual({
mcpServers: {},
});
});
it("keeps JSONC tolerance for other dialects while Pi rejects the same text", () => {
const jsonc = `\uFEFF{\n // A comment Pi rejects but OpenCode keeps.\n "mcp": { "other": { "type": "local" }, },\n}\n`;
expect(parseClientConfiguration(jsonc, "opencode").servers).toEqual({
other: { type: "local" },
});
expect(parseClientConfiguration("", "opencode").document).toEqual({});
expect(parseClientConfiguration("\uFEFF", "opencode").document).toEqual({});
expect(() => parseClientConfiguration(jsonc, "pi")).toThrow();
expect(() => parseClientConfiguration("", "pi")).toThrow();
expect(() => parseClientConfiguration("\uFEFF", "pi")).toThrow();
});
});
@@ -0,0 +1,183 @@
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { parse as parseJsonc } from "jsonc-parser";
import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js";
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
import { systemSetupHost } from "../../../src/application/SetupHost.js";
import { supportedClients } from "../../../src/application/SupportedClients.js";
import { systemUninstallHost } from "../../../src/application/Uninstall.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
clearClientLocationEnvironment,
NPX_REGISTRATION_COMMAND,
} from "../../fixtures/clientEnvironment.js";
const command = NPX_REGISTRATION_COMMAND;
beforeEach(clearClientLocationEnvironment);
afterEach(() => vi.unstubAllEnvs());
const qwenPath = (
home: string,
platform: NodeJS.Platform,
env: Parameters<typeof supportedClients>[2] = {},
) =>
supportedClients(home, platform, env).find(
({ name }) => name === "qwen_code",
);
describe("Qwen Code configuration paths", () => {
it("resolves the user settings file and marker directory", () => {
expect(qwenPath("/home/a", "linux")).toEqual({
name: "qwen_code",
displayName: "Qwen Code",
configPath: join("/home/a", ".qwen", "settings.json"),
markerPath: join("/home/a", ".qwen"),
format: "json",
});
expect(qwenPath("/Users/a", "darwin")?.configPath).toBe(
join("/Users/a", ".qwen", "settings.json"),
);
});
it.each([
["", join("/home/a", ".qwen")],
["~", "/home/a"],
["~/profiles/work", join("/home/a", "profiles", "work")],
["~\\profiles\\work", join("/home/a", "profiles", "work")],
["profiles/work", resolve("profiles/work")],
[" profile ", resolve(" profile ")],
["$PROFILE", resolve("$PROFILE")],
])("matches Qwen's QWEN_HOME resolution for %j", (override, directory) => {
vi.stubEnv("QWEN_HOME", override);
const client = qwenPath("/home/a", process.platform, {
QWEN_HOME: override,
});
expect(
supportedClients("/home/a").find(({ name }) => name === "qwen_code"),
).toEqual(client);
expect(client).toMatchObject({
configPath: join(directory, "settings.json"),
markerPath: directory,
});
});
});
describe("Qwen Code client lifecycle", () => {
const qwenClient = async () => {
const home = await createTestTempDirectory("rea-qwen-");
const client = qwenPath(home, process.platform, {});
if (client?.markerPath === undefined)
throw new Error("missing Qwen Code client");
await mkdir(client.markerPath, { recursive: true });
return { home, client };
};
it("registers rea in mcpServers while preserving unrelated settings and comments", async () => {
const { home, client } = await qwenClient();
await writeFile(
client.configPath,
`{
// Keep this note.
"model": { "name": "qwen3-coder-plus" },
"mcpServers": { "other": { "command": "other-server" } }
}
`,
);
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const text = await readFile(client.configPath, "utf8");
expect(text).toContain("// Keep this note.");
expect(parseJsonc(text)).toEqual({
model: { name: "qwen3-coder-plus" },
mcpServers: {
other: { command: "other-server" },
rea: { command: "npx", args: command.slice(1) },
},
});
expect(await configureClientConfiguration(client, {}, command)).toEqual({
status: "unchanged",
});
expect((await systemUninstallHost(home).removeClient(client)).status).toBe(
"removed",
);
const removedText = await readFile(client.configPath, "utf8");
const removed = parseJsonc(removedText);
expect(removed).toEqual({
model: { name: "qwen3-coder-plus" },
mcpServers: { other: { command: "other-server" } },
});
expect(removedText).toContain("// Keep this note.");
});
it("reports a package-runner registration as aligned", async () => {
const { home, client } = await qwenClient();
expect(
(await configureClientConfiguration(client, {}, command)).status,
).toBe("configured");
const entry = resolve("scripts/rea.mjs");
const status = (
await readClientRegistrationStatuses(home, entry, { environment: {} })
).find(({ client: name }) => name === "qwen_code");
expect(status).toMatchObject({ state: "aligned" });
});
});
describe("Qwen Code profile setup", () => {
it.each([false, true])(
"installs and removes the shared skill with a custom home: %s",
async (customHome) => {
const home = await createTestTempDirectory("rea-qwen-profile-");
const profile = join(home, customHome ? "qwen-profile" : ".qwen");
const environment = {
HOME: home,
USERPROFILE: home,
...(customHome ? { QWEN_HOME: profile } : {}),
};
await mkdir(profile);
const setup = systemSetupHost(undefined, environment);
const client = (await setup.detectedClients()).find(
({ name }) => name === "qwen_code",
);
if (client === undefined) throw new Error("missing Qwen Code client");
expect(client.configPath).toBe(join(profile, "settings.json"));
expect(await setup.configureClient(client, {}, command)).toEqual({
status: "configured",
});
expect(await setup.installSkill([client.name])).toBe("installed");
const skill = join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName);
expect(await readFile(join(skill, "SKILL.md"), "utf8")).toContain(
"reverse-engineer-anything",
);
expect(await setup.clientNeedsConfigure(client, {}, command)).toBe(false);
expect(await setup.skillNeedsInstall([client.name])).toBe(false);
expect(await setup.installSkill([client.name])).toBe("unchanged");
expect(
(
await readClientRegistrationStatuses(
home,
resolve("scripts/rea.mjs"),
{ environment },
)
).find(({ client: name }) => name === "qwen_code"),
).toMatchObject({ state: "aligned" });
const uninstall = systemUninstallHost(home, undefined, environment);
const registered = (await uninstall.clients()).find(
({ name }) => name === "qwen_code",
);
expect(registered).toEqual(client);
expect((await uninstall.removeClient(client)).status).toBe("removed");
expect((await uninstall.removeSkill()).status).toBe("removed");
await expect(access(skill)).rejects.toMatchObject({ code: "ENOENT" });
if (customHome)
await expect(access(join(home, ".qwen"))).rejects.toMatchObject({
code: "ENOENT",
});
},
);
});
+11 -8
View File
@@ -13,7 +13,6 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
canonicalSkillNeedsInstall,
claudeCodeSkillsDirectory,
installCanonicalSkill,
} from "../../../src/application/SetupSkill.js";
import {
@@ -56,9 +55,7 @@ describe("canonical skill transaction", () => {
it("installs only the selected Claude Code personal skill", async () => {
const home = await createTestTempDirectory("rea-claude-skill-");
const configDirectory = join(home, "claude-config");
const skillsDirectory = claudeCodeSkillsDirectory(home, {
CLAUDE_CONFIG_DIR: configDirectory,
});
const skillsDirectory = join(configDirectory, "skills");
const claudeSkill = join(
skillsDirectory,
"reverse-engineer-anything/SKILL.md",
@@ -84,13 +81,19 @@ describe("canonical skill transaction", () => {
});
expect(
await canonicalSkillNeedsInstall(home, ["claude_code"], skillsDirectory),
await canonicalSkillNeedsInstall(home, ["claude_code"], {
CLAUDE_CONFIG_DIR: dirname(skillsDirectory),
}),
).toBe(true);
expect(
await installCanonicalSkill(home, ["claude_code"], skillsDirectory),
await installCanonicalSkill(home, ["claude_code"], {
CLAUDE_CONFIG_DIR: dirname(skillsDirectory),
}),
).toBe("installed");
expect(
await canonicalSkillNeedsInstall(home, ["claude_code"], skillsDirectory),
await canonicalSkillNeedsInstall(home, ["claude_code"], {
CLAUDE_CONFIG_DIR: dirname(skillsDirectory),
}),
).toBe(false);
await expect(access(claudeSkill)).resolves.toBeUndefined();
await expect(
@@ -112,7 +115,7 @@ describe("canonical skill transaction", () => {
home,
".agents/skills/reverse-engineer-anything/SKILL.md",
);
const claudeSkills = claudeCodeSkillsDirectory(home);
const claudeSkills = join(home, ".claude", "skills");
const claudeSkill = join(
claudeSkills,
"reverse-engineer-anything/SKILL.md",
+130 -1
View File
@@ -6,7 +6,9 @@ import { z } from "zod";
import { BinaryLayoutService } from "../../../src/application/binaryDiagnostics/BinaryLayoutService.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
import { ok } from "../../../src/domain/result.js";
import {
createJavaScriptApplicationGraph,
@@ -109,6 +111,68 @@ it("advertises exact schemas and projects one layout section from retained Evide
);
});
it("delivers a bounded native dossier view over MCP without a Ghidra provider or lost connection", async () => {
const { client, session } = await connect();
const original = functionDossierSchema.parse(ghidraFunctionDossier());
const parent = createEvidence(
{
path: "/fixtures/oversized-native.exe",
format: "pe",
sha256: "b".repeat(64),
},
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
{
operation: "analyze_function",
parameters: { address: "0x401000" },
result: { ...original, pseudocode: "X".repeat(11 * 1024 * 1024) },
},
);
expect(session.recordEvidence(parent).ok).toBe(true);
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_analysis_view",
);
if (advertised?.outputSchema === undefined)
throw new Error("missing view schemas");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const inputSchema: Record<string, unknown> = advertised.inputSchema;
const outputSchema: Record<string, unknown> = advertised.outputSchema;
const arguments_ = {
source: { kind: "retained-evidence", evidence_id: parent.evidence_id },
view: { kind: "native", facet: "pseudocode", offset: 0, limit: 500 },
};
expect(ajv.validateSchema(inputSchema)).toBe(true);
expect(ajv.validateSchema(outputSchema)).toBe(true);
expect(
ajv.validate(inputSchema, arguments_),
JSON.stringify(ajv.errors),
).toBe(true);
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: arguments_,
});
expect(response.isError).not.toBe(true);
expect(
ajv.validate(outputSchema, response.structuredContent),
JSON.stringify(ajv.errors),
).toBe(true);
const parsed = toolContract("inspect_analysis_view").outputSchema.parse(
response.structuredContent,
);
expect(parsed.normalized_result).toMatchObject({
kind: "native",
parent_evidence_id: parent.evidence_id,
procedure_address: "0x401000",
coverage: { examined: 500, next_offset: 500, total: 11 * 1024 * 1024 },
});
expect(parsed.evidence_links).toEqual([parent.evidence_id]);
expect(parsed.locations).toEqual([
{ kind: "artifact-path", path: "/fixtures/oversized-native.exe" },
{ kind: "address", address: "0x401000" },
]);
expect(JSON.stringify(response.structuredContent).length).toBeLessThan(12000);
await client.ping();
});
it("retains an oversized selected observation and keeps subsequent views usable", async () => {
const { client, session } = await connect();
const analysis = analysisViewJavaScriptAnalysisWithSource();
@@ -185,6 +249,71 @@ it("retains an oversized selected observation and keeps subsequent views usable"
expect(summary.isError).not.toBe(true);
});
it("retains an oversized native assembly row and permits a subsequent smaller view", async () => {
const { client, session } = await connect();
const row = "\0".repeat(1_000_000);
const parent = createEvidence(
{ path: "/fixtures/large-row.exe", format: "pe", sha256: "c".repeat(64) },
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
{
operation: "analyze_function",
parameters: {},
result: {
...functionDossierSchema.parse(ghidraFunctionDossier()),
assembly: [row],
},
},
);
expect(session.recordEvidence(parent).ok).toBe(true);
const source = { kind: "retained-evidence", evidence_id: parent.evidence_id };
const response = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source,
view: { kind: "native", facet: "assembly", offset: 0, limit: 1 },
},
});
expect(response.isError).toBe(true);
const error = z
.object({
error: z.object({
details: z.object({
reported_limits: z.object({
evidence_reference: z.object({
kind: z.literal("retained-evidence"),
evidence_id: z.string(),
}),
}),
}),
}),
})
.parse(parseMcpToolError(response));
const retained = session.evidenceById(
error.error.details.reported_limits.evidence_reference.evidence_id,
);
expect(retained?.normalized_result).toMatchObject({
item: [row],
parent_evidence_id: parent.evidence_id,
});
const next = await client.callTool({
name: "inspect_analysis_view",
arguments: {
source,
view: { kind: "native", facet: "pseudocode", offset: 0, limit: 12 },
},
});
expect(next.isError).not.toBe(true);
expect(
toolContract("inspect_analysis_view").outputSchema.parse(
next.structuredContent,
).normalized_result,
).toMatchObject({
item: { text: "int fixture_" },
parent_evidence_id: parent.evidence_id,
});
await client.ping();
});
it("returns a JavaScript summary without graph payloads from a retained reference", async () => {
const { client, session } = await connect();
const parent = analysisViewJavaScriptEvidence();
@@ -0,0 +1,281 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import { compactAdvertisedInputSchema } from "../../../src/contracts/compactInputSchema.js";
import {
COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
parseMcpInputSchemaProfile,
} from "../../../src/config/mcpInputSchemaProfile.js";
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { ToolResultDelivery } from "../../../src/server/toolResult.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
interface AdvertisedTool {
readonly name: string;
readonly inputSchema: Record<string, unknown>;
readonly outputSchema?: Record<string, unknown> | undefined;
readonly description?: string | undefined;
}
const serializedBytes = (value: unknown): number =>
Buffer.byteLength(JSON.stringify(value), "utf8");
const listToolsThroughTransport = async (
server: EvidenceMcpServer,
): Promise<readonly AdvertisedTool[]> => {
const client = new Client({ name: "compact-profile", version: "0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
return (await client.listTools()).tools;
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
};
const registerCatalog = (server: EvidenceMcpServer): void => {
for (const contract of TOOL_CONTRACTS)
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async () => ({ content: [] }),
);
};
const compactServer = (): EvidenceMcpServer =>
new EvidenceMcpServer(
{ name: "compact-profile", version: "0" },
{ capabilities: {} },
undefined,
new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
{ budgetBytes: COMPACT_INPUT_SCHEMA_BUDGET_BYTES },
);
const fullServer = (): EvidenceMcpServer =>
new EvidenceMcpServer(
{ name: "full-profile", version: "0" },
{ capabilities: {} },
undefined,
new ToolResultDelivery(STDIO_DEFAULT_MAX_BUFFER_SIZE),
);
describe("MCP compact input schema profile", () => {
it("advertises every tool input schema within the provider budget", async () => {
const server = compactServer();
registerCatalog(server);
const tools = await listToolsThroughTransport(server);
expect(tools.map(({ name }) => name).sort()).toEqual(
TOOL_CONTRACTS.map(({ name }) => name).sort(),
);
const oversized = tools.filter(
({ inputSchema }) =>
serializedBytes(inputSchema) > COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
);
expect(oversized.map(({ name }) => name)).toEqual([]);
});
it("keeps output schemas and tool descriptions identical to the default profile", async () => {
const compact = compactServer();
const full = fullServer();
registerCatalog(compact);
registerCatalog(full);
const [compactTools, fullTools] = await Promise.all([
listToolsThroughTransport(compact),
listToolsThroughTransport(full),
]);
const fullByName = new Map(fullTools.map((tool) => [tool.name, tool]));
expect(compactTools.length).toBe(fullTools.length);
for (const tool of compactTools) {
const reference = fullByName.get(tool.name);
if (reference === undefined) throw new Error(`Missing ${tool.name}`);
expect(tool.outputSchema, tool.name).toEqual(reference.outputSchema);
expect(tool.description, tool.name).toBe(reference.description);
}
});
it("keeps compact schemas valid and accepting canonical examples", async () => {
const server = compactServer();
registerCatalog(server);
const tools = await listToolsThroughTransport(server);
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const contractsByName = new Map<string, (typeof TOOL_CONTRACTS)[number]>(
TOOL_CONTRACTS.map((contract) => [contract.name, contract]),
);
for (const tool of tools) {
expect(
ajv.validateSchema(tool.inputSchema),
`${tool.name}: ${ajv.errorsText(ajv.errors)}`,
).toBe(true);
const contract = contractsByName.get(tool.name);
const validate = ajv.compile(tool.inputSchema);
for (const example of contract?.examples ?? [])
expect(validate(example.input), `${tool.name}: ${example.title}`).toBe(
true,
);
}
});
it("reduces at most the structurally oversized tools", async () => {
const full = fullServer();
registerCatalog(full);
const tools = await listToolsThroughTransport(full);
const reduced: string[] = [];
for (const tool of tools) {
const { presentation } = compactAdvertisedInputSchema(
tool.inputSchema,
COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
);
if (presentation === "reduced") reduced.push(tool.name);
}
expect(reduced.sort()).toEqual([
"build_reconstruction_obligation_ledger",
"capture_browser_scenario",
"compare_application_versions",
"compare_web_captures",
"evaluate_reconstruction_coverage",
"project_managed_application_graph",
]);
expect(tools.length).toBe(TOOL_CONTRACTS.length);
});
it("retains parameter types and avoids client-side reference expansion", async () => {
const server = compactServer();
registerCatalog(server);
const tools = await listToolsThroughTransport(server);
for (const tool of tools) {
// Kimi Code 2.1.1 expands references and defaults description-only
// properties to string. Inline schemas with explicit shallow types
// avoid both conversions for the structurally oversized tools.
expect(JSON.stringify(tool.inputSchema), tool.name).not.toContain(
'"$ref":',
);
}
const comparison = tools.find(
({ name }) => name === "compare_managed_members",
);
expect(comparison?.inputSchema.properties).toMatchObject({
left: {
properties: {
normalized_result: {
type: ["null", "boolean", "object", "array", "number", "string"],
},
},
},
});
const ledger = tools.find(
({ name }) => name === "build_reconstruction_obligation_ledger",
);
expect(ledger?.inputSchema.properties).toMatchObject({
evidence_bundle: { type: "object" },
reviewed_obligations: { type: "array" },
manifest: { type: "object" },
});
const coverage = tools.find(
({ name }) => name === "evaluate_reconstruction_coverage",
);
expect(coverage?.inputSchema.properties).toMatchObject({
coverage: { type: "object" },
boundary_id: { type: "string" },
});
});
it("parses the profile selection the server startup reads", () => {
expect(parseMcpInputSchemaProfile("compact")).toEqual({
ok: true,
value: "compact",
});
expect(parseMcpInputSchemaProfile("surprise")).not.toHaveProperty("value");
});
});
describe("MCP compact input schema canonical enforcement", () => {
it("still rejects canonical-invalid arguments the compact advertisement accepts", async () => {
const server = compactServer();
const contract = TOOL_CONTRACTS.find(
({ name }) => name === "capture_process_scenario",
);
if (contract === undefined)
throw new Error("Process capture contract was not registered");
let handlerCalled = false;
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async () => {
handlerCalled = true;
return {
content: [{ type: "text" as const, text: "handler ran" }],
isError: true,
};
},
);
const client = new Client({ name: "compact-validation", version: "0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = (await client.listTools()).tools.find(
({ name }) => name === contract.name,
);
if (advertised === undefined)
throw new Error("Process capture tool was not advertised");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
const validate = ajv.compile(advertised.inputSchema);
const valid = { executable: "node", environment: { APP_MODE: "test" } };
const reserved = {
executable: "node",
environment: { REA_PROCESS_RUN_ID: "caller-value" },
};
expect(validate(valid)).toBe(true);
expect(processScenarioSchema.safeParse(valid).success).toBe(true);
expect(processScenarioSchema.safeParse(reserved).success).toBe(false);
const result = await client.callTool({
name: contract.name,
arguments: reserved,
});
expect(result.isError).toBe(true);
expect(handlerCalled).toBe(false);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
it("compacts plain standard schemas that are not Zod instances", async () => {
// Mirrors registerWebNetworkCaptureTool: a plain standard schema reusing
// the advertised projection while owning its own permissive validator.
const server = compactServer();
const contract = TOOL_CONTRACTS.find(
({ name }) => name === "inspect_web_network_capture",
);
if (contract === undefined)
throw new Error("Network capture contract was not registered");
const registration = toolRegistrationOptions(contract);
const inputSchema = {
"~standard": {
...registration.inputSchema["~standard"],
vendor: "rea-application",
validate: (value: unknown) => ({ value }),
},
};
server.registerTool(
contract.name,
{ ...registration, inputSchema },
async () => ({ content: [] }),
);
const tools = await listToolsThroughTransport(server);
const advertised = tools.find(({ name }) => name === contract.name);
if (advertised === undefined)
throw new Error("Network capture tool was not advertised");
expect(serializedBytes(advertised.inputSchema)).toBeLessThanOrEqual(
COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
);
const ajv = new Ajv2020({ strict: false, validateFormats: false });
expect(ajv.validateSchema(advertised.inputSchema)).toBe(true);
});
});
@@ -0,0 +1,154 @@
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { expect } from "vitest";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
import { javaScriptSemanticTraceResultSchema } from "../../../src/domain/javascript/javascriptSemanticTraceSchemas.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"delivers complete large literals through CLI and default stdio MCP without metadata copies",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-literal-payload-");
const value = 'rea_literal_payload_ğ\\"\0'.padEnd(24, "x").repeat(65_536);
const source = [
`export const payload = ${JSON.stringify(value)};`,
'export const choice = flag ? 1 : "1";',
'export const empty = "";',
].join("\n");
await writeFile(join(root, "main.js"), source);
const cliResponse = await cli.run({
arguments: [
"analyze-javascript-application",
root,
"--artifact-format",
"directory",
"--json",
],
timeoutMs: 60_000,
});
expect(cliResponse.exitCode).toBe(0);
const cliEvidence = toolContract(
"analyze_javascript_application",
).outputSchema.parse(cliResponse.json);
const client = new Client({ name: "literal-payload-e2e", version: "1" });
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: { PATH: process.env.PATH ?? "" },
stderr: "pipe",
});
transport.stderr?.on("data", () => undefined);
try {
await client.connect(transport);
const response = await client.callTool({
name: "analyze_javascript_application",
arguments: { input_path: root, format: "directory" },
});
// The old payload-bearing role key/label exceed the default wire budget.
expect(response.isError).not.toBe(true);
const evidence = toolContract(
"analyze_javascript_application",
).outputSchema.parse(response.structuredContent);
expect(evidence.evidence_id).toBe(cliEvidence.evidence_id);
const text = response.content.find((item) => item.type === "text");
if (text?.type !== "text") throw new Error("Missing MCP text result");
const textEvidence = toolContract(
"analyze_javascript_application",
).outputSchema.parse(JSON.parse(text.text));
expect(textEvidence.evidence_id).toBe(evidence.evidence_id);
const graph = javascriptApplicationAnalysisResultSchema.parse(
evidence.normalized_result,
).semantic_graph;
const literal = graph.nodes.find(
(node) => node.kind === "literal" && node.properties.value === value,
);
if (literal === undefined) throw new Error("Complete literal was lost");
const sourceSha256 = createHash("sha256").update(source).digest("hex");
expect(literal.identity).toMatchObject({
module_path: "main.js",
artifact_sha256: sourceSha256,
});
expect(literal.evidence.location).toMatchObject({
available: true,
value: { kind: "source-range", source: "main.js" },
});
const choices = graph.nodes.filter(
(node) =>
node.kind === "literal" &&
(node.properties.value === 1 || node.properties.value === "1"),
);
expect(choices.length).toBe(2);
expect(new Set(choices.map((node) => node.node_id)).size).toBe(2);
expect(
graph.nodes.some(
(node) => node.kind === "literal" && node.properties.value === "",
),
).toBe(true);
const traceResponse = await client.callTool({
name: "trace_javascript_semantics",
arguments: {
application: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
query: {
seed: { kind: "semantic-node", node_id: literal.node_id },
direction: "backward-provenance",
},
},
});
expect(traceResponse.isError).not.toBe(true);
const traceEvidence = toolContract(
"trace_javascript_semantics",
).outputSchema.parse(traceResponse.structuredContent);
const trace = javaScriptSemanticTraceResultSchema.parse(
traceEvidence.normalized_result,
);
expect(
trace.nodes.some(
(node) =>
node.node_id === literal.node_id && node.properties.value === value,
),
).toBe(true);
const valueTraceResponse = await client.callTool({
name: "trace_javascript_semantics",
arguments: {
application: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
query: {
seed: { kind: "literal", value: "1" },
direction: "backward-provenance",
},
},
});
expect(valueTraceResponse.isError).not.toBe(true);
const valueTraceEvidence = toolContract(
"trace_javascript_semantics",
).outputSchema.parse(valueTraceResponse.structuredContent);
const valueTrace = javaScriptSemanticTraceResultSchema.parse(
valueTraceEvidence.normalized_result,
);
expect(valueTrace.seed_node_ids).toEqual(
choices
.filter((node) => node.properties.value === "1")
.map((node) => node.node_id),
);
await client.ping();
} finally {
await client.close();
await transport.close();
}
},
60_000,
);
+76 -1
View File
@@ -1,4 +1,6 @@
import { readFile } from "node:fs/promises";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { readFile, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -43,6 +45,79 @@ describe("production MCP doctor", () => {
);
}, 30_000);
it("rejects a schema-invalid probe while retaining the discovered inventory", async () => {
const root = await createTestTempDirectory("rea-mcp-doctor-reply-");
const snapshotPath = join(root, "reply.json");
const environment = { PATH: process.env.PATH ?? "" };
const client = new Client({ name: "doctor-reply-capture", version: "1" });
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("scripts/rea.mjs"), "mcp"],
cwd: process.cwd(),
env: environment,
stderr: "pipe",
});
transport.stderr?.on("data", () => undefined);
try {
await client.connect(transport);
const tools = await client.listTools();
const prompts = await client.listPrompts();
const toolDefinition = tools.tools.find(
({ name }) => name === "binary_session",
);
if (toolDefinition === undefined)
throw new Error("Production binary_session contract is missing");
const reply = await client.callTool(
{ name: "binary_session", arguments: {} },
{ toolDefinition },
);
await writeFile(
snapshotPath,
JSON.stringify({
serverInfo: client.getServerVersion(),
protocolVersion: client.getNegotiatedProtocolVersion(),
tools,
prompts,
reply,
}),
);
} finally {
await client.close();
await transport.close();
}
// Replay real production metadata through a synthetic stdio producer.
for (const mode of ["valid", "invalid"]) {
const result = await runProductionMcpDoctor({
command: process.execPath,
args: [
resolve("tests/fixtures/mcpDoctorReply.mjs"),
snapshotPath,
mode,
],
cwd: process.cwd(),
environment,
});
expect(result.healthy).toBe(mode === "valid");
expect(result.inventory?.tools.observed).toBe(
CATALOG_IDENTITY.counts.mcp_tools,
);
expect(result.inventory?.prompts.observed).toBe(
CATALOG_IDENTITY.counts.mcp_prompts,
);
expect(result.checks).toContainEqual({
name: "initialize",
ok: true,
detail: expect.any(String),
});
if (mode === "invalid")
expect(result.checks).toContainEqual({
name: "request-flow",
ok: false,
detail: expect.stringMatching(/output schema/iu),
});
}
}, 30_000);
it("reports exact missing, unexpected, and duplicate inventory names", () => {
expect(compareInventory(["a", "b"], ["b", "c", "c"])).toEqual({
expected: 2,
@@ -0,0 +1,108 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { expect, it } from "vitest";
import { z } from "zod";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { toolOutputSchemaWithMetadata } from "../../../src/contracts/toolSchemaMetadata.js";
const advertised = <
Schema extends z.ZodType<Readonly<Record<string, unknown>>>,
>(
schema: Schema,
): Schema =>
toolOutputSchemaWithMetadata({
...toolContract("binary_session"),
outputSchema: schema,
});
const connect = async (server: McpServer, client: Client): Promise<void> => {
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
};
it("validates changed schemas after catalog refreshes and availability changes", async () => {
const client = new Client({ name: "output-reuse-test", version: "1" });
const server = new McpServer({ name: "output-reuse-fixture", version: "1" });
const schema = advertised(z.strictObject({ state: z.literal("ready") }));
let state = "ready";
const selected = server.registerTool(
"selected",
{ inputSchema: z.strictObject({}), outputSchema: schema },
() => ({ content: [], structuredContent: { state } }),
);
server.registerTool(
"equivalent",
{ inputSchema: z.strictObject({}), outputSchema: schema },
() => ({ content: [], structuredContent: { state: "ready" } }),
);
try {
await connect(server, client);
await client.listTools();
expect(
(await client.callTool({ name: "selected" })).structuredContent,
).toEqual({
state: "ready",
});
await client.listTools();
await client.callTool({ name: "equivalent" });
selected.update({
outputSchema: advertised(z.strictObject({ state: z.literal("updated") })),
});
state = "updated";
await client.listTools();
expect(
(await client.callTool({ name: "selected" })).structuredContent,
).toEqual({
state: "updated",
});
selected.disable();
const unavailable = await client.listTools();
expect(unavailable.tools.some((tool) => tool.name === "selected")).toBe(
false,
);
await expect(client.callTool({ name: "selected" })).rejects.toThrow(
/not found|disabled/iu,
);
await client.callTool({ name: "equivalent" });
selected.enable();
await client.listTools();
await client.callTool({ name: "selected" });
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
});
it("uses the new server's schema after reconnecting the client", async () => {
const client = new Client({ name: "output-reconnect-test", version: "1" });
const servers: McpServer[] = [];
try {
for (const state of ["first", "second"]) {
const server = new McpServer({ name: `fixture-${state}`, version: "1" });
servers.push(server);
server.registerTool(
"selected",
{
inputSchema: z.strictObject({}),
outputSchema: advertised(z.strictObject({ state: z.literal(state) })),
},
() => ({ content: [], structuredContent: { state } }),
);
await connect(server, client);
await client.listTools();
expect(
(await client.callTool({ name: "selected" })).structuredContent,
).toEqual({ state });
await client.close();
await server.close();
}
} finally {
await Promise.allSettled([
client.close(),
...servers.map((server) => server.close()),
]);
}
});
@@ -43,12 +43,14 @@ const exerciseDeliveryFailure = async (
recordEvidence,
delivery,
);
server.registerTool("large_failure", { inputSchema: {} }, async () =>
oversizedFailure(),
server.registerTool(
"large_failure",
{ inputSchema: z.object({}) },
async () => oversizedFailure(),
);
server.registerTool(
"healthy",
{ inputSchema: {} },
{ inputSchema: z.object({}) },
async (): Promise<CallToolResult> => ({
content: [{ type: "text", text: "still connected" }],
}),
@@ -161,7 +163,7 @@ it("delivers an error whose text fits although structured and text copies would
},
delivery,
);
server.registerTool("mid_failure", { inputSchema: {} }, async () =>
server.registerTool("mid_failure", { inputSchema: z.object({}) }, async () =>
failureWithName(nameBytes),
);
const client = new Client({ name: "mid-sized-error-client", version: "1" });
+12 -9
View File
@@ -117,7 +117,7 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
expect(advertised.get(name), name).toMatchObject({ annotations });
}
function expectRecursivePropertyDescriptions(
function expectMeaningfulPropertyDescriptions(
schema: unknown,
path: string,
root: unknown = schema,
@@ -125,7 +125,7 @@ function expectRecursivePropertyDescriptions(
): void {
if (!isRecord(schema)) return;
if (typeof schema.$ref === "string" && !active.has(schema.$ref))
expectRecursivePropertyDescriptions(
expectMeaningfulPropertyDescriptions(
resolveReference(root, schema.$ref),
`${path}.${schema.$ref}`,
root,
@@ -133,10 +133,13 @@ function expectRecursivePropertyDescriptions(
);
if (isRecord(schema.properties)) {
for (const [property, child] of Object.entries(schema.properties)) {
expect(child, `${path}.${property}`).toMatchObject({
description: expect.any(String),
});
expectRecursivePropertyDescriptions(
// Omit a description rather than restate the property name.
const description = isRecord(child) ? child.description : undefined;
if (description !== undefined)
expect(description, `${path}.${property}`).toEqual(
expect.not.stringMatching(/^(?:Value for .*)?$/u),
);
expectMeaningfulPropertyDescriptions(
child,
`${path}.${property}`,
root,
@@ -147,12 +150,12 @@ function expectRecursivePropertyDescriptions(
for (const key of ["items", "additionalProperties"])
if (schema[key] !== undefined)
expectRecursivePropertyDescriptions(schema[key], path, root, active);
expectMeaningfulPropertyDescriptions(schema[key], path, root, active);
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
const children = schema[key];
if (Array.isArray(children))
children.forEach((child: unknown, index: number) =>
expectRecursivePropertyDescriptions(
expectMeaningfulPropertyDescriptions(
child,
`${path}.${key}[${index}]`,
root,
@@ -358,7 +361,7 @@ describe("MCP JSON Schema validity", () => {
contract.inputSchema.safeParse(example.input).success,
`${contract.name}: ${example.title}`,
).toBe(true);
expectRecursivePropertyDescriptions(tool?.inputSchema, contract.name);
expectMeaningfulPropertyDescriptions(tool?.inputSchema, contract.name);
}
} finally {
await Promise.allSettled([client.close(), server.close()]);
@@ -11,6 +11,7 @@ import {
parseProcessScenario,
} from "../../../src/domain/process/processScenario.js";
import { parseProcessCapture } from "../../../src/domain/process/processCaptureParsing.js";
import { compareProcessCaptures } from "../../../src/domain/process/processComparison.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { itWithCaptureCapability } from "./processCaptureCapability.js";
@@ -64,7 +65,11 @@ itWithCaptureCapability(
).toBe(true);
expect(capture.manifest.comparison_contract).toMatchObject({
port_normalization_version: "contextual-endpoints-v2",
rendered_line_format: "trailing-spaces-trimmed-v1",
});
expect(capture.manifest.comparison_contract).not.toHaveProperty(
"pattern_normalization_version",
);
expect(capture.exit).toMatchObject({ code: 0, reason: "exited" });
expect(capture.cleanup).toMatchObject({
owned_process_group: "verified",
@@ -73,6 +78,67 @@ itWithCaptureCapability(
},
);
itWithCaptureCapability.each([
{ pattern: "AB", replacement: "$&$&", expected: "$&$&" },
{
pattern: "AB",
replacement: "$$ $` $' $1",
expected: "$$ $` $' $1",
},
{ pattern: "", replacement: "-", expected: "-A-B-" },
])(
"preserves literal replacement $replacement and rejects legacy comparison semantics",
async ({ pattern, replacement, expected }) => {
const root = await createTestTempDirectory("rea-process-literal-");
const scenario = parseProcessScenario({
executable: process.execPath,
arguments: ["-e", 'process.stdout.write("AB")'],
working_directory: root,
normalization: {
paths: false,
pids: false,
ports: false,
patterns: [{ pattern, replacement }],
},
settle_ms: 100,
});
const result = await captureProcessScenario(scenario);
if (!result.ok) throw result.error;
const capture = parseProcessCapture(
createProcessCaptureEvidence(scenario, result.value).normalized_result,
);
expect(capture.frames.map(({ data }) => data).join("")).toBe(expected);
expect(
capture.frames.map(({ raw_data, data }) => raw_data ?? data).join(""),
).toBe("AB");
expect(capture.cleanup).toMatchObject({
owned_process_group: "verified",
temporary_root: "removed",
});
expect(compareProcessCaptures(capture, capture).terminal).toBe("unchanged");
const legacyContract = { ...capture.manifest.comparison_contract };
delete legacyContract.pattern_normalization_version;
const legacy = parseProcessCapture({
...capture,
manifest: {
...capture.manifest,
comparison_contract: legacyContract,
comparison_contract_sha256: digestProcessCommitment(legacyContract),
},
});
expect(() => compareProcessCaptures(legacy, capture)).toThrow(
expect.objectContaining({
issues: [
expect.objectContaining({
expected: ["pattern_normalization_version"],
}),
],
}),
);
},
20_000,
);
itWithLinuxCaptureCapability.each([false, true])(
"honors pids=%s in owned Linux capture samples and committed Evidence",
async (pids) => {
@@ -1,4 +1,5 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
@@ -7,6 +8,7 @@ import { expect, it, onTestFinished } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { compareProcessCaptures } from "../../../src/domain/process/processComparison.js";
import { parseProcessCapture } from "../../../src/domain/process/processCaptureParsing.js";
import { parseProcessScenario } from "../../../src/domain/process/processScenario.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
@@ -58,6 +60,108 @@ const captureViaMcp = async (scenario: Record<string, unknown>) => {
return evidence;
};
itWithCaptureCapability.each(["cli", "mcp"] as const)(
"hashes the documented complete report despite omitted terminal output through %s",
async (adapter) => {
const document = await readFile("docs/process-capture.md", "utf8");
const example = document
.split("## Hash a report independently of terminal output")[1]
?.match(/```json\n([\s\S]*?)\n```/u)?.[1];
if (example === undefined)
throw new Error("Missing report capture example");
const scenario = parseProcessScenario(JSON.parse(example));
const root = await createTestTempDirectory("rea-full-report-adapter-");
const evidence = await (adapter === "cli" ? captureViaCli : captureViaMcp)({
...scenario,
executable: process.execPath,
working_directory: root,
filesystem_observation_paths: [join(root, "reports")],
});
const capture = parseProcessCapture(evidence.normalized_result);
const bytes = await readFile(join(root, "reports", "final.json"));
expect(JSON.parse(bytes.toString())).toEqual({
status: "complete",
data: "X".repeat(131072),
});
expect(bytes.length).toBeGreaterThan(scenario.limits.output_bytes);
expect(capture.files_after).toContainEqual(
expect.objectContaining({
path: "root_0:final.json",
size: bytes.length,
sha256: createHash("sha256").update(bytes).digest("hex"),
}),
);
expect(capture.truncation_details.filesystem_after).toMatchObject({
enumeration_truncated: false,
hash_budget_bytes: scenario.limits.file_bytes,
hashed_bytes: bytes.length,
hash_omissions: [],
});
expect(capture.truncation_details.raw_terminal.retained_bytes).toBeLessThan(
capture.truncation_details.raw_terminal.observed_bytes,
);
},
20_000,
);
itWithCaptureCapability.each(["cli", "mcp"] as const)(
"accounts for exact cumulative hash budgets independently at each %s checkpoint",
async (adapter) => {
const runCapture = adapter === "cli" ? captureViaCli : captureViaMcp;
for (const shortfall of [0, 1]) {
const root = await createTestTempDirectory("rea-report-cumulative-");
const periodic = Buffer.from('{"status":"running"}');
const final = Buffer.from('{"status":"complete"}');
await writeFile(join(root, "periodic.json"), periodic);
const budget = periodic.length + final.length - shortfall;
const evidence = await runCapture({
executable: process.execPath,
arguments: [
"-e",
"require('node:fs').writeFileSync('final.json','{\"status\":\"complete\"}')",
],
working_directory: root,
filesystem_observation_paths: [root],
limits: { output_bytes: 1, file_bytes: budget },
});
const capture = parseProcessCapture(evidence.normalized_result);
expect(capture.truncation_details.filesystem_before).toMatchObject({
hashed_bytes: periodic.length,
hash_omissions: [],
});
expect(capture.files_after).toContainEqual(
expect.objectContaining({
path: "root_0:final.json",
sha256: createHash("sha256").update(final).digest("hex"),
}),
);
expect(capture.truncation_details.filesystem_after).toMatchObject({
enumeration_truncated: false,
hashed_bytes: final.length + (shortfall === 0 ? periodic.length : 0),
hash_omissions:
shortfall === 0
? []
: [
{
path: "root_0:periodic.json",
reason: "file_bytes_budget",
remaining_budget_bytes: periodic.length - 1,
},
],
});
expect(
capture.files_after.find(({ path }) => path === "root_0:periodic.json")
?.sha256,
).toBe(
shortfall === 0
? createHash("sha256").update(periodic).digest("hex")
: null,
);
}
},
20_000,
);
itWithCaptureCapability.each(["cli", "mcp"] as const)(
"reports unknown absence instead of deletion in truncated %s capture Evidence",
async (adapter) => {
@@ -60,6 +60,18 @@ describe("artifact archive inventory", () => {
expect(inspectionEvidence.evidence_links).toEqual(
inspection.evidence_links,
);
// The graph is delivered once, in the nested inventory Evidence.
expect(
artifactInventoryResultSchema.parse(
inspection.substeps[0]?.evidence.normalized_result,
).occurrences,
).toHaveLength(3);
// Occurrences name every logical path; neither Evidence repeats them.
expect(inspectionEvidence.locations).toEqual([]);
expect(inspection.substeps[0]?.evidence.locations).toEqual([]);
expect(inspection.observations.map(({ kind }) => kind)).toEqual([
"root-manifest",
]);
const cancellation = new AbortController();
cancellation.abort();
await expect(
@@ -1,4 +1,4 @@
import { readFile, writeFile } from "node:fs/promises";
import { lstat, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
@@ -9,6 +9,8 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
import { createDirectAnalysis } from "../../../../src/composition/directAnalysis.js";
import {
ArtifactPathRegistry,
destinationCaseCollisionMessage,
ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION,
normalizeArtifactPath,
} from "../../../../src/artifacts/ArtifactPaths.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
@@ -18,6 +20,7 @@ import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGr
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import { parseEvidence } from "../../../../src/domain/evidence.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
const { runProviderAnalysis } = createDirectAnalysis({});
@@ -95,17 +98,8 @@ describe("artifact archive safety", () => {
});
const registry = new ArtifactPathRegistry();
registry.add("A.js", "file");
let collisionError: unknown;
try {
registry.add("a.js", "file");
} catch (error: unknown) {
collisionError = error;
}
expect(collisionError).toBeInstanceOf(ArtifactReaderFailure);
expect(collisionError).toMatchObject({
reason: "path",
message: "Artifact path collision: a.js differs only in case from A.js",
});
expect(() => registry.add("a.js", "file")).not.toThrow();
expect(() => registry.add("A.js", "file")).toThrow(ArtifactReaderFailure);
for (const [filePath, childPath] of [
["Foo", "foo/bar"],
@@ -113,11 +107,15 @@ describe("artifact archive safety", () => {
] as const) {
const casePrefixRegistry = new ArtifactPathRegistry();
casePrefixRegistry.add(filePath, "file");
expect(() => casePrefixRegistry.add(childPath, "file")).toThrow(
ArtifactReaderFailure,
);
expect(() => casePrefixRegistry.add(childPath, "file")).not.toThrow();
}
const exactPrefixRegistry = new ArtifactPathRegistry();
exactPrefixRegistry.add("Foo", "file");
expect(() => exactPrefixRegistry.add("Foo/bar", "file")).toThrow(
ArtifactReaderFailure,
);
const sameDirectoryRegistry = new ArtifactPathRegistry();
sameDirectoryRegistry.add("Foo/one.js", "file");
expect(() => sameDirectoryRegistry.add("Foo/two.js", "file")).not.toThrow();
@@ -126,8 +124,64 @@ describe("artifact archive safety", () => {
caseVariantDirectoryRegistry.add("Foo/one.js", "file");
expect(() =>
caseVariantDirectoryRegistry.add("foo/two.js", "file"),
).toThrow(ArtifactReaderFailure);
).not.toThrow();
});
it("names a destination case collision from the directory listing", () => {
expect(
destinationCaseCollisionMessage("res/2f.xml", ["2F.xml", "other.xml"]),
).toBe(
"Destination filesystem cannot store both res/2f.xml and res/2F.xml; inventory retains both logical names.",
);
expect(
destinationCaseCollisionMessage("res/2f.xml", ["2f.xml", "2F.xml"]),
).toBeUndefined();
});
});
it("extracts case-distinct names only when the destination can preserve them", async () => {
const root = await createTestTempDirectory("rea-case-distinct-zip-");
await writeFile(join(root, "case-probe"), "lower");
await writeFile(join(root, "CASE-PROBE"), "upper");
const caseSensitive =
(await readFile(join(root, "case-probe"), "utf8")) === "lower";
const path = join(root, "fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
await writer.add("Main.js", new TextReader("upper"));
await writer.add("main.js", new TextReader("lower"));
await writeFile(path, await writer.close());
const parsed = await parseBinaryTarget(path);
if (!parsed.ok) throw parsed.error;
const result = await inventory(parsed.value);
expect(result.limitations).toContain(
ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION,
);
expect(
result.occurrences
.filter(({ logical_path }) => logical_path !== ".")
.map(({ logical_path }) => logical_path)
.sort(),
).toEqual(["Main.js", "main.js"]);
const output = join(root, "output");
const extracted = await new ArtifactProvider(process.env)
.createClient(parsed.value)
.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({ output_root: output }),
);
if (!caseSensitive) {
if (extracted.ok) throw new Error("expected a destination case collision");
expect(projectAnalysisError(extracted.error)).toMatchObject({
message:
"Destination filesystem cannot store both main.js and Main.js; inventory retains both logical names.",
details: { operation: "extract_artifact", reason: "path" },
});
await expect(lstat(output)).rejects.toMatchObject({ code: "ENOENT" });
return;
}
if (!extracted.ok) throw extracted.error;
expect(await readFile(join(output, "Main.js"), "utf8")).toBe("upper");
expect(await readFile(join(output, "main.js"), "utf8")).toBe("lower");
});
const inventory = async (targetValue: BinaryTarget) => {
const result = await new ArtifactProvider(process.env)
@@ -65,7 +65,7 @@ describe("artifact directory inventory", () => {
expect.objectContaining({
relation: "maps-source",
parent_artifact_id: script?.artifact_id,
child_artifact_id: sourceMap?.artifact_id,
occurrence_id: sourceMap?.occurrence_id,
}),
]),
);
@@ -65,6 +65,8 @@ describe("artifact extraction", () => {
]),
extraction_manifest: { output_root_alias: "$OUTPUT_ROOT" },
});
// artifacts names every extracted path; the Evidence does not repeat them.
expect(result.value.locations).toEqual([]);
expect(await readFile(join(output, "assets", "selected.js"), "utf8")).toBe(
"selected();\n",
);
@@ -6,30 +6,73 @@ import { writeOrderedZip } from "../../../fixtures/artifactEntryOrder.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
import {
destinationCaseCollisionMessage,
ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION,
} from "../../../../src/artifacts/ArtifactPaths.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { artifactInventoryResultSchema } from "../../../../src/domain/artifactGraph.js";
import { ArtifactOperationError } from "../../../../src/domain/artifactOperationError.js";
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
it.each([
[
["Main.js", "main.js"],
"Artifact path collision: main.js differs only in case from Main.js",
],
[["a\\b.js"], 'Artifact path is absolute or unsafe: "a\\\\b.js"'],
] as const)(
"reports the failed path constraint for %j",
async (entries, detail) => {
const root = await createTestTempDirectory("rea-artifact-detail-");
const path = join(root, "fixture.zip");
await writeOrderedZip(path, entries);
const target = await parseBinaryTarget(path);
if (!target.ok) throw new Error("expected a ZIP target");
const result = await new ArtifactProvider(process.env)
.createClient(target.value)
.execute("inventory_artifact", {});
if (result.ok) throw new Error("expected the path constraint to fail");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "artifact_operation_failed",
details: { operation: "inventory_artifact", reason: "path", detail },
});
},
);
it("keeps logical names that differ only in case and records the limitation", async () => {
const root = await createTestTempDirectory("rea-artifact-detail-");
const path = join(root, "fixture.zip");
await writeOrderedZip(path, ["Main.js", "main.js"]);
const target = await parseBinaryTarget(path);
if (!target.ok) throw new Error("expected a ZIP target");
const result = await new ArtifactProvider(process.env)
.createClient(target.value)
.execute("inventory_artifact", {});
if (!result.ok) throw result.error;
const inventory = artifactInventoryResultSchema.parse(result.value.result);
expect(inventory.occurrences.map(({ logical_path }) => logical_path)).toEqual(
expect.arrayContaining(["Main.js", "main.js"]),
);
expect(inventory.limitations).toContain(
ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION,
);
for (const logicalPath of ["Main.js", "main.js"]) {
expect(
inventory.occurrences
.find((occurrence) => occurrence.logical_path === logicalPath)
?.limitations.join("\n"),
).toContain("English (en-US) Unicode case folding");
}
});
it("reports an unsafe path as a hostile artifact path", async () => {
const root = await createTestTempDirectory("rea-artifact-detail-");
const path = join(root, "fixture.zip");
await writeOrderedZip(path, ["a\\b.js"]);
const target = await parseBinaryTarget(path);
if (!target.ok) throw new Error("expected a ZIP target");
const result = await new ArtifactProvider(process.env)
.createClient(target.value)
.execute("inventory_artifact", {});
if (result.ok) throw new Error("expected the path constraint to fail");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "artifact_operation_failed",
message:
"Artifact contains an unsafe internal path. Inspect the reported path and correct the artifact before retrying.",
details: {
operation: "inventory_artifact",
reason: "path",
detail: 'Artifact path is absolute or unsafe: "a\\\\b.js"',
},
});
});
it("returns a destination case collision as the user-facing path message", () => {
const detail = destinationCaseCollisionMessage("res/2f.xml", ["2F.xml"]);
expect(detail).toEqual(expect.any(String));
if (detail === undefined) return;
expect(
projectAnalysisError(
new ArtifactOperationError("extract_artifact", "path", undefined, detail),
),
).toMatchObject({
message: detail,
details: { reason: "path", detail },
});
});
@@ -552,6 +552,43 @@ describe("native macOS provider inspection", () => {
});
});
describe("native macOS provider raw results", () => {
it("records command provenance once, in the normalized result", async () => {
directory = await createTestTempDirectory("rea-native-");
const app = join(directory, "Fixture.app");
const executable = join(app, "Contents/MacOS/Fixture");
await mkdir(join(app, "Contents/MacOS"), { recursive: true });
await writeFile(executable, "fixture");
await writeFile(join(app, "Contents/Info.plist"), "fixture");
const client = new NativeMacOSProvider(
{},
new FixtureRunner(),
"darwin",
).createClient(await nativeMachoTargetForFile(executable, app));
const requests: readonly (readonly [
Parameters<typeof client.execute>[0],
Parameters<typeof client.execute>[1],
])[] = [
["inspect_macho", {}],
["list_architectures", {}],
["inspect_signature", {}],
["inspect_plist", {}],
["demangle_swift", { symbols: ["$s4Test3fooyyF", "plain_symbol"] }],
];
for (const [operation, parameters] of requests) {
const execution = await client.execute(operation, parameters);
if (!execution.ok) throw execution.error;
expect(execution.value.rawResult, operation).toBeNull();
expect(execution.value.result, operation).toMatchObject({
provenance: expect.arrayContaining([
expect.objectContaining({ tool: expect.any(String) }),
]),
});
}
});
});
describe("native plist defaults for iOS-style bundles", () => {
it("defaults to the Info.plist the bundle program was resolved from", async () => {
directory = await createTestTempDirectory("rea-native-flat-");